Merge branch 'refs/heads/trunk' into modularity-module-migration

# Conflicts:
#	composer.lock
#	modules/ppcp-axo/src/AxoModule.php
#	modules/ppcp-blocks/src/BlocksModule.php
#	modules/ppcp-compat/src/CompatModule.php
#	modules/ppcp-googlepay/src/GooglepayModule.php
#	modules/ppcp-order-tracking/src/OrderTrackingModule.php
#	modules/ppcp-wc-subscriptions/src/WcSubscriptionsModule.php
This commit is contained in:
Moritz Meißelbach 2024-08-23 14:25:36 +02:00
commit 4d9f23e315
No known key found for this signature in database
GPG key ID: 9FDCE7BEB31FA3E5
301 changed files with 33875 additions and 13196 deletions

View file

@ -20,6 +20,9 @@ return array(
'wcgateway.settings.fields' => function ( array $fields, ContainerInterface $container ): array {
// Used in various places to mark fields for the preview button.
$apm_name = 'GooglePay';
// Eligibility check.
if ( ! $container->has( 'googlepay.eligible' ) || ! $container->get( 'googlepay.eligible' ) ) {
return $fields;
@ -133,7 +136,7 @@ return array(
'gateway' => 'dcc',
'requirements' => array(),
'custom_attributes' => array(
'data-ppcp-display' => wp_json_encode(
'data-ppcp-display' => wp_json_encode(
array(
$display_manager
->rule()
@ -142,64 +145,79 @@ return array(
->action_visible( 'googlepay_button_color' )
->action_visible( 'googlepay_button_language' )
->action_visible( 'googlepay_button_shipping_enabled' )
->action_visible( 'googlepay_button_preview' )
->action_class( 'googlepay_button_enabled', 'active' )
->to_array(),
)
),
'data-ppcp-apm-name' => $apm_name,
'data-ppcp-field-name' => 'is_enabled',
),
'classes' => array( 'ppcp-valign-label-middle', 'ppcp-align-label-center' ),
),
'googlepay_button_type' => array(
'title' => __( 'Button Label', 'woocommerce-paypal-payments' ),
'type' => 'select',
'desc_tip' => true,
'description' => __(
'title' => __( 'Button Label', 'woocommerce-paypal-payments' ),
'type' => 'select',
'desc_tip' => true,
'description' => __(
'This controls the label of the Google Pay button.',
'woocommerce-paypal-payments'
),
'classes' => array( 'ppcp-field-indent' ),
'class' => array(),
'input_class' => array( 'wc-enhanced-select' ),
'default' => 'pay',
'options' => PropertiesDictionary::button_types(),
'screens' => array( State::STATE_ONBOARDED ),
'gateway' => 'dcc',
'requirements' => array(),
'classes' => array( 'ppcp-field-indent' ),
'class' => array(),
'input_class' => array( 'wc-enhanced-select' ),
'default' => 'pay',
'options' => PropertiesDictionary::button_types(),
'screens' => array( State::STATE_ONBOARDED ),
'gateway' => 'dcc',
'requirements' => array(),
'custom_attributes' => array(
'data-ppcp-apm-name' => $apm_name,
'data-ppcp-field-name' => 'type',
),
),
'googlepay_button_color' => array(
'title' => __( 'Button Color', 'woocommerce-paypal-payments' ),
'type' => 'select',
'desc_tip' => true,
'description' => __(
'title' => __( 'Button Color', 'woocommerce-paypal-payments' ),
'type' => 'select',
'desc_tip' => true,
'description' => __(
'Google Pay payment buttons exist in two styles: dark and light. To provide contrast, use dark buttons on light backgrounds and light buttons on dark or colorful backgrounds.',
'woocommerce-paypal-payments'
),
'label' => '',
'input_class' => array( 'wc-enhanced-select' ),
'classes' => array( 'ppcp-field-indent' ),
'class' => array(),
'default' => 'black',
'options' => PropertiesDictionary::button_colors(),
'screens' => array( State::STATE_ONBOARDED ),
'gateway' => 'dcc',
'requirements' => array(),
'label' => '',
'input_class' => array( 'wc-enhanced-select' ),
'classes' => array( 'ppcp-field-indent' ),
'class' => array(),
'default' => 'black',
'options' => PropertiesDictionary::button_colors(),
'screens' => array( State::STATE_ONBOARDED ),
'gateway' => 'dcc',
'requirements' => array(),
'custom_attributes' => array(
'data-ppcp-apm-name' => $apm_name,
'data-ppcp-field-name' => 'color',
),
),
'googlepay_button_language' => array(
'title' => __( 'Button Language', 'woocommerce-paypal-payments' ),
'type' => 'select',
'desc_tip' => true,
'description' => __(
'title' => __( 'Button Language', 'woocommerce-paypal-payments' ),
'type' => 'select',
'desc_tip' => true,
'description' => __(
'The language and region used for the displayed Google Pay button. The default value is the current language and region setting in a browser.',
'woocommerce-paypal-payments'
),
'classes' => array( 'ppcp-field-indent' ),
'class' => array(),
'input_class' => array( 'wc-enhanced-select' ),
'default' => 'en',
'options' => PropertiesDictionary::button_languages(),
'screens' => array( State::STATE_ONBOARDED ),
'gateway' => 'dcc',
'requirements' => array(),
'classes' => array( 'ppcp-field-indent' ),
'class' => array(),
'input_class' => array( 'wc-enhanced-select' ),
'default' => 'en',
'options' => PropertiesDictionary::button_languages(),
'screens' => array( State::STATE_ONBOARDED ),
'gateway' => 'dcc',
'requirements' => array(),
'custom_attributes' => array(
'data-ppcp-apm-name' => $apm_name,
'data-ppcp-field-name' => 'language',
),
),
'googlepay_button_shipping_enabled' => array(
'title' => __( 'Shipping Callback', 'woocommerce-paypal-payments' ),
@ -209,13 +227,28 @@ return array(
'Synchronizes your available shipping options with Google Pay. Enabling this may impact the buyer experience.',
'woocommerce-paypal-payments'
),
'classes' => array( 'ppcp-field-indent' ),
'classes' => array( 'ppcp-field-indent ppcp' ),
'label' => __( 'Enable Google Pay shipping callback', 'woocommerce-paypal-payments' ),
'default' => 'no',
'screens' => array( State::STATE_ONBOARDED ),
'gateway' => 'dcc',
'requirements' => array(),
),
'googlepay_button_preview' => array(
'type' => 'ppcp-preview',
'preview' => array(
'id' => 'ppcp' . $apm_name . 'ButtonPreview',
'type' => 'button',
'message' => __( 'Button Styling Preview', 'woocommerce-paypal-payments' ),
'apm' => $apm_name,
'single' => true,
),
'screens' => array(
State::STATE_ONBOARDED,
),
'requirements' => array(),
'gateway' => 'dcc',
),
)
);
},

View file

@ -1,5 +1,11 @@
.ppcp-button-googlepay {
min-height: 40px;
.gpay-card-info-container,
.gpay-button {
outline-offset: -1px;
border-radius: var(--apm-button-border-radius);
}
}
.wp-block-woocommerce-checkout, .wp-block-woocommerce-cart {
@ -7,3 +13,7 @@
min-width: 0 !important;
}
}
#ppc-button-ppcp-googlepay {
display: none;
}

View file

@ -1,78 +1,68 @@
import ErrorHandler from "../../../../ppcp-button/resources/js/modules/ErrorHandler";
import CartActionHandler
from "../../../../ppcp-button/resources/js/modules/ActionHandler/CartActionHandler";
import ErrorHandler from '../../../../ppcp-button/resources/js/modules/ErrorHandler';
import CartActionHandler from '../../../../ppcp-button/resources/js/modules/ActionHandler/CartActionHandler';
class BaseHandler {
constructor( buttonConfig, ppcpConfig, externalHandler ) {
this.buttonConfig = buttonConfig;
this.ppcpConfig = ppcpConfig;
this.externalHandler = externalHandler;
}
constructor(buttonConfig, ppcpConfig, externalHandler) {
this.buttonConfig = buttonConfig;
this.ppcpConfig = ppcpConfig;
this.externalHandler = externalHandler;
}
validateContext() {
if ( this.ppcpConfig?.locations_with_subscription_product?.cart ) {
return false;
}
return true;
}
validateContext() {
if ( this.ppcpConfig?.locations_with_subscription_product?.cart ) {
return false;
}
return true;
}
shippingAllowed() {
// Status of the shipping settings in WooCommerce.
return this.buttonConfig.shipping.configured;
}
shippingAllowed() {
return true;
}
transactionInfo() {
return new Promise( ( resolve, reject ) => {
fetch( this.ppcpConfig.ajax.cart_script_params.endpoint, {
method: 'GET',
credentials: 'same-origin',
} )
.then( ( result ) => result.json() )
.then( ( result ) => {
if ( ! result.success ) {
return;
}
transactionInfo() {
return new Promise((resolve, reject) => {
// handle script reload
const data = result.data;
fetch(
this.ppcpConfig.ajax.cart_script_params.endpoint,
{
method: 'GET',
credentials: 'same-origin',
}
)
.then(result => result.json())
.then(result => {
if (! result.success) {
return;
}
resolve( {
countryCode: data.country_code,
currencyCode: data.currency_code,
totalPriceStatus: 'FINAL',
totalPrice: data.total_str,
} );
} );
} );
}
// handle script reload
const data = result.data;
createOrder() {
return this.actionHandler().configuration().createOrder( null, null );
}
resolve({
countryCode: data.country_code,
currencyCode: data.currency_code,
totalPriceStatus: 'FINAL',
totalPrice: data.total_str
});
approveOrder( data, actions ) {
return this.actionHandler().configuration().onApprove( data, actions );
}
});
});
}
createOrder() {
return this.actionHandler().configuration().createOrder(null, null);
}
approveOrder(data, actions) {
return this.actionHandler().configuration().onApprove(data, actions);
}
actionHandler() {
return new CartActionHandler(
this.ppcpConfig,
this.errorHandler(),
);
}
errorHandler() {
return new ErrorHandler(
this.ppcpConfig.labels.error.generic,
document.querySelector('.woocommerce-notices-wrapper')
);
}
actionHandler() {
return new CartActionHandler( this.ppcpConfig, this.errorHandler() );
}
errorHandler() {
return new ErrorHandler(
this.ppcpConfig.labels.error.generic,
document.querySelector( '.woocommerce-notices-wrapper' )
);
}
}
export default BaseHandler;

View file

@ -1,15 +1,13 @@
import BaseHandler from "./BaseHandler";
import BaseHandler from './BaseHandler';
class CartBlockHandler extends BaseHandler {
createOrder() {
return this.externalHandler.createOrder();
}
createOrder() {
return this.externalHandler.createOrder();
}
approveOrder(data, actions) {
return this.externalHandler.onApprove(data, actions);
}
approveOrder( data, actions ) {
return this.externalHandler.onApprove( data, actions );
}
}
export default CartBlockHandler;

View file

@ -1,7 +1,5 @@
import BaseHandler from "./BaseHandler";
import BaseHandler from './BaseHandler';
class CartHandler extends BaseHandler {
}
class CartHandler extends BaseHandler {}
export default CartHandler;

View file

@ -1,19 +1,13 @@
import BaseHandler from "./BaseHandler";
import BaseHandler from './BaseHandler';
class CheckoutBlockHandler extends BaseHandler{
shippingAllowed() {
return false;
}
createOrder() {
return this.externalHandler.createOrder();
}
approveOrder(data, actions) {
return this.externalHandler.onApprove(data, actions);
}
class CheckoutBlockHandler extends BaseHandler {
createOrder() {
return this.externalHandler.createOrder();
}
approveOrder( data, actions ) {
return this.externalHandler.onApprove( data, actions );
}
}
export default CheckoutBlockHandler;

View file

@ -1,64 +1,64 @@
import Spinner from "../../../../ppcp-button/resources/js/modules/Helper/Spinner";
import BaseHandler from "./BaseHandler";
import CheckoutActionHandler
from "../../../../ppcp-button/resources/js/modules/ActionHandler/CheckoutActionHandler";
import FormValidator from "../../../../ppcp-button/resources/js/modules/Helper/FormValidator";
import Spinner from '../../../../ppcp-button/resources/js/modules/Helper/Spinner';
import BaseHandler from './BaseHandler';
import CheckoutActionHandler from '../../../../ppcp-button/resources/js/modules/ActionHandler/CheckoutActionHandler';
import FormValidator from '../../../../ppcp-button/resources/js/modules/Helper/FormValidator';
class CheckoutHandler extends BaseHandler {
validateForm() {
return new Promise( async ( resolve, reject ) => {
try {
const spinner = new Spinner();
const errorHandler = this.errorHandler();
shippingAllowed() {
return false;
}
const formSelector =
this.ppcpConfig.context === 'checkout'
? 'form.checkout'
: 'form#order_review';
const formValidator = this.ppcpConfig
.early_checkout_validation_enabled
? new FormValidator(
this.ppcpConfig.ajax.validate_checkout.endpoint,
this.ppcpConfig.ajax.validate_checkout.nonce
)
: null;
transactionInfo() {
return new Promise(async (resolve, reject) => {
if ( ! formValidator ) {
resolve();
return;
}
try {
const spinner = new Spinner();
const errorHandler = this.errorHandler();
formValidator
.validate( document.querySelector( formSelector ) )
.then( ( errors ) => {
if ( errors.length > 0 ) {
spinner.unblock();
errorHandler.clear();
errorHandler.messages( errors );
const formSelector = this.ppcpConfig.context === 'checkout' ? 'form.checkout' : 'form#order_review';
const formValidator = this.ppcpConfig.early_checkout_validation_enabled ?
new FormValidator(
this.ppcpConfig.ajax.validate_checkout.endpoint,
this.ppcpConfig.ajax.validate_checkout.nonce,
) : null;
// fire WC event for other plugins
jQuery( document.body ).trigger( 'checkout_error', [
errorHandler.currentHtml(),
] );
if (!formValidator) {
resolve(super.transactionInfo());
return;
}
formValidator.validate(document.querySelector(formSelector)).then((errors) => {
if (errors.length > 0) {
spinner.unblock();
errorHandler.clear();
errorHandler.messages(errors);
// fire WC event for other plugins
jQuery( document.body ).trigger( 'checkout_error' , [ errorHandler.currentHtml() ] );
reject();
} else {
resolve(super.transactionInfo());
}
});
} catch (error) {
console.error(error);
reject();
}
});
}
actionHandler() {
return new CheckoutActionHandler(
this.ppcpConfig,
this.errorHandler(),
new Spinner()
);
}
reject();
} else {
resolve();
}
} );
} catch ( error ) {
console.error( error );
reject();
}
} );
}
actionHandler() {
return new CheckoutActionHandler(
this.ppcpConfig,
this.errorHandler(),
new Spinner()
);
}
}
export default CheckoutHandler;

View file

@ -1,34 +1,65 @@
import SingleProductHandler from "./SingleProductHandler";
import CartHandler from "./CartHandler";
import CheckoutHandler from "./CheckoutHandler";
import CartBlockHandler from "./CartBlockHandler";
import CheckoutBlockHandler from "./CheckoutBlockHandler";
import MiniCartHandler from "./MiniCartHandler";
import PayNowHandler from "./PayNowHandler";
import PreviewHandler from "./PreviewHandler";
import SingleProductHandler from './SingleProductHandler';
import CartHandler from './CartHandler';
import CheckoutHandler from './CheckoutHandler';
import CartBlockHandler from './CartBlockHandler';
import CheckoutBlockHandler from './CheckoutBlockHandler';
import MiniCartHandler from './MiniCartHandler';
import PayNowHandler from './PayNowHandler';
import PreviewHandler from './PreviewHandler';
class ContextHandlerFactory {
static create(context, buttonConfig, ppcpConfig, externalActionHandler) {
switch (context) {
case 'product':
return new SingleProductHandler(buttonConfig, ppcpConfig, externalActionHandler);
case 'cart':
return new CartHandler(buttonConfig, ppcpConfig, externalActionHandler);
case 'checkout':
return new CheckoutHandler(buttonConfig, ppcpConfig, externalActionHandler);
case 'pay-now':
return new PayNowHandler(buttonConfig, ppcpConfig, externalActionHandler);
case 'mini-cart':
return new MiniCartHandler(buttonConfig, ppcpConfig, externalActionHandler);
case 'cart-block':
return new CartBlockHandler(buttonConfig, ppcpConfig, externalActionHandler);
case 'checkout-block':
return new CheckoutBlockHandler(buttonConfig, ppcpConfig, externalActionHandler);
case 'preview':
return new PreviewHandler(buttonConfig, ppcpConfig, externalActionHandler);
}
}
static create( context, buttonConfig, ppcpConfig, externalActionHandler ) {
switch ( context ) {
case 'product':
return new SingleProductHandler(
buttonConfig,
ppcpConfig,
externalActionHandler
);
case 'cart':
return new CartHandler(
buttonConfig,
ppcpConfig,
externalActionHandler
);
case 'checkout':
return new CheckoutHandler(
buttonConfig,
ppcpConfig,
externalActionHandler
);
case 'pay-now':
return new PayNowHandler(
buttonConfig,
ppcpConfig,
externalActionHandler
);
case 'mini-cart':
return new MiniCartHandler(
buttonConfig,
ppcpConfig,
externalActionHandler
);
case 'cart-block':
return new CartBlockHandler(
buttonConfig,
ppcpConfig,
externalActionHandler
);
case 'checkout-block':
return new CheckoutBlockHandler(
buttonConfig,
ppcpConfig,
externalActionHandler
);
case 'preview':
return new PreviewHandler(
buttonConfig,
ppcpConfig,
externalActionHandler
);
}
}
}
export default ContextHandlerFactory;

View file

@ -1,7 +1,5 @@
import BaseHandler from "./BaseHandler";
import BaseHandler from './BaseHandler';
class MiniCartHandler extends BaseHandler {
}
class MiniCartHandler extends BaseHandler {}
export default MiniCartHandler;

View file

@ -1,42 +1,35 @@
import Spinner from "../../../../ppcp-button/resources/js/modules/Helper/Spinner";
import BaseHandler from "./BaseHandler";
import CheckoutActionHandler
from "../../../../ppcp-button/resources/js/modules/ActionHandler/CheckoutActionHandler";
import Spinner from '../../../../ppcp-button/resources/js/modules/Helper/Spinner';
import BaseHandler from './BaseHandler';
import CheckoutActionHandler from '../../../../ppcp-button/resources/js/modules/ActionHandler/CheckoutActionHandler';
class PayNowHandler extends BaseHandler {
validateContext() {
if ( this.ppcpConfig?.locations_with_subscription_product?.payorder ) {
return false;
}
return true;
}
validateContext() {
if ( this.ppcpConfig?.locations_with_subscription_product?.payorder ) {
return false;
}
return true;
}
transactionInfo() {
return new Promise( async ( resolve, reject ) => {
const data = this.ppcpConfig.pay_now;
shippingAllowed() {
return false;
}
transactionInfo() {
return new Promise(async (resolve, reject) => {
const data = this.ppcpConfig['pay_now'];
resolve({
countryCode: data.country_code,
currencyCode: data.currency_code,
totalPriceStatus: 'FINAL',
totalPrice: data.total_str
});
});
}
actionHandler() {
return new CheckoutActionHandler(
this.ppcpConfig,
this.errorHandler(),
new Spinner()
);
}
resolve( {
countryCode: data.country_code,
currencyCode: data.currency_code,
totalPriceStatus: 'FINAL',
totalPrice: data.total_str,
} );
} );
}
actionHandler() {
return new CheckoutActionHandler(
this.ppcpConfig,
this.errorHandler(),
new Spinner()
);
}
}
export default PayNowHandler;

View file

@ -1,31 +1,29 @@
import BaseHandler from "./BaseHandler";
import BaseHandler from './BaseHandler';
class PreviewHandler extends BaseHandler {
constructor( buttonConfig, ppcpConfig, externalHandler ) {
super( buttonConfig, ppcpConfig, externalHandler );
}
constructor(buttonConfig, ppcpConfig, externalHandler) {
super(buttonConfig, ppcpConfig, externalHandler);
}
transactionInfo() {
throw new Error( 'Transaction info fail. This is just a preview.' );
}
transactionInfo() {
throw new Error('Transaction info fail. This is just a preview.');
}
createOrder() {
throw new Error( 'Create order fail. This is just a preview.' );
}
createOrder() {
throw new Error('Create order fail. This is just a preview.');
}
approveOrder( data, actions ) {
throw new Error( 'Approve order fail. This is just a preview.' );
}
approveOrder(data, actions) {
throw new Error('Approve order fail. This is just a preview.');
}
actionHandler() {
throw new Error('Action handler fail. This is just a preview.');
}
errorHandler() {
throw new Error('Error handler fail. This is just a preview.');
}
actionHandler() {
throw new Error( 'Action handler fail. This is just a preview.' );
}
errorHandler() {
throw new Error( 'Error handler fail. This is just a preview.' );
}
}
export default PreviewHandler;

View file

@ -1,80 +1,78 @@
import SingleProductActionHandler
from "../../../../ppcp-button/resources/js/modules/ActionHandler/SingleProductActionHandler";
import SimulateCart from "../../../../ppcp-button/resources/js/modules/Helper/SimulateCart";
import ErrorHandler from "../../../../ppcp-button/resources/js/modules/ErrorHandler";
import UpdateCart from "../../../../ppcp-button/resources/js/modules/Helper/UpdateCart";
import BaseHandler from "./BaseHandler";
import SingleProductActionHandler from '../../../../ppcp-button/resources/js/modules/ActionHandler/SingleProductActionHandler';
import SimulateCart from '../../../../ppcp-button/resources/js/modules/Helper/SimulateCart';
import ErrorHandler from '../../../../ppcp-button/resources/js/modules/ErrorHandler';
import UpdateCart from '../../../../ppcp-button/resources/js/modules/Helper/UpdateCart';
import BaseHandler from './BaseHandler';
class SingleProductHandler extends BaseHandler {
validateContext() {
if ( this.ppcpConfig?.locations_with_subscription_product?.product ) {
return false;
}
return true;
}
validateContext() {
if ( this.ppcpConfig?.locations_with_subscription_product?.product ) {
return false;
}
return true;
}
transactionInfo() {
const errorHandler = new ErrorHandler(
this.ppcpConfig.labels.error.generic,
document.querySelector( '.woocommerce-notices-wrapper' )
);
transactionInfo() {
const errorHandler = new ErrorHandler(
this.ppcpConfig.labels.error.generic,
document.querySelector('.woocommerce-notices-wrapper')
);
function form() {
return document.querySelector( 'form.cart' );
}
function form() {
return document.querySelector('form.cart');
}
const actionHandler = new SingleProductActionHandler(
null,
null,
form(),
errorHandler
);
const actionHandler = new SingleProductActionHandler(
null,
null,
form(),
errorHandler,
);
const hasSubscriptions =
PayPalCommerceGateway.data_client_id.has_subscriptions &&
PayPalCommerceGateway.data_client_id.paypal_subscriptions_enabled;
const hasSubscriptions = PayPalCommerceGateway.data_client_id.has_subscriptions
&& PayPalCommerceGateway.data_client_id.paypal_subscriptions_enabled;
const products = hasSubscriptions
? actionHandler.getSubscriptionProducts()
: actionHandler.getProducts();
const products = hasSubscriptions
? actionHandler.getSubscriptionProducts()
: actionHandler.getProducts();
return new Promise( ( resolve, reject ) => {
new SimulateCart(
this.ppcpConfig.ajax.simulate_cart.endpoint,
this.ppcpConfig.ajax.simulate_cart.nonce
).simulate( ( data ) => {
resolve( {
countryCode: data.country_code,
currencyCode: data.currency_code,
totalPriceStatus: 'FINAL',
totalPrice: data.total_str,
} );
}, products );
} );
}
return new Promise((resolve, reject) => {
(new SimulateCart(
this.ppcpConfig.ajax.simulate_cart.endpoint,
this.ppcpConfig.ajax.simulate_cart.nonce,
)).simulate((data) => {
resolve({
countryCode: data.country_code,
currencyCode: data.currency_code,
totalPriceStatus: 'FINAL',
totalPrice: data.total_str
});
}, products);
});
}
createOrder() {
return this.actionHandler().configuration().createOrder(null, null, {
'updateCartOptions': {
'keepShipping': true
}
});
}
actionHandler() {
return new SingleProductActionHandler(
this.ppcpConfig,
new UpdateCart(
this.ppcpConfig.ajax.change_cart.endpoint,
this.ppcpConfig.ajax.change_cart.nonce,
),
document.querySelector('form.cart'),
this.errorHandler(),
);
}
createOrder() {
return this.actionHandler()
.configuration()
.createOrder( null, null, {
updateCartOptions: {
keepShipping: true,
},
} );
}
actionHandler() {
return new SingleProductActionHandler(
this.ppcpConfig,
new UpdateCart(
this.ppcpConfig.ajax.change_cart.endpoint,
this.ppcpConfig.ajax.change_cart.nonce
),
document.querySelector( 'form.cart' ),
this.errorHandler()
);
}
}
export default SingleProductHandler;

View file

@ -1,394 +1,542 @@
import ContextHandlerFactory from "./Context/ContextHandlerFactory";
import {setVisible} from '../../../ppcp-button/resources/js/modules/Helper/Hiding';
import {setEnabled} from '../../../ppcp-button/resources/js/modules/Helper/ButtonDisabler';
import widgetBuilder from "../../../ppcp-button/resources/js/modules/Renderer/WidgetBuilder";
import UpdatePaymentData from "./Helper/UpdatePaymentData";
import {apmButtonsInit} from "../../../ppcp-button/resources/js/modules/Helper/ApmButtons";
import { setVisible } from '../../../ppcp-button/resources/js/modules/Helper/Hiding';
import { setEnabled } from '../../../ppcp-button/resources/js/modules/Helper/ButtonDisabler';
import widgetBuilder from '../../../ppcp-button/resources/js/modules/Renderer/WidgetBuilder';
import UpdatePaymentData from './Helper/UpdatePaymentData';
import { apmButtonsInit } from '../../../ppcp-button/resources/js/modules/Helper/ApmButtons';
class GooglepayButton {
constructor(context, externalHandler, buttonConfig, ppcpConfig) {
apmButtonsInit(ppcpConfig);
this.isInitialized = false;
this.context = context;
this.externalHandler = externalHandler;
this.buttonConfig = buttonConfig;
this.ppcpConfig = ppcpConfig;
this.paymentsClient = null;
this.contextHandler = ContextHandlerFactory.create(
this.context,
this.buttonConfig,
this.ppcpConfig,
this.externalHandler
);
this.log = function() {
if ( this.buttonConfig.is_debug ) {
//console.log('[GooglePayButton]', ...arguments);
}
}
}
init(config) {
if (this.isInitialized) {
return;
}
this.isInitialized = true;
if (!this.validateConfig()) {
return;
}
if (!this.contextHandler.validateContext()) {
return;
}
this.googlePayConfig = config;
this.allowedPaymentMethods = config.allowedPaymentMethods;
this.baseCardPaymentMethod = this.allowedPaymentMethods[0];
this.initClient();
this.initEventHandlers();
this.paymentsClient.isReadyToPay(
this.buildReadyToPayRequest(this.allowedPaymentMethods, config)
)
.then((response) => {
if (response.result) {
this.addButton(this.baseCardPaymentMethod);
}
})
.catch(function(err) {
console.error(err);
});
}
reinit() {
if (!this.googlePayConfig) {
return;
}
this.isInitialized = false;
this.init(this.googlePayConfig);
}
validateConfig() {
if ( ['PRODUCTION', 'TEST'].indexOf(this.buttonConfig.environment) === -1) {
console.error('[GooglePayButton] Invalid environment.', this.buttonConfig.environment);
return false;
}
if ( !this.contextHandler ) {
console.error('[GooglePayButton] Invalid context handler.', this.contextHandler);
return false;
}
return true;
}
/**
* Returns configurations relative to this button context.
*/
contextConfig() {
let config = {
wrapper: this.buttonConfig.button.wrapper,
ppcpStyle: this.ppcpConfig.button.style,
buttonStyle: this.buttonConfig.button.style,
ppcpButtonWrapper: this.ppcpConfig.button.wrapper
}
if (this.context === 'mini-cart') {
config.wrapper = this.buttonConfig.button.mini_cart_wrapper;
config.ppcpStyle = this.ppcpConfig.button.mini_cart_style;
config.buttonStyle = this.buttonConfig.button.mini_cart_style;
config.ppcpButtonWrapper = this.ppcpConfig.button.mini_cart_wrapper;
// Handle incompatible types.
if (config.buttonStyle.type === 'buy') {
config.buttonStyle.type = 'pay';
}
}
if (['cart-block', 'checkout-block'].indexOf(this.context) !== -1) {
config.ppcpButtonWrapper = '#express-payment-method-ppcp-gateway-paypal';
}
return config;
}
initClient() {
const callbacks = {
onPaymentAuthorized: this.onPaymentAuthorized.bind(this)
}
if ( this.buttonConfig.shipping.enabled && this.contextHandler.shippingAllowed() ) {
callbacks['onPaymentDataChanged'] = this.onPaymentDataChanged.bind(this);
}
this.paymentsClient = new google.payments.api.PaymentsClient({
environment: this.buttonConfig.environment,
// add merchant info maybe
paymentDataCallbacks: callbacks
});
}
initEventHandlers() {
const { wrapper, ppcpButtonWrapper } = this.contextConfig();
const syncButtonVisibility = () => {
const $ppcpButtonWrapper = jQuery(ppcpButtonWrapper);
setVisible(wrapper, $ppcpButtonWrapper.is(':visible'));
setEnabled(wrapper, !$ppcpButtonWrapper.hasClass('ppcp-disabled'));
}
jQuery(document).on('ppcp-shown ppcp-hidden ppcp-enabled ppcp-disabled', (ev, data) => {
if (jQuery(data.selector).is(ppcpButtonWrapper)) {
syncButtonVisibility();
}
});
syncButtonVisibility();
}
buildReadyToPayRequest(allowedPaymentMethods, baseRequest) {
return Object.assign({}, baseRequest, {
allowedPaymentMethods: allowedPaymentMethods,
});
}
/**
* Add a Google Pay purchase button
*/
addButton(baseCardPaymentMethod) {
this.log('addButton', this.context);
const { wrapper, ppcpStyle, buttonStyle } = this.contextConfig();
this.waitForWrapper(wrapper, () => {
jQuery(wrapper).addClass('ppcp-button-' + ppcpStyle.shape);
if (ppcpStyle.height) {
jQuery(wrapper).css('height', `${ppcpStyle.height}px`)
}
const button =
this.paymentsClient.createButton({
onClick: this.onButtonClick.bind(this),
allowedPaymentMethods: [baseCardPaymentMethod],
buttonColor: buttonStyle.color || 'black',
buttonType: buttonStyle.type || 'pay',
buttonLocale: buttonStyle.language || 'en',
buttonSizeMode: 'fill',
});
jQuery(wrapper).append(button);
});
}
waitForWrapper(selector, callback, delay = 100, timeout = 2000) {
const startTime = Date.now();
const interval = setInterval(() => {
const el = document.querySelector(selector);
const timeElapsed = Date.now() - startTime;
if (el) {
clearInterval(interval);
callback(el);
} else if (timeElapsed > timeout) {
clearInterval(interval);
}
}, delay);
}
//------------------------
// Button click
//------------------------
/**
* Show Google Pay payment sheet when Google Pay payment button is clicked
*/
async onButtonClick() {
this.log('onButtonClick', this.context);
const paymentDataRequest = await this.paymentDataRequest();
this.log('onButtonClick: paymentDataRequest', paymentDataRequest, this.context);
window.ppcpFundingSource = 'googlepay'; // Do this on another place like on create order endpoint handler.
this.paymentsClient.loadPaymentData(paymentDataRequest);
}
async paymentDataRequest() {
let baseRequest = {
apiVersion: 2,
apiVersionMinor: 0
}
const googlePayConfig = this.googlePayConfig;
const paymentDataRequest = Object.assign({}, baseRequest);
paymentDataRequest.allowedPaymentMethods = googlePayConfig.allowedPaymentMethods;
paymentDataRequest.transactionInfo = await this.contextHandler.transactionInfo();
paymentDataRequest.merchantInfo = googlePayConfig.merchantInfo;
if ( this.buttonConfig.shipping.enabled && this.contextHandler.shippingAllowed() ) {
paymentDataRequest.callbackIntents = ["SHIPPING_ADDRESS", "SHIPPING_OPTION", "PAYMENT_AUTHORIZATION"];
paymentDataRequest.shippingAddressRequired = true;
paymentDataRequest.shippingAddressParameters = this.shippingAddressParameters();
paymentDataRequest.shippingOptionRequired = true;
} else {
paymentDataRequest.callbackIntents = ['PAYMENT_AUTHORIZATION'];
}
return paymentDataRequest;
}
//------------------------
// Shipping processing
//------------------------
shippingAddressParameters() {
return {
allowedCountryCodes: this.buttonConfig.shipping.countries,
phoneNumberRequired: true
};
}
onPaymentDataChanged(paymentData) {
this.log('onPaymentDataChanged', this.context);
this.log('paymentData', paymentData);
return new Promise(async (resolve, reject) => {
let paymentDataRequestUpdate = {};
const updatedData = await (new UpdatePaymentData(this.buttonConfig.ajax.update_payment_data)).update(paymentData);
const transactionInfo = await this.contextHandler.transactionInfo();
this.log('onPaymentDataChanged:updatedData', updatedData);
this.log('onPaymentDataChanged:transactionInfo', transactionInfo);
updatedData.country_code = transactionInfo.countryCode;
updatedData.currency_code = transactionInfo.currencyCode;
updatedData.total_str = transactionInfo.totalPrice;
// Handle unserviceable address.
if(!updatedData.shipping_options || !updatedData.shipping_options.shippingOptions.length) {
paymentDataRequestUpdate.error = this.unserviceableShippingAddressError();
resolve(paymentDataRequestUpdate);
return;
}
switch (paymentData.callbackTrigger) {
case 'INITIALIZE':
case 'SHIPPING_ADDRESS':
paymentDataRequestUpdate.newShippingOptionParameters = updatedData.shipping_options;
paymentDataRequestUpdate.newTransactionInfo = this.calculateNewTransactionInfo(updatedData);
break;
case 'SHIPPING_OPTION':
paymentDataRequestUpdate.newTransactionInfo = this.calculateNewTransactionInfo(updatedData);
break;
}
resolve(paymentDataRequestUpdate);
});
}
unserviceableShippingAddressError() {
return {
reason: "SHIPPING_ADDRESS_UNSERVICEABLE",
message: "Cannot ship to the selected address",
intent: "SHIPPING_ADDRESS"
};
}
calculateNewTransactionInfo(updatedData) {
return {
countryCode: updatedData.country_code,
currencyCode: updatedData.currency_code,
totalPriceStatus: 'FINAL',
totalPrice: updatedData.total_str
};
}
//------------------------
// Payment process
//------------------------
onPaymentAuthorized(paymentData) {
this.log('onPaymentAuthorized', this.context);
return this.processPayment(paymentData);
}
async processPayment(paymentData) {
this.log('processPayment', this.context);
return new Promise(async (resolve, reject) => {
try {
let id = await this.contextHandler.createOrder();
this.log('processPayment: createOrder', id, this.context);
const confirmOrderResponse = await widgetBuilder.paypal.Googlepay().confirmOrder({
orderId: id,
paymentMethodData: paymentData.paymentMethodData
});
this.log('processPayment: confirmOrder', confirmOrderResponse, this.context);
/** Capture the Order on the Server */
if (confirmOrderResponse.status === "APPROVED") {
let approveFailed = false;
await this.contextHandler.approveOrder({
orderID: id
}, { // actions mock object.
restart: () => new Promise((resolve, reject) => {
approveFailed = true;
resolve();
}),
order: {
get: () => new Promise((resolve, reject) => {
resolve(null);
})
}
});
if (!approveFailed) {
resolve(this.processPaymentResponse('SUCCESS'));
} else {
resolve(this.processPaymentResponse('ERROR', 'PAYMENT_AUTHORIZATION', 'FAILED TO APPROVE'));
}
} else {
resolve(this.processPaymentResponse('ERROR', 'PAYMENT_AUTHORIZATION', 'TRANSACTION FAILED'));
}
} catch(err) {
resolve(this.processPaymentResponse('ERROR', 'PAYMENT_AUTHORIZATION', err.message));
}
});
}
processPaymentResponse(state, intent = null, message = null) {
let response = {
transactionState: state,
}
if (intent || message) {
response.error = {
intent: intent,
message: message,
}
}
this.log('processPaymentResponse', response, this.context);
return response;
}
constructor(
context,
externalHandler,
buttonConfig,
ppcpConfig,
contextHandler
) {
apmButtonsInit( ppcpConfig );
this.isInitialized = false;
this.context = context;
this.externalHandler = externalHandler;
this.buttonConfig = buttonConfig;
this.ppcpConfig = ppcpConfig;
this.contextHandler = contextHandler;
this.paymentsClient = null;
this.log = function () {
if ( this.buttonConfig.is_debug ) {
//console.log('[GooglePayButton]', ...arguments);
}
};
}
init( config, transactionInfo ) {
if ( this.isInitialized ) {
return;
}
this.isInitialized = true;
if ( ! this.validateConfig() ) {
return;
}
if ( ! this.contextHandler.validateContext() ) {
return;
}
this.googlePayConfig = config;
this.transactionInfo = transactionInfo;
this.allowedPaymentMethods = config.allowedPaymentMethods;
this.baseCardPaymentMethod = this.allowedPaymentMethods[ 0 ];
this.initClient();
this.initEventHandlers();
this.paymentsClient
.isReadyToPay(
this.buildReadyToPayRequest(
this.allowedPaymentMethods,
config
)
)
.then( ( response ) => {
if ( response.result ) {
if (
( this.context === 'checkout' ||
this.context === 'pay-now' ) &&
this.buttonConfig.is_wc_gateway_enabled === '1'
) {
const wrapper = document.getElementById(
'ppc-button-ppcp-googlepay'
);
if ( wrapper ) {
const { ppcpStyle, buttonStyle } =
this.contextConfig();
wrapper.classList.add(
`ppcp-button-${ ppcpStyle.shape }`,
'ppcp-button-apm',
'ppcp-button-googlepay'
);
if ( ppcpStyle.height ) {
wrapper.style.height = `${ ppcpStyle.height }px`;
}
this.addButtonCheckout(
this.baseCardPaymentMethod,
wrapper,
buttonStyle
);
return;
}
}
this.addButton( this.baseCardPaymentMethod );
}
} )
.catch( function ( err ) {
console.error( err );
} );
}
reinit() {
if ( ! this.googlePayConfig ) {
return;
}
this.isInitialized = false;
this.init( this.googlePayConfig, this.transactionInfo );
}
validateConfig() {
if (
[ 'PRODUCTION', 'TEST' ].indexOf(
this.buttonConfig.environment
) === -1
) {
console.error(
'[GooglePayButton] Invalid environment.',
this.buttonConfig.environment
);
return false;
}
if ( ! this.contextHandler ) {
console.error(
'[GooglePayButton] Invalid context handler.',
this.contextHandler
);
return false;
}
return true;
}
/**
* Returns configurations relative to this button context.
*/
contextConfig() {
const config = {
wrapper: this.buttonConfig.button.wrapper,
ppcpStyle: this.ppcpConfig.button.style,
buttonStyle: this.buttonConfig.button.style,
ppcpButtonWrapper: this.ppcpConfig.button.wrapper,
};
if ( this.context === 'mini-cart' ) {
config.wrapper = this.buttonConfig.button.mini_cart_wrapper;
config.ppcpStyle = this.ppcpConfig.button.mini_cart_style;
config.buttonStyle = this.buttonConfig.button.mini_cart_style;
config.ppcpButtonWrapper = this.ppcpConfig.button.mini_cart_wrapper;
// Handle incompatible types.
if ( config.buttonStyle.type === 'buy' ) {
config.buttonStyle.type = 'pay';
}
}
if (
[ 'cart-block', 'checkout-block' ].indexOf( this.context ) !== -1
) {
config.ppcpButtonWrapper =
'#express-payment-method-ppcp-gateway-paypal';
}
return config;
}
initClient() {
const callbacks = {
onPaymentAuthorized: this.onPaymentAuthorized.bind( this ),
};
if (
this.buttonConfig.shipping.enabled &&
this.contextHandler.shippingAllowed()
) {
callbacks.onPaymentDataChanged =
this.onPaymentDataChanged.bind( this );
}
this.paymentsClient = new google.payments.api.PaymentsClient( {
environment: this.buttonConfig.environment,
// add merchant info maybe
paymentDataCallbacks: callbacks,
} );
}
initEventHandlers() {
const { wrapper, ppcpButtonWrapper } = this.contextConfig();
if ( wrapper === ppcpButtonWrapper ) {
throw new Error(
`[GooglePayButton] "wrapper" and "ppcpButtonWrapper" values must differ to avoid infinite loop. Current value: "${ wrapper }"`
);
}
const syncButtonVisibility = () => {
const $ppcpButtonWrapper = jQuery( ppcpButtonWrapper );
setVisible( wrapper, $ppcpButtonWrapper.is( ':visible' ) );
setEnabled(
wrapper,
! $ppcpButtonWrapper.hasClass( 'ppcp-disabled' )
);
};
jQuery( document ).on(
'ppcp-shown ppcp-hidden ppcp-enabled ppcp-disabled',
( ev, data ) => {
if ( jQuery( data.selector ).is( ppcpButtonWrapper ) ) {
syncButtonVisibility();
}
}
);
syncButtonVisibility();
}
buildReadyToPayRequest( allowedPaymentMethods, baseRequest ) {
return Object.assign( {}, baseRequest, {
allowedPaymentMethods,
} );
}
/**
* Add a Google Pay purchase button
* @param baseCardPaymentMethod
*/
addButton( baseCardPaymentMethod ) {
this.log( 'addButton', this.context );
const { wrapper, ppcpStyle, buttonStyle } = this.contextConfig();
this.waitForWrapper( wrapper, () => {
jQuery( wrapper ).addClass( 'ppcp-button-' + ppcpStyle.shape );
if ( ppcpStyle.height ) {
jQuery( wrapper ).css( 'height', `${ ppcpStyle.height }px` );
}
const button = this.paymentsClient.createButton( {
onClick: this.onButtonClick.bind( this ),
allowedPaymentMethods: [ baseCardPaymentMethod ],
buttonColor: buttonStyle.color || 'black',
buttonType: buttonStyle.type || 'pay',
buttonLocale: buttonStyle.language || 'en',
buttonSizeMode: 'fill',
} );
jQuery( wrapper ).append( button );
} );
}
addButtonCheckout( baseCardPaymentMethod, wrapper, buttonStyle ) {
const button = this.paymentsClient.createButton( {
onClick: this.onButtonClick.bind( this ),
allowedPaymentMethods: [ baseCardPaymentMethod ],
buttonColor: buttonStyle.color || 'black',
buttonType: buttonStyle.type || 'pay',
buttonLocale: buttonStyle.language || 'en',
buttonSizeMode: 'fill',
} );
wrapper.appendChild( button );
}
waitForWrapper( selector, callback, delay = 100, timeout = 2000 ) {
const startTime = Date.now();
const interval = setInterval( () => {
const el = document.querySelector( selector );
const timeElapsed = Date.now() - startTime;
if ( el ) {
clearInterval( interval );
callback( el );
} else if ( timeElapsed > timeout ) {
clearInterval( interval );
}
}, delay );
}
//------------------------
// Button click
//------------------------
/**
* Show Google Pay payment sheet when Google Pay payment button is clicked
*/
onButtonClick() {
this.log( 'onButtonClick', this.context );
const initiatePaymentRequest = () => {
window.ppcpFundingSource = 'googlepay';
const paymentDataRequest = this.paymentDataRequest();
this.log(
'onButtonClick: paymentDataRequest',
paymentDataRequest,
this.context
);
this.paymentsClient.loadPaymentData( paymentDataRequest );
};
if ( 'function' === typeof this.contextHandler.validateForm ) {
// During regular checkout, validate the checkout form before initiating the payment.
this.contextHandler
.validateForm()
.then( initiatePaymentRequest, () => {
console.error(
'[GooglePayButton] Form validation failed.'
);
} );
} else {
// This is the flow on product page, cart, and other non-checkout pages.
initiatePaymentRequest();
}
}
paymentDataRequest() {
const baseRequest = {
apiVersion: 2,
apiVersionMinor: 0,
};
const googlePayConfig = this.googlePayConfig;
const paymentDataRequest = Object.assign( {}, baseRequest );
paymentDataRequest.allowedPaymentMethods =
googlePayConfig.allowedPaymentMethods;
paymentDataRequest.transactionInfo = this.transactionInfo;
paymentDataRequest.merchantInfo = googlePayConfig.merchantInfo;
if (
this.buttonConfig.shipping.enabled &&
this.contextHandler.shippingAllowed()
) {
paymentDataRequest.callbackIntents = [
'SHIPPING_ADDRESS',
'SHIPPING_OPTION',
'PAYMENT_AUTHORIZATION',
];
paymentDataRequest.shippingAddressRequired = true;
paymentDataRequest.shippingAddressParameters =
this.shippingAddressParameters();
paymentDataRequest.shippingOptionRequired = true;
} else {
paymentDataRequest.callbackIntents = [ 'PAYMENT_AUTHORIZATION' ];
}
return paymentDataRequest;
}
//------------------------
// Shipping processing
//------------------------
shippingAddressParameters() {
return {
allowedCountryCodes: this.buttonConfig.shipping.countries,
phoneNumberRequired: true,
};
}
onPaymentDataChanged( paymentData ) {
this.log( 'onPaymentDataChanged', this.context );
this.log( 'paymentData', paymentData );
return new Promise( async ( resolve, reject ) => {
try {
const paymentDataRequestUpdate = {};
const updatedData = await new UpdatePaymentData(
this.buttonConfig.ajax.update_payment_data
).update( paymentData );
const transactionInfo = this.transactionInfo;
this.log( 'onPaymentDataChanged:updatedData', updatedData );
this.log(
'onPaymentDataChanged:transactionInfo',
transactionInfo
);
updatedData.country_code = transactionInfo.countryCode;
updatedData.currency_code = transactionInfo.currencyCode;
updatedData.total_str = transactionInfo.totalPrice;
// Handle unserviceable address.
if ( ! updatedData.shipping_options?.shippingOptions?.length ) {
paymentDataRequestUpdate.error =
this.unserviceableShippingAddressError();
resolve( paymentDataRequestUpdate );
return;
}
switch ( paymentData.callbackTrigger ) {
case 'INITIALIZE':
case 'SHIPPING_ADDRESS':
paymentDataRequestUpdate.newShippingOptionParameters =
updatedData.shipping_options;
paymentDataRequestUpdate.newTransactionInfo =
this.calculateNewTransactionInfo( updatedData );
break;
case 'SHIPPING_OPTION':
paymentDataRequestUpdate.newTransactionInfo =
this.calculateNewTransactionInfo( updatedData );
break;
}
resolve( paymentDataRequestUpdate );
} catch ( error ) {
console.error( 'Error during onPaymentDataChanged:', error );
reject( error );
}
} );
}
unserviceableShippingAddressError() {
return {
reason: 'SHIPPING_ADDRESS_UNSERVICEABLE',
message: 'Cannot ship to the selected address',
intent: 'SHIPPING_ADDRESS',
};
}
calculateNewTransactionInfo( updatedData ) {
return {
countryCode: updatedData.country_code,
currencyCode: updatedData.currency_code,
totalPriceStatus: 'FINAL',
totalPrice: updatedData.total_str,
};
}
//------------------------
// Payment process
//------------------------
onPaymentAuthorized( paymentData ) {
this.log( 'onPaymentAuthorized', this.context );
return this.processPayment( paymentData );
}
async processPayment( paymentData ) {
this.log( 'processPayment', this.context );
return new Promise( async ( resolve, reject ) => {
try {
const id = await this.contextHandler.createOrder();
this.log( 'processPayment: createOrder', id, this.context );
const confirmOrderResponse = await widgetBuilder.paypal
.Googlepay()
.confirmOrder( {
orderId: id,
paymentMethodData: paymentData.paymentMethodData,
} );
this.log(
'processPayment: confirmOrder',
confirmOrderResponse,
this.context
);
/** Capture the Order on the Server */
if ( confirmOrderResponse.status === 'APPROVED' ) {
let approveFailed = false;
await this.contextHandler.approveOrder(
{
orderID: id,
},
{
// actions mock object.
restart: () =>
new Promise( ( resolve, reject ) => {
approveFailed = true;
resolve();
} ),
order: {
get: () =>
new Promise( ( resolve, reject ) => {
resolve( null );
} ),
},
}
);
if ( ! approveFailed ) {
resolve( this.processPaymentResponse( 'SUCCESS' ) );
} else {
resolve(
this.processPaymentResponse(
'ERROR',
'PAYMENT_AUTHORIZATION',
'FAILED TO APPROVE'
)
);
}
} else {
resolve(
this.processPaymentResponse(
'ERROR',
'PAYMENT_AUTHORIZATION',
'TRANSACTION FAILED'
)
);
}
} catch ( err ) {
resolve(
this.processPaymentResponse(
'ERROR',
'PAYMENT_AUTHORIZATION',
err.message
)
);
}
} );
}
processPaymentResponse( state, intent = null, message = null ) {
const response = {
transactionState: state,
};
if ( intent || message ) {
response.error = {
intent,
message,
};
}
this.log( 'processPaymentResponse', response, this.context );
return response;
}
}
export default GooglepayButton;

View file

@ -1,49 +1,83 @@
import buttonModuleWatcher from "../../../ppcp-button/resources/js/modules/ButtonModuleWatcher";
import GooglepayButton from "./GooglepayButton";
import buttonModuleWatcher from '../../../ppcp-button/resources/js/modules/ButtonModuleWatcher';
import GooglepayButton from './GooglepayButton';
import ContextHandlerFactory from './Context/ContextHandlerFactory';
class GooglepayManager {
constructor( buttonConfig, ppcpConfig ) {
this.buttonConfig = buttonConfig;
this.ppcpConfig = ppcpConfig;
this.googlePayConfig = null;
this.transactionInfo = null;
this.contextHandler = null;
constructor(buttonConfig, ppcpConfig) {
this.buttons = [];
this.buttonConfig = buttonConfig;
this.ppcpConfig = ppcpConfig;
this.googlePayConfig = null;
buttonModuleWatcher.watchContextBootstrap( async ( bootstrap ) => {
this.contextHandler = ContextHandlerFactory.create(
bootstrap.context,
buttonConfig,
ppcpConfig,
bootstrap.handler
);
this.buttons = [];
const button = new GooglepayButton(
bootstrap.context,
bootstrap.handler,
buttonConfig,
ppcpConfig,
this.contextHandler
);
buttonModuleWatcher.watchContextBootstrap((bootstrap) => {
const button = new GooglepayButton(
bootstrap.context,
bootstrap.handler,
buttonConfig,
ppcpConfig,
);
this.buttons.push( button );
this.buttons.push(button);
// Initialize button only if googlePayConfig and transactionInfo are already fetched.
if ( this.googlePayConfig && this.transactionInfo ) {
button.init( this.googlePayConfig, this.transactionInfo );
} else {
await this.init();
if ( this.googlePayConfig && this.transactionInfo ) {
button.init( this.googlePayConfig, this.transactionInfo );
}
}
} );
}
if (this.googlePayConfig) {
button.init(this.googlePayConfig);
}
});
}
async init() {
try {
if ( ! this.googlePayConfig ) {
// Gets GooglePay configuration of the PayPal merchant.
this.googlePayConfig = await paypal.Googlepay().config();
}
init() {
(async () => {
// Gets GooglePay configuration of the PayPal merchant.
this.googlePayConfig = await paypal.Googlepay().config();
if ( ! this.transactionInfo ) {
this.transactionInfo = await this.fetchTransactionInfo();
}
for (const button of this.buttons) {
button.init(this.googlePayConfig);
}
})();
}
for ( const button of this.buttons ) {
button.init( this.googlePayConfig, this.transactionInfo );
}
} catch ( error ) {
console.error( 'Error during initialization:', error );
}
}
reinit() {
for (const button of this.buttons) {
button.reinit();
}
}
async fetchTransactionInfo() {
try {
if ( ! this.contextHandler ) {
throw new Error( 'ContextHandler is not initialized' );
}
return await this.contextHandler.transactionInfo();
} catch ( error ) {
console.error( 'Error fetching transaction info:', error );
throw error;
}
}
reinit() {
for ( const button of this.buttons ) {
button.reinit();
}
}
}
export default GooglepayManager;

View file

@ -1,38 +1,31 @@
class UpdatePaymentData {
constructor( config ) {
this.config = config;
}
constructor(config) {
this.config = config;
}
update(paymentData) {
return new Promise((resolve, reject) => {
fetch(
this.config.endpoint,
{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
credentials: 'same-origin',
body: JSON.stringify({
nonce: this.config.nonce,
paymentData: paymentData,
})
}
)
.then(result => result.json())
.then(result => {
if (!result.success) {
return;
}
resolve(result.data);
});
});
}
update( paymentData ) {
return new Promise( ( resolve, reject ) => {
fetch( this.config.endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
credentials: 'same-origin',
body: JSON.stringify( {
nonce: this.config.nonce,
paymentData,
} ),
} )
.then( ( result ) => result.json() )
.then( ( result ) => {
if ( ! result.success ) {
return;
}
resolve( result.data );
} );
} );
}
}
export default UpdatePaymentData;

View file

@ -1,146 +1,132 @@
import {loadCustomScript} from "@paypal/paypal-js";
import GooglepayButton from "./GooglepayButton";
import widgetBuilder from "../../../ppcp-button/resources/js/modules/Renderer/WidgetBuilder";
import GooglepayButton from './GooglepayButton';
import PreviewButton from '../../../ppcp-button/resources/js/modules/Renderer/PreviewButton';
import PreviewButtonManager from '../../../ppcp-button/resources/js/modules/Renderer/PreviewButtonManager';
import ContextHandlerFactory from './Context/ContextHandlerFactory';
(function ({
buttonConfig,
jQuery
}) {
/**
* Accessor that creates and returns a single PreviewButtonManager instance.
*/
const buttonManager = () => {
if ( ! GooglePayPreviewButtonManager.instance ) {
GooglePayPreviewButtonManager.instance =
new GooglePayPreviewButtonManager();
}
let googlePayConfig;
let buttonQueue = [];
let activeButtons = {};
let bootstrapped = false;
return GooglePayPreviewButtonManager.instance;
};
// React to PayPal config changes.
jQuery(document).on('ppcp_paypal_render_preview', (ev, ppcpConfig) => {
if (bootstrapped) {
createButton(ppcpConfig);
} else {
buttonQueue.push({
ppcpConfig: JSON.parse(JSON.stringify(ppcpConfig))
});
}
});
/**
* Manages all GooglePay preview buttons on this page.
*/
class GooglePayPreviewButtonManager extends PreviewButtonManager {
constructor() {
const args = {
methodName: 'GooglePay',
buttonConfig: window.wc_ppcp_googlepay_admin,
};
// React to GooglePay config changes.
jQuery([
'#ppcp-googlepay_button_enabled',
'#ppcp-googlepay_button_type',
'#ppcp-googlepay_button_color',
'#ppcp-googlepay_button_language',
'#ppcp-googlepay_button_shipping_enabled'
].join(',')).on('change', () => {
for (const [selector, ppcpConfig] of Object.entries(activeButtons)) {
createButton(ppcpConfig);
}
});
super( args );
}
// Maybe we can find a more elegant reload method when transitioning from styling modes.
jQuery([
'#ppcp-smart_button_enable_styling_per_location'
].join(',')).on('change', () => {
setTimeout(() => {
for (const [selector, ppcpConfig] of Object.entries(activeButtons)) {
createButton(ppcpConfig);
}
}, 100);
});
/**
* Responsible for fetching and returning the PayPal configuration object for this payment
* method.
*
* @param {{}} payPal - The PayPal SDK object provided by WidgetBuilder.
* @return {Promise<{}>}
*/
async fetchConfig( payPal ) {
const apiMethod = payPal?.Googlepay()?.config;
const applyConfigOptions = function (buttonConfig) {
buttonConfig.button = buttonConfig.button || {};
buttonConfig.button.style = buttonConfig.button.style || {};
buttonConfig.button.style.type = jQuery('#ppcp-googlepay_button_type').val();
buttonConfig.button.style.color = jQuery('#ppcp-googlepay_button_color').val();
buttonConfig.button.style.language = jQuery('#ppcp-googlepay_button_language').val();
}
if ( ! apiMethod ) {
this.error(
'configuration object cannot be retrieved from PayPal'
);
return {};
}
const createButton = function (ppcpConfig) {
const selector = ppcpConfig.button.wrapper + 'GooglePay';
try {
return await apiMethod();
} catch ( error ) {
if ( error.message.includes( 'Not Eligible' ) ) {
this.apiError = 'Not Eligible';
}
return null;
}
}
if (!jQuery('#ppcp-googlepay_button_enabled').is(':checked')) {
jQuery(selector).remove();
return;
}
/**
* This method is responsible for creating a new PreviewButton instance and returning it.
*
* @param {string} wrapperId - CSS ID of the wrapper element.
* @return {GooglePayPreviewButton}
*/
createButtonInstance( wrapperId ) {
return new GooglePayPreviewButton( {
selector: wrapperId,
apiConfig: this.apiConfig,
} );
}
}
buttonConfig = JSON.parse(JSON.stringify(buttonConfig));
buttonConfig.button.wrapper = selector;
applyConfigOptions(buttonConfig);
/**
* A single GooglePay preview button instance.
*/
class GooglePayPreviewButton extends PreviewButton {
constructor( args ) {
super( args );
const wrapperElement = `<div id="${selector.replace('#', '')}" class="ppcp-button-apm ppcp-button-googlepay"></div>`;
this.selector = `${ args.selector }GooglePay`;
this.defaultAttributes = {
button: {
style: {
type: 'pay',
color: 'black',
language: 'en',
},
},
};
}
if (!jQuery(selector).length) {
jQuery(ppcpConfig.button.wrapper).after(wrapperElement);
} else {
jQuery(selector).replaceWith(wrapperElement);
}
createNewWrapper() {
const element = super.createNewWrapper();
element.addClass( 'ppcp-button-googlepay' );
const button = new GooglepayButton(
'preview',
null,
buttonConfig,
ppcpConfig,
);
return element;
}
button.init(googlePayConfig);
createButton( buttonConfig ) {
const contextHandler = ContextHandlerFactory.create(
'preview',
buttonConfig,
this.ppcpConfig,
null
);
activeButtons[selector] = ppcpConfig;
}
const button = new GooglepayButton(
'preview',
null,
buttonConfig,
this.ppcpConfig,
contextHandler
);
const bootstrap = async function () {
if (!widgetBuilder.paypal) {
return;
}
button.init( this.apiConfig, null );
}
googlePayConfig = await widgetBuilder.paypal.Googlepay().config();
/**
* Merge form details into the config object for preview.
* Mutates the previewConfig object; no return value.
* @param buttonConfig
* @param ppcpConfig
*/
dynamicPreviewConfig( buttonConfig, ppcpConfig ) {
// Merge the current form-values into the preview-button configuration.
if ( ppcpConfig.button && buttonConfig.button ) {
Object.assign( buttonConfig.button.style, ppcpConfig.button.style );
}
}
}
// We need to set bootstrapped here otherwise googlePayConfig may not be set.
bootstrapped = true;
let options;
while (options = buttonQueue.pop()) {
createButton(options.ppcpConfig);
}
};
document.addEventListener(
'DOMContentLoaded',
() => {
if (typeof (buttonConfig) === 'undefined') {
console.error('PayPal button could not be configured.');
return;
}
let paypalLoaded = false;
let googlePayLoaded = false;
const tryToBoot = () => {
if (!bootstrapped && paypalLoaded && googlePayLoaded) {
bootstrap();
}
}
// Load GooglePay SDK
loadCustomScript({ url: buttonConfig.sdk_url }).then(() => {
googlePayLoaded = true;
tryToBoot();
});
// Wait for PayPal to be loaded externally
if (typeof widgetBuilder.paypal !== 'undefined') {
paypalLoaded = true;
tryToBoot();
}
jQuery(document).on('ppcp-paypal-loaded', () => {
paypalLoaded = true;
tryToBoot();
});
},
);
})({
buttonConfig: window.wc_ppcp_googlepay_admin,
jQuery: window.jQuery
});
// Initialize the preview button manager.
buttonManager();

View file

@ -1,63 +1,69 @@
import {useEffect, useState} from '@wordpress/element';
import {registerExpressPaymentMethod, registerPaymentMethod} from '@woocommerce/blocks-registry';
import {loadPaypalScript} from '../../../ppcp-button/resources/js/modules/Helper/ScriptLoading'
import GooglepayManager from "./GooglepayManager";
import {loadCustomScript} from "@paypal/paypal-js";
import { useEffect, useState } from '@wordpress/element';
import {
registerExpressPaymentMethod,
registerPaymentMethod,
} from '@woocommerce/blocks-registry';
import { loadPaypalScript } from '../../../ppcp-button/resources/js/modules/Helper/ScriptLoading';
import GooglepayManager from './GooglepayManager';
import { loadCustomScript } from '@paypal/paypal-js';
const ppcpData = wc.wcSettings.getSetting('ppcp-gateway_data');
const ppcpData = wc.wcSettings.getSetting( 'ppcp-gateway_data' );
const ppcpConfig = ppcpData.scriptData;
const buttonData = wc.wcSettings.getSetting('ppcp-googlepay_data');
const buttonData = wc.wcSettings.getSetting( 'ppcp-googlepay_data' );
const buttonConfig = buttonData.scriptData;
if (typeof window.PayPalCommerceGateway === 'undefined') {
window.PayPalCommerceGateway = ppcpConfig;
if ( typeof window.PayPalCommerceGateway === 'undefined' ) {
window.PayPalCommerceGateway = ppcpConfig;
}
const GooglePayComponent = () => {
const [bootstrapped, setBootstrapped] = useState(false);
const [paypalLoaded, setPaypalLoaded] = useState(false);
const [googlePayLoaded, setGooglePayLoaded] = useState(false);
const [ bootstrapped, setBootstrapped ] = useState( false );
const [ paypalLoaded, setPaypalLoaded ] = useState( false );
const [ googlePayLoaded, setGooglePayLoaded ] = useState( false );
const bootstrap = function () {
const manager = new GooglepayManager(buttonConfig, ppcpConfig);
manager.init();
};
const bootstrap = function () {
const manager = new GooglepayManager( buttonConfig, ppcpConfig );
manager.init();
};
useEffect(() => {
// Load GooglePay SDK
loadCustomScript({ url: buttonConfig.sdk_url }).then(() => {
setGooglePayLoaded(true);
});
useEffect( () => {
// Load GooglePay SDK
loadCustomScript( { url: buttonConfig.sdk_url } ).then( () => {
setGooglePayLoaded( true );
} );
// Load PayPal
loadPaypalScript(ppcpConfig, () => {
setPaypalLoaded(true);
});
}, []);
// Load PayPal
loadPaypalScript( ppcpConfig, () => {
setPaypalLoaded( true );
} );
}, [] );
useEffect(() => {
if (!bootstrapped && paypalLoaded && googlePayLoaded) {
setBootstrapped(true);
bootstrap();
}
}, [paypalLoaded, googlePayLoaded]);
useEffect( () => {
if ( ! bootstrapped && paypalLoaded && googlePayLoaded ) {
setBootstrapped( true );
bootstrap();
}
}, [ paypalLoaded, googlePayLoaded ] );
return (
<div id={buttonConfig.button.wrapper.replace('#', '')} className="ppcp-button-apm ppcp-button-googlepay"></div>
);
}
return (
<div
id={ buttonConfig.button.wrapper.replace( '#', '' ) }
className="ppcp-button-apm ppcp-button-googlepay"
></div>
);
};
const features = ['products'];
const features = [ 'products' ];
registerExpressPaymentMethod({
name: buttonData.id,
label: <div dangerouslySetInnerHTML={{__html: buttonData.title}}/>,
content: <GooglePayComponent isEditing={false}/>,
edit: <GooglePayComponent isEditing={true}/>,
ariaLabel: buttonData.title,
canMakePayment: () => buttonData.enabled,
supports: {
features: features,
},
});
registerExpressPaymentMethod( {
name: buttonData.id,
label: <div dangerouslySetInnerHTML={ { __html: buttonData.title } } />,
content: <GooglePayComponent isEditing={ false } />,
edit: <GooglePayComponent isEditing={ true } />,
ariaLabel: buttonData.title,
canMakePayment: () => buttonData.enabled,
supports: {
features,
},
} );

View file

@ -1,73 +1,56 @@
import {loadCustomScript} from "@paypal/paypal-js";
import {loadPaypalScript} from "../../../ppcp-button/resources/js/modules/Helper/ScriptLoading";
import GooglepayManager from "./GooglepayManager";
import { loadCustomScript } from '@paypal/paypal-js';
import { loadPaypalScript } from '../../../ppcp-button/resources/js/modules/Helper/ScriptLoading';
import GooglepayManager from './GooglepayManager';
import { setupButtonEvents } from '../../../ppcp-button/resources/js/modules/Helper/ButtonRefreshHelper';
(function ({
buttonConfig,
ppcpConfig,
jQuery
}) {
( function ( { buttonConfig, ppcpConfig, jQuery } ) {
let manager;
let manager;
const bootstrap = function () {
manager = new GooglepayManager( buttonConfig, ppcpConfig );
manager.init();
};
const bootstrap = function () {
manager = new GooglepayManager(buttonConfig, ppcpConfig);
manager.init();
};
setupButtonEvents( function () {
if ( manager ) {
manager.reinit();
}
} );
jQuery(document.body).on('updated_cart_totals updated_checkout', () => {
if (manager) {
manager.reinit();
}
});
document.addEventListener( 'DOMContentLoaded', () => {
if (
typeof buttonConfig === 'undefined' ||
typeof ppcpConfig === 'undefined'
) {
// No PayPal buttons present on this page.
return;
}
// Use set timeout as it's unnecessary to refresh upon Minicart initial render.
setTimeout(() => {
jQuery(document.body).on('wc_fragments_loaded wc_fragments_refreshed', () => {
if (manager) {
manager.reinit();
}
});
}, 1000);
let bootstrapped = false;
let paypalLoaded = false;
let googlePayLoaded = false;
document.addEventListener(
'DOMContentLoaded',
() => {
if (
(typeof (buttonConfig) === 'undefined') ||
(typeof (ppcpConfig) === 'undefined')
) {
// No PayPal buttons present on this page.
return;
}
const tryToBoot = () => {
if ( ! bootstrapped && paypalLoaded && googlePayLoaded ) {
bootstrapped = true;
bootstrap();
}
};
let bootstrapped = false;
let paypalLoaded = false;
let googlePayLoaded = false;
// Load GooglePay SDK
loadCustomScript( { url: buttonConfig.sdk_url } ).then( () => {
googlePayLoaded = true;
tryToBoot();
} );
const tryToBoot = () => {
if (!bootstrapped && paypalLoaded && googlePayLoaded) {
bootstrapped = true;
bootstrap();
}
}
// Load GooglePay SDK
loadCustomScript({ url: buttonConfig.sdk_url }).then(() => {
googlePayLoaded = true;
tryToBoot();
});
// Load PayPal
loadPaypalScript(ppcpConfig, () => {
paypalLoaded = true;
tryToBoot();
});
},
);
})({
buttonConfig: window.wc_ppcp_googlepay,
ppcpConfig: window.PayPalCommerceGateway,
jQuery: window.jQuery
});
// Load PayPal
loadPaypalScript( ppcpConfig, () => {
paypalLoaded = true;
tryToBoot();
} );
} );
} )( {
buttonConfig: window.wc_ppcp_googlepay,
ppcpConfig: window.PayPalCommerceGateway,
jQuery: window.jQuery,
} );

View file

@ -25,23 +25,24 @@ use WooCommerce\PayPalCommerce\Vendor\Psr\Container\ContainerInterface;
return array(
// If GooglePay can be configured.
'googlepay.eligible' => static function ( ContainerInterface $container ): bool {
'googlepay.eligible' => static function ( ContainerInterface $container ): bool {
$apm_applies = $container->get( 'googlepay.helpers.apm-applies' );
assert( $apm_applies instanceof ApmApplies );
return $apm_applies->for_country_currency();
return $apm_applies->for_country() && $apm_applies->for_currency();
},
'googlepay.helpers.apm-applies' => static function ( ContainerInterface $container ) : ApmApplies {
'googlepay.helpers.apm-applies' => static function ( ContainerInterface $container ) : ApmApplies {
return new ApmApplies(
$container->get( 'googlepay.supported-country-currency-matrix' ),
$container->get( 'googlepay.supported-countries' ),
$container->get( 'googlepay.supported-currencies' ),
$container->get( 'api.shop.currency' ),
$container->get( 'api.shop.country' )
);
},
// If GooglePay is configured and onboarded.
'googlepay.available' => static function ( ContainerInterface $container ): bool {
'googlepay.available' => static function ( ContainerInterface $container ): bool {
if ( apply_filters( 'woocommerce_paypal_payments_googlepay_validate_product_status', true ) ) {
$status = $container->get( 'googlepay.helpers.apm-product-status' );
assert( $status instanceof ApmProductStatus );
@ -54,14 +55,14 @@ return array(
},
// We assume it's a referral if we can check product status without API request failures.
'googlepay.is_referral' => static function ( ContainerInterface $container ): bool {
'googlepay.is_referral' => static function ( ContainerInterface $container ): bool {
$status = $container->get( 'googlepay.helpers.apm-product-status' );
assert( $status instanceof ApmProductStatus );
return ! $status->has_request_failure();
},
'googlepay.availability_notice' => static function ( ContainerInterface $container ): AvailabilityNotice {
'googlepay.availability_notice' => static function ( ContainerInterface $container ): AvailabilityNotice {
return new AvailabilityNotice(
$container->get( 'googlepay.helpers.apm-product-status' ),
$container->get( 'wcgateway.is-wc-gateways-list-page' ),
@ -69,7 +70,7 @@ return array(
);
},
'googlepay.helpers.apm-product-status' => SingletonDecorator::make(
'googlepay.helpers.apm-product-status' => SingletonDecorator::make(
static function( ContainerInterface $container ): ApmProductStatus {
return new ApmProductStatus(
$container->get( 'wcgateway.settings' ),
@ -81,772 +82,93 @@ return array(
),
/**
* The matrix which countries and currency combinations can be used for GooglePay.
* The list of which countries can be used for GooglePay.
*/
'googlepay.supported-country-currency-matrix' => static function ( ContainerInterface $container ) : array {
'googlepay.supported-countries' => static function ( ContainerInterface $container ) : array {
/**
* Returns which countries and currency combinations can be used for GooglePay.
* Returns which countries can be used for GooglePay.
*/
return apply_filters(
'woocommerce_paypal_payments_googlepay_supported_country_currency_matrix',
'woocommerce_paypal_payments_googlepay_supported_countries',
// phpcs:disable Squiz.Commenting.InlineComment
array(
'AU' => array(
'AUD',
'BRL',
'CAD',
'CHF',
'CZK',
'DKK',
'EUR',
'GBP',
'HKD',
'HUF',
'ILS',
'JPY',
'MXN',
'NOK',
'NZD',
'PHP',
'PLN',
'SEK',
'SGD',
'THB',
'TWD',
'USD',
),
'AT' => array(
'AUD',
'BRL',
'CAD',
'CHF',
'CZK',
'DKK',
'EUR',
'GBP',
'HKD',
'HUF',
'ILS',
'JPY',
'MXN',
'NOK',
'NZD',
'PHP',
'PLN',
'SEK',
'SGD',
'THB',
'TWD',
'USD',
),
'BE' => array(
'AUD',
'BRL',
'CAD',
'CHF',
'CZK',
'DKK',
'EUR',
'GBP',
'HKD',
'HUF',
'ILS',
'JPY',
'MXN',
'NOK',
'NZD',
'PHP',
'PLN',
'SEK',
'SGD',
'THB',
'TWD',
'USD',
),
'BG' => array(
'AUD',
'BRL',
'CAD',
'CHF',
'CZK',
'DKK',
'EUR',
'GBP',
'HKD',
'HUF',
'ILS',
'JPY',
'MXN',
'NOK',
'NZD',
'PHP',
'PLN',
'SEK',
'SGD',
'THB',
'TWD',
'USD',
),
'CA' => array(
'AUD',
'BRL',
'CAD',
'CHF',
'CZK',
'DKK',
'EUR',
'GBP',
'HKD',
'HUF',
'ILS',
'JPY',
'MXN',
'NOK',
'NZD',
'PHP',
'PLN',
'SEK',
'SGD',
'THB',
'TWD',
'USD',
),
'CY' => array(
'AUD',
'BRL',
'CAD',
'CHF',
'CZK',
'DKK',
'EUR',
'GBP',
'HKD',
'HUF',
'ILS',
'JPY',
'MXN',
'NOK',
'NZD',
'PHP',
'PLN',
'SEK',
'SGD',
'THB',
'TWD',
'USD',
),
'CZ' => array(
'AUD',
'BRL',
'CAD',
'CHF',
'CZK',
'DKK',
'EUR',
'GBP',
'HKD',
'HUF',
'ILS',
'JPY',
'MXN',
'NOK',
'NZD',
'PHP',
'PLN',
'SEK',
'SGD',
'THB',
'TWD',
'USD',
),
'DK' => array(
'AUD',
'BRL',
'CAD',
'CHF',
'CZK',
'DKK',
'EUR',
'GBP',
'HKD',
'HUF',
'ILS',
'JPY',
'MXN',
'NOK',
'NZD',
'PHP',
'PLN',
'SEK',
'SGD',
'THB',
'TWD',
'USD',
),
'EE' => array(
'AUD',
'BRL',
'CAD',
'CHF',
'CZK',
'DKK',
'EUR',
'GBP',
'HKD',
'HUF',
'ILS',
'JPY',
'MXN',
'NOK',
'NZD',
'PHP',
'PLN',
'SEK',
'SGD',
'THB',
'TWD',
'USD',
),
'FI' => array(
'AUD',
'BRL',
'CAD',
'CHF',
'CZK',
'DKK',
'EUR',
'GBP',
'HKD',
'HUF',
'ILS',
'JPY',
'MXN',
'NOK',
'NZD',
'PHP',
'PLN',
'SEK',
'SGD',
'THB',
'TWD',
'USD',
),
'FR' => array(
'AUD',
'BRL',
'CAD',
'CHF',
'CZK',
'DKK',
'EUR',
'GBP',
'HKD',
'HUF',
'ILS',
'JPY',
'MXN',
'NOK',
'NZD',
'PHP',
'PLN',
'SEK',
'SGD',
'THB',
'TWD',
'USD',
),
'DE' => array(
'AUD',
'BRL',
'CAD',
'CHF',
'CZK',
'DKK',
'EUR',
'GBP',
'HKD',
'HUF',
'ILS',
'JPY',
'MXN',
'NOK',
'NZD',
'PHP',
'PLN',
'SEK',
'SGD',
'THB',
'TWD',
'USD',
),
'GR' => array(
'AUD',
'BRL',
'CAD',
'CHF',
'CZK',
'DKK',
'EUR',
'GBP',
'HKD',
'HUF',
'ILS',
'JPY',
'MXN',
'NOK',
'NZD',
'PHP',
'PLN',
'SEK',
'SGD',
'THB',
'TWD',
'USD',
),
'HU' => array(
'AUD',
'BRL',
'CAD',
'CHF',
'CZK',
'DKK',
'EUR',
'GBP',
'HKD',
'HUF',
'ILS',
'JPY',
'MXN',
'NOK',
'NZD',
'PHP',
'PLN',
'SEK',
'SGD',
'THB',
'TWD',
'USD',
),
'IE' => array(
'AUD',
'BRL',
'CAD',
'CHF',
'CZK',
'DKK',
'EUR',
'GBP',
'HKD',
'HUF',
'ILS',
'JPY',
'MXN',
'NOK',
'NZD',
'PHP',
'PLN',
'SEK',
'SGD',
'THB',
'TWD',
'USD',
),
'IT' => array(
'AUD',
'BRL',
'CAD',
'CHF',
'CZK',
'DKK',
'EUR',
'GBP',
'HKD',
'HUF',
'ILS',
'JPY',
'MXN',
'NOK',
'NZD',
'PHP',
'PLN',
'SEK',
'SGD',
'THB',
'TWD',
'USD',
),
'LV' => array(
'AUD',
'BRL',
'CAD',
'CHF',
'CZK',
'DKK',
'EUR',
'GBP',
'HKD',
'HUF',
'ILS',
'JPY',
'MXN',
'NOK',
'NZD',
'PHP',
'PLN',
'SEK',
'SGD',
'THB',
'TWD',
'USD',
),
'LI' => array(
'AUD',
'BRL',
'CAD',
'CHF',
'CZK',
'DKK',
'EUR',
'GBP',
'HKD',
'HUF',
'ILS',
'JPY',
'MXN',
'NOK',
'NZD',
'PHP',
'PLN',
'SEK',
'SGD',
'THB',
'TWD',
'USD',
),
'LT' => array(
'AUD',
'BRL',
'CAD',
'CHF',
'CZK',
'DKK',
'EUR',
'GBP',
'HKD',
'HUF',
'ILS',
'JPY',
'MXN',
'NOK',
'NZD',
'PHP',
'PLN',
'SEK',
'SGD',
'THB',
'TWD',
'USD',
),
'LU' => array(
'AUD',
'BRL',
'CAD',
'CHF',
'CZK',
'DKK',
'EUR',
'GBP',
'HKD',
'HUF',
'ILS',
'JPY',
'MXN',
'NOK',
'NZD',
'PHP',
'PLN',
'SEK',
'SGD',
'THB',
'TWD',
'USD',
),
'MT' => array(
'AUD',
'BRL',
'CAD',
'CHF',
'CZK',
'DKK',
'EUR',
'GBP',
'HKD',
'HUF',
'ILS',
'JPY',
'MXN',
'NOK',
'NZD',
'PHP',
'PLN',
'SEK',
'SGD',
'THB',
'TWD',
'USD',
),
'NO' => array(
'AUD',
'BRL',
'CAD',
'CHF',
'CZK',
'DKK',
'EUR',
'GBP',
'HKD',
'HUF',
'ILS',
'JPY',
'MXN',
'NOK',
'NZD',
'PHP',
'PLN',
'SEK',
'SGD',
'THB',
'TWD',
'USD',
),
'NL' => array(
'AUD',
'BRL',
'CAD',
'CHF',
'CZK',
'DKK',
'EUR',
'GBP',
'HKD',
'HUF',
'ILS',
'JPY',
'MXN',
'NOK',
'NZD',
'PHP',
'PLN',
'SEK',
'SGD',
'THB',
'TWD',
'USD',
),
'PL' => array(
'AUD',
'BRL',
'CAD',
'CHF',
'CZK',
'DKK',
'EUR',
'GBP',
'HKD',
'HUF',
'ILS',
'JPY',
'MXN',
'NOK',
'NZD',
'PHP',
'PLN',
'SEK',
'SGD',
'THB',
'TWD',
'USD',
),
'PT' => array(
'AUD',
'BRL',
'CAD',
'CHF',
'CZK',
'DKK',
'EUR',
'GBP',
'HKD',
'HUF',
'ILS',
'JPY',
'MXN',
'NOK',
'NZD',
'PHP',
'PLN',
'SEK',
'SGD',
'THB',
'TWD',
'USD',
),
'RO' => array(
'AUD',
'BRL',
'CAD',
'CHF',
'CZK',
'DKK',
'EUR',
'GBP',
'HKD',
'HUF',
'ILS',
'JPY',
'MXN',
'NOK',
'NZD',
'PHP',
'PLN',
'SEK',
'SGD',
'THB',
'TWD',
'USD',
),
'SK' => array(
'AUD',
'BRL',
'CAD',
'CHF',
'CZK',
'DKK',
'EUR',
'GBP',
'HKD',
'HUF',
'ILS',
'JPY',
'MXN',
'NOK',
'NZD',
'PHP',
'PLN',
'SEK',
'SGD',
'THB',
'TWD',
'USD',
),
'SI' => array(
'AUD',
'BRL',
'CAD',
'CHF',
'CZK',
'DKK',
'EUR',
'GBP',
'HKD',
'HUF',
'ILS',
'JPY',
'MXN',
'NOK',
'NZD',
'PHP',
'PLN',
'SEK',
'SGD',
'THB',
'TWD',
'USD',
),
'ES' => array(
'AUD',
'BRL',
'CAD',
'CHF',
'CZK',
'DKK',
'EUR',
'GBP',
'HKD',
'HUF',
'ILS',
'JPY',
'MXN',
'NOK',
'NZD',
'PHP',
'PLN',
'SEK',
'SGD',
'THB',
'TWD',
'USD',
),
'SE' => array(
'AUD',
'BRL',
'CAD',
'CHF',
'CZK',
'DKK',
'EUR',
'GBP',
'HKD',
'HUF',
'ILS',
'JPY',
'MXN',
'NOK',
'NZD',
'PHP',
'PLN',
'SEK',
'SGD',
'THB',
'TWD',
'USD',
),
'GB' => array(
'AUD',
'BRL',
'CAD',
'CHF',
'CZK',
'DKK',
'EUR',
'GBP',
'HKD',
'HUF',
'ILS',
'JPY',
'MXN',
'NOK',
'NZD',
'PHP',
'PLN',
'SEK',
'SGD',
'THB',
'TWD',
'USD',
),
'US' => array(
'AUD',
'CAD',
'EUR',
'GBP',
'JPY',
'USD',
),
'AU', // Australia
'AT', // Austria
'BE', // Belgium
'BG', // Bulgaria
'CA', // Canada
'CN', // China
'CY', // Cyprus
'CZ', // Czech Republic
'DK', // Denmark
'EE', // Estonia
'FI', // Finland
'FR', // France
'DE', // Germany
'GR', // Greece
'HU', // Hungary
'IE', // Ireland
'IT', // Italy
'LV', // Latvia
'LI', // Liechtenstein
'LT', // Lithuania
'LU', // Luxembourg
'MT', // Malta
'NL', // Netherlands
'NO', // Norway
'PL', // Poland
'PT', // Portugal
'RO', // Romania
'SK', // Slovakia
'SI', // Slovenia
'ES', // Spain
'SE', // Sweden
'US', // United States
'GB', // United Kingdom
)
// phpcs:enable Squiz.Commenting.InlineComment
);
},
'googlepay.button' => static function ( ContainerInterface $container ): ButtonInterface {
/**
* The list of which currencies can be used for GooglePay.
*/
'googlepay.supported-currencies' => static function ( ContainerInterface $container ) : array {
/**
* Returns which currencies can be used for GooglePay.
*/
return apply_filters(
'woocommerce_paypal_payments_googlepay_supported_currencies',
// phpcs:disable Squiz.Commenting.InlineComment
array(
'AUD', // Australian Dollar
'BRL', // Brazilian Real
'CAD', // Canadian Dollar
'CHF', // Swiss Franc
'CZK', // Czech Koruna
'DKK', // Danish Krone
'EUR', // Euro
'GBP', // British Pound Sterling
'HKD', // Hong Kong Dollar
'HUF', // Hungarian Forint
'ILS', // Israeli New Shekel
'JPY', // Japanese Yen
'MXN', // Mexican Peso
'NOK', // Norwegian Krone
'NZD', // New Zealand Dollar
'PHP', // Philippine Peso
'PLN', // Polish Zloty
'SEK', // Swedish Krona
'SGD', // Singapore Dollar
'THB', // Thai Baht
'TWD', // New Taiwan Dollar
'USD', // United States Dollar
)
// phpcs:enable Squiz.Commenting.InlineComment
);
},
'googlepay.button' => static function ( ContainerInterface $container ): ButtonInterface {
return new Button(
$container->get( 'googlepay.url' ),
$container->get( 'googlepay.sdk_url' ),
@ -860,7 +182,7 @@ return array(
);
},
'googlepay.blocks-payment-method' => static function ( ContainerInterface $container ): PaymentMethodTypeInterface {
'googlepay.blocks-payment-method' => static function ( ContainerInterface $container ): PaymentMethodTypeInterface {
return new BlocksPaymentMethod(
'ppcp-googlepay',
$container->get( 'googlepay.url' ),
@ -870,7 +192,7 @@ return array(
);
},
'googlepay.url' => static function ( ContainerInterface $container ): string {
'googlepay.url' => static function ( ContainerInterface $container ): string {
$path = realpath( __FILE__ );
if ( false === $path ) {
return '';
@ -881,26 +203,26 @@ return array(
);
},
'googlepay.sdk_url' => static function ( ContainerInterface $container ): string {
'googlepay.sdk_url' => static function ( ContainerInterface $container ): string {
return 'https://pay.google.com/gp/p/js/pay.js';
},
'googlepay.endpoint.update-payment-data' => static function ( ContainerInterface $container ): UpdatePaymentDataEndpoint {
'googlepay.endpoint.update-payment-data' => static function ( ContainerInterface $container ): UpdatePaymentDataEndpoint {
return new UpdatePaymentDataEndpoint(
$container->get( 'button.request-data' ),
$container->get( 'woocommerce.logger.woocommerce' )
);
},
'googlepay.enable-url-sandbox' => static function ( ContainerInterface $container ): string {
'googlepay.enable-url-sandbox' => static function ( ContainerInterface $container ): string {
return 'https://www.sandbox.paypal.com/bizsignup/add-product?product=payment_methods&capabilities=GOOGLE_PAY';
},
'googlepay.enable-url-live' => static function ( ContainerInterface $container ): string {
'googlepay.enable-url-live' => static function ( ContainerInterface $container ): string {
return 'https://www.paypal.com/bizsignup/add-product?product=payment_methods&capabilities=GOOGLE_PAY';
},
'googlepay.settings.connection.status-text' => static function ( ContainerInterface $container ): string {
'googlepay.settings.connection.status-text' => static function ( ContainerInterface $container ): string {
$state = $container->get( 'onboarding.state' );
if ( $state->current_state() < State::STATE_ONBOARDED ) {
return '';
@ -926,7 +248,7 @@ return array(
: $container->get( 'googlepay.enable-url-sandbox' );
$button_url = $enabled
? admin_url( 'admin.php?page=wc-settings&tab=checkout&section=ppcp-gateway#field-alternative_payment_methods' )
? admin_url( 'admin.php?page=wc-settings&tab=checkout&section=ppcp-gateway&ppcp-tab=ppcp-credit-card-gateway#ppcp-googlepay_button_enabled' )
: $enable_url;
return sprintf(
@ -938,5 +260,14 @@ return array(
esc_html( $button_text )
);
},
'googlepay.wc-gateway' => static function ( ContainerInterface $container ): GooglePayGateway {
return new GooglePayGateway(
$container->get( 'wcgateway.order-processor' ),
$container->get( 'api.factory.paypal-checkout-url' ),
$container->get( 'wcgateway.processor.refunds' ),
$container->get( 'wcgateway.transaction-url-provider' ),
$container->get( 'session.handler' ),
$container->get( 'googlepay.url' )
);
},
);

View file

@ -13,7 +13,9 @@ use Exception;
use Psr\Log\LoggerInterface;
use WC_Countries;
use WooCommerce\PayPalCommerce\Button\Assets\ButtonInterface;
use WooCommerce\PayPalCommerce\Button\Helper\ContextTrait;
use WooCommerce\PayPalCommerce\Googlepay\Endpoint\UpdatePaymentDataEndpoint;
use WooCommerce\PayPalCommerce\Googlepay\GooglePayGateway;
use WooCommerce\PayPalCommerce\Onboarding\Environment;
use WooCommerce\PayPalCommerce\Session\SessionHandler;
use WooCommerce\PayPalCommerce\WcGateway\Exception\NotFoundException;
@ -25,6 +27,8 @@ use WooCommerce\PayPalCommerce\WcGateway\Settings\Settings;
*/
class Button implements ButtonInterface {
use ContextTrait;
/**
* The URL to the module.
*
@ -409,27 +413,35 @@ class Button implements ButtonInterface {
*/
public function script_data(): array {
$shipping = array(
'enabled' => $this->settings->has( 'googlepay_button_shipping_enabled' )
'enabled' => $this->settings->has( 'googlepay_button_shipping_enabled' )
? boolval( $this->settings->get( 'googlepay_button_shipping_enabled' ) )
: false,
'configured' => wc_shipping_enabled() && wc_get_shipping_method_count( false, true ) > 0,
);
if ( $shipping['enabled'] ) {
$shipping['countries'] = array_keys( $this->wc_countries()->get_shipping_countries() );
}
$is_enabled = $this->settings->has( 'googlepay_button_enabled' ) && $this->settings->get( 'googlepay_button_enabled' );
$available_gateways = WC()->payment_gateways->get_available_payment_gateways();
$is_wc_gateway_enabled = isset( $available_gateways[ GooglePayGateway::ID ] );
return array(
'environment' => $this->environment->current_environment_is( Environment::SANDBOX ) ? 'TEST' : 'PRODUCTION',
'is_debug' => defined( 'WP_DEBUG' ) && WP_DEBUG ? true : false,
'sdk_url' => $this->sdk_url,
'button' => array(
'environment' => $this->environment->current_environment_is( Environment::SANDBOX ) ? 'TEST' : 'PRODUCTION',
'is_debug' => defined( 'WP_DEBUG' ) && WP_DEBUG,
'is_enabled' => $is_enabled,
'is_wc_gateway_enabled' => $is_wc_gateway_enabled,
'sdk_url' => $this->sdk_url,
'button' => array(
'wrapper' => '#ppc-button-googlepay-container',
'style' => $this->button_styles_for_context( 'cart' ), // For now use cart. Pass the context if necessary.
'mini_cart_wrapper' => '#ppc-button-googlepay-container-minicart',
'mini_cart_style' => $this->button_styles_for_context( 'mini-cart' ),
),
'shipping' => $shipping,
'ajax' => array(
'shipping' => $shipping,
'ajax' => array(
'update_payment_data' => array(
'endpoint' => \WC_AJAX::get_endpoint( UpdatePaymentDataEndpoint::ENDPOINT ),
'nonce' => wp_create_nonce( UpdatePaymentDataEndpoint::nonce() ),

View file

@ -0,0 +1,238 @@
<?php
/**
* The Google Pay Payment Gateway
*
* @package WooCommerce\PayPalCommerce\Googlepay
*/
declare(strict_types=1);
namespace WooCommerce\PayPalCommerce\Googlepay;
use Exception;
use WC_Order;
use WC_Payment_Gateway;
use WooCommerce\PayPalCommerce\ApiClient\Exception\PayPalApiException;
use WooCommerce\PayPalCommerce\Session\SessionHandler;
use WooCommerce\PayPalCommerce\WcGateway\Exception\GatewayGenericException;
use WooCommerce\PayPalCommerce\WcGateway\Exception\PayPalOrderMissingException;
use WooCommerce\PayPalCommerce\WcGateway\Gateway\Messages;
use WooCommerce\PayPalCommerce\WcGateway\Gateway\ProcessPaymentTrait;
use WooCommerce\PayPalCommerce\WcGateway\Gateway\TransactionUrlProvider;
use WooCommerce\PayPalCommerce\WcGateway\Processor\OrderProcessor;
use WooCommerce\PayPalCommerce\WcGateway\Processor\RefundProcessor;
/**
* Class GooglePayGateway
*/
class GooglePayGateway extends WC_Payment_Gateway {
use ProcessPaymentTrait;
const ID = 'ppcp-googlepay';
/**
* The processor for orders.
*
* @var OrderProcessor
*/
protected $order_processor;
/**
* The function return the PayPal checkout URL for the given order ID.
*
* @var callable(string):string
*/
private $paypal_checkout_url_factory;
/**
* The Refund Processor.
*
* @var RefundProcessor
*/
private $refund_processor;
/**
* Service able to provide transaction url for an order.
*
* @var TransactionUrlProvider
*/
protected $transaction_url_provider;
/**
* The Session Handler.
*
* @var SessionHandler
*/
protected $session_handler;
/**
* The URL to the module.
*
* @var string
*/
private $module_url;
/**
* GooglePayGateway constructor.
*
* @param OrderProcessor $order_processor The Order Processor.
* @param callable(string):string $paypal_checkout_url_factory The function return the PayPal checkout URL for the given order ID.
* @param RefundProcessor $refund_processor The Refund Processor.
* @param TransactionUrlProvider $transaction_url_provider Service providing transaction view URL based on order.
* @param SessionHandler $session_handler The Session Handler.
* @param string $module_url The URL to the module.
*/
public function __construct(
OrderProcessor $order_processor,
callable $paypal_checkout_url_factory,
RefundProcessor $refund_processor,
TransactionUrlProvider $transaction_url_provider,
SessionHandler $session_handler,
string $module_url
) {
$this->id = self::ID;
$this->method_title = __( 'Google Pay (via PayPal) ', 'woocommerce-paypal-payments' );
$this->method_description = __( 'The separate payment gateway with the Google Pay button. If disabled, the button is included in the PayPal gateway.', 'woocommerce-paypal-payments' );
$this->title = $this->get_option( 'title', __( 'Google Pay', 'woocommerce-paypal-payments' ) );
$this->description = $this->get_option( 'description', '' );
$this->module_url = $module_url;
$this->icon = esc_url( $this->module_url ) . 'assets/images/googlepay.png';
$this->init_form_fields();
$this->init_settings();
$this->order_processor = $order_processor;
$this->paypal_checkout_url_factory = $paypal_checkout_url_factory;
$this->refund_processor = $refund_processor;
$this->transaction_url_provider = $transaction_url_provider;
$this->session_handler = $session_handler;
add_action(
'woocommerce_update_options_payment_gateways_' . $this->id,
array(
$this,
'process_admin_options',
)
);
}
/**
* Initialize the form fields.
*/
public function init_form_fields() {
$this->form_fields = array(
'enabled' => array(
'title' => __( 'Enable/Disable', 'woocommerce-paypal-payments' ),
'type' => 'checkbox',
'label' => __( 'Google Pay', 'woocommerce-paypal-payments' ),
'default' => 'no',
'desc_tip' => true,
'description' => __( 'Enable/Disable Google Pay payment gateway.', 'woocommerce-paypal-payments' ),
),
'title' => array(
'title' => __( 'Title', 'woocommerce-paypal-payments' ),
'type' => 'text',
'default' => $this->title,
'desc_tip' => true,
'description' => __( 'This controls the title which the user sees during checkout.', 'woocommerce-paypal-payments' ),
),
'description' => array(
'title' => __( 'Description', 'woocommerce-paypal-payments' ),
'type' => 'text',
'default' => $this->description,
'desc_tip' => true,
'description' => __( 'This controls the description which the user sees during checkout.', 'woocommerce-paypal-payments' ),
),
);
}
/**
* Process payment for a WooCommerce order.
*
* @param int $order_id The WooCommerce order id.
*
* @return array
*/
public function process_payment( $order_id ) {
$wc_order = wc_get_order( $order_id );
if ( ! is_a( $wc_order, WC_Order::class ) ) {
return $this->handle_payment_failure(
null,
new GatewayGenericException( new Exception( 'WC order was not found.' ) )
);
}
/**
* If the WC_Order is paid through the approved webhook.
*/
//phpcs:disable WordPress.Security.NonceVerification.Recommended
if ( isset( $_REQUEST['ppcp-resume-order'] ) && $wc_order->has_status( 'processing' ) ) {
return $this->handle_payment_success( $wc_order );
}
//phpcs:enable WordPress.Security.NonceVerification.Recommended
do_action( 'woocommerce_paypal_payments_before_process_order', $wc_order );
try {
try {
$this->order_processor->process( $wc_order );
do_action( 'woocommerce_paypal_payments_before_handle_payment_success', $wc_order );
return $this->handle_payment_success( $wc_order );
} catch ( PayPalOrderMissingException $exc ) {
$order = $this->order_processor->create_order( $wc_order );
return array(
'result' => 'success',
'redirect' => ( $this->paypal_checkout_url_factory )( $order->id() ),
);
}
} catch ( PayPalApiException $error ) {
return $this->handle_payment_failure(
$wc_order,
new Exception(
Messages::generic_payment_error_message() . ' ' . $error->getMessage(),
$error->getCode(),
$error
)
);
} catch ( Exception $error ) {
return $this->handle_payment_failure( $wc_order, $error );
}
}
/**
* Process refund.
*
* If the gateway declares 'refunds' support, this will allow it to refund.
* a passed in amount.
*
* @param int $order_id Order ID.
* @param float $amount Refund amount.
* @param string $reason Refund reason.
* @return boolean True or false based on success, or a WP_Error object.
*/
public function process_refund( $order_id, $amount = null, $reason = '' ) {
$order = wc_get_order( $order_id );
if ( ! is_a( $order, \WC_Order::class ) ) {
return false;
}
return $this->refund_processor->process( $order, (float) $amount, (string) $reason );
}
/**
* Return transaction url for this gateway and given order.
*
* @param \WC_Order $order WC order to get transaction url by.
*
* @return string
*/
public function get_transaction_url( $order ): string {
$this->view_transaction_url = $this->transaction_url_provider->get_transaction_url_base( $order );
return parent::get_transaction_url( $order );
}
}

View file

@ -10,6 +10,7 @@ declare(strict_types=1);
namespace WooCommerce\PayPalCommerce\Googlepay;
use Automattic\WooCommerce\Blocks\Payments\PaymentMethodRegistry;
use WC_Payment_Gateway;
use WooCommerce\PayPalCommerce\Button\Assets\ButtonInterface;
use WooCommerce\PayPalCommerce\Button\Assets\SmartButtonInterface;
use WooCommerce\PayPalCommerce\Googlepay\Endpoint\UpdatePaymentDataEndpoint;
@ -119,7 +120,7 @@ class GooglepayModule implements ServiceModule, ExtendingModule, ExecutableModul
add_action(
'admin_enqueue_scripts',
static function () use ( $c, $button ) {
if ( ! is_admin() || ! $c->get( 'wcgateway.is-ppcp-settings-standard-payments-page' ) ) {
if ( ! is_admin() || ! $c->get( 'wcgateway.is-ppcp-settings-payment-methods-page' ) ) {
return;
}
@ -167,6 +168,46 @@ class GooglepayModule implements ServiceModule, ExtendingModule, ExecutableModul
1
);
add_filter(
'woocommerce_payment_gateways',
/**
* Param types removed to avoid third-party issues.
*
* @psalm-suppress MissingClosureParamType
*/
static function ( $methods ) use ( $c ): array {
if ( ! is_array( $methods ) ) {
return $methods;
}
$settings = $c->get( 'wcgateway.settings' );
assert( $settings instanceof Settings );
if ( $settings->has( 'googlepay_button_enabled' ) && $settings->get( 'googlepay_button_enabled' ) ) {
$googlepay_gateway = $c->get( 'googlepay.wc-gateway' );
assert( $googlepay_gateway instanceof WC_Payment_Gateway );
$methods[] = $googlepay_gateway;
}
return $methods;
}
);
add_action(
'woocommerce_review_order_after_submit',
function () {
echo '<div id="ppc-button-' . esc_attr( GooglePayGateway::ID ) . '"></div>';
}
);
add_action(
'woocommerce_pay_order_after_submit',
function () {
echo '<div id="ppc-button-' . esc_attr( GooglePayGateway::ID ) . '"></div>';
}
);
return true;
}
}

View file

@ -16,11 +16,18 @@ namespace WooCommerce\PayPalCommerce\Googlepay\Helper;
class ApmApplies {
/**
* The matrix which countries and currency combinations can be used for GooglePay.
* The list of which countries can be used for GooglePay.
*
* @var array
*/
private $allowed_country_currency_matrix;
private $allowed_countries;
/**
* The list of which currencies can be used for GooglePay.
*
* @var array
*/
private $allowed_currencies;
/**
* 3-letter currency code of the shop.
@ -39,30 +46,39 @@ class ApmApplies {
/**
* DccApplies constructor.
*
* @param array $allowed_country_currency_matrix The matrix which countries and currency combinations can be used for GooglePay.
* @param array $allowed_countries The list of which countries can be used for GooglePay.
* @param array $allowed_currencies The list of which currencies can be used for GooglePay.
* @param string $currency 3-letter currency code of the shop.
* @param string $country 2-letter country code of the shop.
*/
public function __construct(
array $allowed_country_currency_matrix,
array $allowed_countries,
array $allowed_currencies,
string $currency,
string $country
) {
$this->allowed_country_currency_matrix = $allowed_country_currency_matrix;
$this->currency = $currency;
$this->country = $country;
$this->allowed_countries = $allowed_countries;
$this->allowed_currencies = $allowed_currencies;
$this->currency = $currency;
$this->country = $country;
}
/**
* Returns whether GooglePay can be used in the current country and the current currency used.
* Returns whether GooglePay can be used in the current country used.
*
* @return bool
*/
public function for_country_currency(): bool {
if ( ! in_array( $this->country, array_keys( $this->allowed_country_currency_matrix ), true ) ) {
return false;
}
return in_array( $this->currency, $this->allowed_country_currency_matrix[ $this->country ], true );
public function for_country(): bool {
return in_array( $this->country, $this->allowed_countries, true );
}
/**
* Returns whether GooglePay can be used in the current currency used.
*
* @return bool
*/
public function for_currency(): bool {
return in_array( $this->currency, $this->allowed_currencies, true );
}
}