Run eslint autofix

This commit is contained in:
Emili Castells Guasch 2024-07-12 12:58:34 +02:00
parent 36a13f6500
commit 11105d913b
141 changed files with 14160 additions and 11825 deletions

View file

@ -1,79 +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() {
// Status of the shipping settings in WooCommerce.
return this.buttonConfig.shipping.configured;
}
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,15 +1,13 @@
import BaseHandler from "./BaseHandler";
import BaseHandler from './BaseHandler';
class CheckoutBlockHandler extends BaseHandler{
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,60 +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 {
transactionInfo() {
return new Promise( async ( resolve, reject ) => {
try {
const spinner = new Spinner();
const errorHandler = this.errorHandler();
transactionInfo() {
return new Promise(async (resolve, reject) => {
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;
try {
const spinner = new Spinner();
const errorHandler = this.errorHandler();
if ( ! formValidator ) {
resolve( super.transactionInfo() );
return;
}
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;
formValidator
.validate( document.querySelector( formSelector ) )
.then( ( errors ) => {
if ( errors.length > 0 ) {
spinner.unblock();
errorHandler.clear();
errorHandler.messages( errors );
if (!formValidator) {
resolve(super.transactionInfo());
return;
}
// fire WC event for other plugins
jQuery( document.body ).trigger( 'checkout_error', [
errorHandler.currentHtml(),
] );
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( super.transactionInfo() );
}
} );
} 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,38 +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;
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,398 +1,472 @@
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 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';
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();
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: 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?.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 ) {
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() {
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 );
} );
}
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() {
const 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 ) => {
const 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?.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 {
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,46 @@
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';
class GooglepayManager {
constructor( buttonConfig, ppcpConfig ) {
this.buttonConfig = buttonConfig;
this.ppcpConfig = ppcpConfig;
this.googlePayConfig = null;
constructor(buttonConfig, ppcpConfig) {
this.buttons = [];
this.buttonConfig = buttonConfig;
this.ppcpConfig = ppcpConfig;
this.googlePayConfig = null;
buttonModuleWatcher.watchContextBootstrap( ( bootstrap ) => {
const button = new GooglepayButton(
bootstrap.context,
bootstrap.handler,
buttonConfig,
ppcpConfig
);
this.buttons = [];
this.buttons.push( button );
buttonModuleWatcher.watchContextBootstrap((bootstrap) => {
const button = new GooglepayButton(
bootstrap.context,
bootstrap.handler,
buttonConfig,
ppcpConfig,
);
if ( this.googlePayConfig ) {
button.init( this.googlePayConfig );
}
} );
}
this.buttons.push(button);
init() {
( async () => {
// Gets GooglePay configuration of the PayPal merchant.
this.googlePayConfig = await paypal.Googlepay().config();
if (this.googlePayConfig) {
button.init(this.googlePayConfig);
}
});
}
init() {
(async () => {
// Gets GooglePay configuration of the PayPal merchant.
this.googlePayConfig = await paypal.Googlepay().config();
for (const button of this.buttons) {
button.init(this.googlePayConfig);
}
})();
}
reinit() {
for (const button of this.buttons) {
button.reinit();
}
}
for ( const button of this.buttons ) {
button.init( this.googlePayConfig );
}
} )();
}
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

@ -6,109 +6,117 @@ import PreviewButtonManager from '../../../ppcp-button/resources/js/modules/Rend
* Accessor that creates and returns a single PreviewButtonManager instance.
*/
const buttonManager = () => {
if (!GooglePayPreviewButtonManager.instance) {
GooglePayPreviewButtonManager.instance = new GooglePayPreviewButtonManager();
}
if ( ! GooglePayPreviewButtonManager.instance ) {
GooglePayPreviewButtonManager.instance =
new GooglePayPreviewButtonManager();
}
return GooglePayPreviewButtonManager.instance;
return GooglePayPreviewButtonManager.instance;
};
/**
* Manages all GooglePay preview buttons on this page.
*/
class GooglePayPreviewButtonManager extends PreviewButtonManager {
constructor() {
const args = {
methodName: 'GooglePay',
buttonConfig: window.wc_ppcp_googlepay_admin,
};
constructor() {
const args = {
methodName: 'GooglePay',
buttonConfig: window.wc_ppcp_googlepay_admin,
};
super(args);
}
super( args );
}
/**
* 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;
/**
* 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;
if (!apiMethod) {
this.error('configuration object cannot be retrieved from PayPal');
return {};
}
if ( ! apiMethod ) {
this.error(
'configuration object cannot be retrieved from PayPal'
);
return {};
}
try {
return await apiMethod();
} catch (error) {
if (error.message.includes('Not Eligible')) {
this.apiError = 'Not Eligible';
}
return null;
}
}
try {
return await apiMethod();
} catch ( error ) {
if ( error.message.includes( 'Not Eligible' ) ) {
this.apiError = 'Not Eligible';
}
return null;
}
}
/**
* 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,
});
}
/**
* 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,
} );
}
}
/**
* A single GooglePay preview button instance.
*/
class GooglePayPreviewButton extends PreviewButton {
constructor(args) {
super(args);
constructor( args ) {
super( args );
this.selector = `${args.selector}GooglePay`;
this.defaultAttributes = {
button: {
style: {
type: 'pay',
color: 'black',
language: 'en',
},
},
};
}
this.selector = `${ args.selector }GooglePay`;
this.defaultAttributes = {
button: {
style: {
type: 'pay',
color: 'black',
language: 'en',
},
},
};
}
createNewWrapper() {
const element = super.createNewWrapper();
element.addClass('ppcp-button-googlepay');
createNewWrapper() {
const element = super.createNewWrapper();
element.addClass( 'ppcp-button-googlepay' );
return element;
}
return element;
}
createButton(buttonConfig) {
const button = new GooglepayButton('preview', null, buttonConfig, this.ppcpConfig);
createButton( buttonConfig ) {
const button = new GooglepayButton(
'preview',
null,
buttonConfig,
this.ppcpConfig
);
button.init(this.apiConfig);
}
button.init( this.apiConfig );
}
/**
* Merge form details into the config object for preview.
* Mutates the previewConfig object; no return value.
*/
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);
}
}
/**
* 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 );
}
}
}
// Initialize the preview button manager.

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,65 +1,56 @@
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';
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();
}
} );
setupButtonEvents(function() {
if (manager) {
manager.reinit();
}
});
document.addEventListener( 'DOMContentLoaded', () => {
if (
typeof buttonConfig === 'undefined' ||
typeof ppcpConfig === 'undefined'
) {
// No PayPal buttons present on this page.
return;
}
document.addEventListener(
'DOMContentLoaded',
() => {
if (
(typeof (buttonConfig) === 'undefined') ||
(typeof (ppcpConfig) === 'undefined')
) {
// No PayPal buttons present on this page.
return;
}
let bootstrapped = false;
let paypalLoaded = false;
let googlePayLoaded = false;
let bootstrapped = false;
let paypalLoaded = false;
let googlePayLoaded = false;
const tryToBoot = () => {
if ( ! bootstrapped && paypalLoaded && googlePayLoaded ) {
bootstrapped = true;
bootstrap();
}
};
const tryToBoot = () => {
if (!bootstrapped && paypalLoaded && googlePayLoaded) {
bootstrapped = true;
bootstrap();
}
}
// Load GooglePay SDK
loadCustomScript( { url: buttonConfig.sdk_url } ).then( () => {
googlePayLoaded = true;
tryToBoot();
} );
// 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,
} );