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

File diff suppressed because it is too large Load diff

View file

@ -1,55 +1,52 @@
import buttonModuleWatcher from "../../../ppcp-button/resources/js/modules/ButtonModuleWatcher";
import ApplepayButton from "./ApplepayButton";
import buttonModuleWatcher from '../../../ppcp-button/resources/js/modules/ButtonModuleWatcher';
import ApplepayButton from './ApplepayButton';
class ApplepayManager {
constructor( buttonConfig, ppcpConfig ) {
this.buttonConfig = buttonConfig;
this.ppcpConfig = ppcpConfig;
this.ApplePayConfig = null;
this.buttons = [];
constructor(buttonConfig, ppcpConfig) {
buttonModuleWatcher.watchContextBootstrap( ( bootstrap ) => {
const button = new ApplepayButton(
bootstrap.context,
bootstrap.handler,
buttonConfig,
ppcpConfig
);
this.buttonConfig = buttonConfig;
this.ppcpConfig = ppcpConfig;
this.ApplePayConfig = null;
this.buttons = [];
this.buttons.push( button );
buttonModuleWatcher.watchContextBootstrap((bootstrap) => {
const button = new ApplepayButton(
bootstrap.context,
bootstrap.handler,
buttonConfig,
ppcpConfig,
);
if ( this.ApplePayConfig ) {
button.init( this.ApplePayConfig );
}
} );
}
this.buttons.push(button);
init() {
( async () => {
await this.config();
for ( const button of this.buttons ) {
button.init( this.ApplePayConfig );
}
} )();
}
if (this.ApplePayConfig) {
button.init(this.ApplePayConfig);
}
});
}
init() {
(async () => {
await this.config();
for (const button of this.buttons) {
button.init(this.ApplePayConfig);
}
})();
}
reinit() {
for (const button of this.buttons) {
button.reinit();
}
}
/**
* Gets ApplePay configuration of the PayPal merchant.
* @returns {Promise<null>}
*/
async config() {
this.ApplePayConfig = await paypal.Applepay().config();
return this.ApplePayConfig;
}
reinit() {
for ( const button of this.buttons ) {
button.reinit();
}
}
/**
* Gets ApplePay configuration of the PayPal merchant.
* @return {Promise<null>}
*/
async config() {
this.ApplePayConfig = await paypal.Applepay().config();
return this.ApplePayConfig;
}
}
export default ApplepayManager;

View file

@ -1,36 +1,34 @@
import ApplepayButton from "./ApplepayButton";
import ApplepayButton from './ApplepayButton';
class ApplepayManagerBlockEditor {
constructor( buttonConfig, ppcpConfig ) {
this.buttonConfig = buttonConfig;
this.ppcpConfig = ppcpConfig;
this.applePayConfig = null;
}
constructor(buttonConfig, ppcpConfig) {
this.buttonConfig = buttonConfig;
this.ppcpConfig = ppcpConfig;
this.applePayConfig = null;
}
init() {
( async () => {
await this.config();
} )();
}
init() {
(async () => {
await this.config();
})();
}
async config() {
try {
this.applePayConfig = await paypal.Applepay().config();
async config() {
try {
this.applePayConfig = await paypal.Applepay().config();
const button = new ApplepayButton(
this.ppcpConfig.context,
null,
this.buttonConfig,
this.ppcpConfig
);
const button = new ApplepayButton(
this.ppcpConfig.context,
null,
this.buttonConfig,
this.ppcpConfig,
);
button.init(this.applePayConfig);
} catch (error) {
console.error('Failed to initialize Apple Pay:', error);
}
}
button.init( this.applePayConfig );
} catch ( error ) {
console.error( 'Failed to initialize Apple Pay:', error );
}
}
}
export default ApplepayManagerBlockEditor;

View file

@ -1,95 +1,88 @@
import ErrorHandler from "../../../../ppcp-button/resources/js/modules/ErrorHandler";
import CartActionHandler
from "../../../../ppcp-button/resources/js/modules/ActionHandler/CartActionHandler";
import {isPayPalSubscription} from "../../../../ppcp-blocks/resources/js/Helper/Subscription";
import ErrorHandler from '../../../../ppcp-button/resources/js/modules/ErrorHandler';
import CartActionHandler from '../../../../ppcp-button/resources/js/modules/ActionHandler/CartActionHandler';
import { isPayPalSubscription } from '../../../../ppcp-blocks/resources/js/Helper/Subscription';
class BaseHandler {
constructor( buttonConfig, ppcpConfig ) {
this.buttonConfig = buttonConfig;
this.ppcpConfig = ppcpConfig;
}
constructor(buttonConfig, ppcpConfig) {
this.buttonConfig = buttonConfig;
this.ppcpConfig = ppcpConfig;
}
isVaultV3Mode() {
return (
this.ppcpConfig?.save_payment_methods?.id_token && // vault v3
! this.ppcpConfig?.data_client_id?.paypal_subscriptions_enabled && // not PayPal Subscriptions mode
this.ppcpConfig?.can_save_vault_token
); // vault is enabled
}
isVaultV3Mode() {
return this.ppcpConfig?.save_payment_methods?.id_token // vault v3
&& ! this.ppcpConfig?.data_client_id?.paypal_subscriptions_enabled // not PayPal Subscriptions mode
&& this.ppcpConfig?.can_save_vault_token; // vault is enabled
}
validateContext() {
if ( this.ppcpConfig?.locations_with_subscription_product?.cart ) {
return this.isVaultV3Mode();
}
return true;
}
validateContext() {
if ( this.ppcpConfig?.locations_with_subscription_product?.cart ) {
return this.isVaultV3Mode();
}
return true;
}
shippingAllowed() {
return this.buttonConfig.product.needsShipping;
}
shippingAllowed() {
return this.buttonConfig.product.needsShipping;
}
transactionInfo() {
return new Promise( ( resolve, reject ) => {
const endpoint = this.ppcpConfig.ajax.cart_script_params.endpoint;
const separator = endpoint.indexOf( '?' ) !== -1 ? '&' : '?';
transactionInfo() {
return new Promise((resolve, reject) => {
const endpoint = this.ppcpConfig.ajax.cart_script_params.endpoint;
const separator = (endpoint.indexOf('?') !== -1) ? '&' : '?';
fetch( endpoint + separator + 'shipping=1', {
method: 'GET',
credentials: 'same-origin',
} )
.then( ( result ) => result.json() )
.then( ( result ) => {
if ( ! result.success ) {
return;
}
fetch(
endpoint + separator + 'shipping=1',
{
method: 'GET',
credentials: 'same-origin'
}
)
.then(result => result.json())
.then(result => {
if (! result.success) {
return;
}
// handle script reload
const data = result.data;
// handle script reload
const data = result.data;
resolve( {
countryCode: data.country_code,
currencyCode: data.currency_code,
totalPriceStatus: 'FINAL',
totalPrice: data.total_str,
chosenShippingMethods:
data.chosen_shipping_methods || null,
shippingPackages: data.shipping_packages || null,
} );
} );
} );
}
resolve({
countryCode: data.country_code,
currencyCode: data.currency_code,
totalPriceStatus: 'FINAL',
totalPrice: data.total_str,
chosenShippingMethods: data.chosen_shipping_methods || null,
shippingPackages: data.shipping_packages || null,
});
createOrder() {
return this.actionHandler().configuration().createOrder( null, null );
}
});
});
}
approveOrder( data, actions ) {
return this.actionHandler().configuration().onApprove( data, actions );
}
createOrder() {
return this.actionHandler().configuration().createOrder(null, null);
}
actionHandler() {
return new CartActionHandler( this.ppcpConfig, this.errorHandler() );
}
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')
);
}
errorHandler() {
return new ErrorHandler(
this.ppcpConfig.labels.error.generic,
document.querySelector('.woocommerce-notices-wrapper')
);
}
errorHandler() {
return new ErrorHandler(
this.ppcpConfig.labels.error.generic,
document.querySelector( '.woocommerce-notices-wrapper' )
);
}
errorHandler() {
return new ErrorHandler(
this.ppcpConfig.labels.error.generic,
document.querySelector( '.woocommerce-notices-wrapper' )
);
}
}
export default BaseHandler;

View file

@ -1,7 +1,5 @@
import BaseHandler from "./BaseHandler";
import BaseHandler from './BaseHandler';
class CartBlockHandler extends BaseHandler {
}
class CartBlockHandler extends BaseHandler {}
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,7 +1,5 @@
import BaseHandler from "./BaseHandler";
import BaseHandler from './BaseHandler';
class CheckoutBlockHandler extends BaseHandler{
}
class CheckoutBlockHandler extends BaseHandler {}
export default CheckoutBlockHandler;

View file

@ -1,17 +1,15 @@
import Spinner from "../../../../ppcp-button/resources/js/modules/Helper/Spinner";
import CheckoutActionHandler
from "../../../../ppcp-button/resources/js/modules/ActionHandler/CheckoutActionHandler";
import BaseHandler from "./BaseHandler";
import Spinner from '../../../../ppcp-button/resources/js/modules/Helper/Spinner';
import CheckoutActionHandler from '../../../../ppcp-button/resources/js/modules/ActionHandler/CheckoutActionHandler';
import BaseHandler from './BaseHandler';
class CheckoutHandler extends BaseHandler {
actionHandler() {
return new CheckoutActionHandler(
this.ppcpConfig,
this.errorHandler(),
new Spinner()
);
}
actionHandler() {
return new CheckoutActionHandler(
this.ppcpConfig,
this.errorHandler(),
new Spinner()
);
}
}
export default CheckoutHandler;

View file

@ -1,34 +1,33 @@
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 PreviewHandler from "./PreviewHandler";
import PayNowHandler from "./PayNowHandler";
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 PreviewHandler from './PreviewHandler';
import PayNowHandler from './PayNowHandler';
class ContextHandlerFactory {
static create(context, buttonConfig, ppcpConfig) {
switch (context) {
case 'product':
return new SingleProductHandler(buttonConfig, ppcpConfig);
case 'cart':
return new CartHandler(buttonConfig, ppcpConfig);
case 'checkout':
return new CheckoutHandler(buttonConfig, ppcpConfig);
case 'pay-now':
return new PayNowHandler(buttonConfig, ppcpConfig);
case 'mini-cart':
return new MiniCartHandler(buttonConfig, ppcpConfig);
case 'cart-block':
return new CartBlockHandler(buttonConfig, ppcpConfig);
case 'checkout-block':
return new CheckoutBlockHandler(buttonConfig, ppcpConfig);
case 'preview':
return new PreviewHandler(buttonConfig, ppcpConfig);
}
}
static create( context, buttonConfig, ppcpConfig ) {
switch ( context ) {
case 'product':
return new SingleProductHandler( buttonConfig, ppcpConfig );
case 'cart':
return new CartHandler( buttonConfig, ppcpConfig );
case 'checkout':
return new CheckoutHandler( buttonConfig, ppcpConfig );
case 'pay-now':
return new PayNowHandler( buttonConfig, ppcpConfig );
case 'mini-cart':
return new MiniCartHandler( buttonConfig, ppcpConfig );
case 'cart-block':
return new CartBlockHandler( buttonConfig, ppcpConfig );
case 'checkout-block':
return new CheckoutBlockHandler( buttonConfig, ppcpConfig );
case 'preview':
return new PreviewHandler( buttonConfig, ppcpConfig );
}
}
}
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 this.isVaultV3Mode();
}
return true;
}
validateContext() {
if ( this.ppcpConfig?.locations_with_subscription_product?.payorder ) {
return this.isVaultV3Mode();
}
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,37 +1,35 @@
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() {
// We need to return something as ApplePay button initialization expects valid data.
return {
countryCode: 'US',
currencyCode: 'USD',
totalPrice: '10.00',
totalPriceStatus: 'FINAL',
};
}
transactionInfo() {
// We need to return something as ApplePay button initialization expects valid data.
return {
countryCode: "US",
currencyCode: "USD",
totalPrice: "10.00",
totalPriceStatus: "FINAL"
}
}
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,83 +1,82 @@
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 this.isVaultV3Mode();
}
return true;
}
validateContext() {
if ( this.ppcpConfig?.locations_with_subscription_product?.product ) {
return this.isVaultV3Mode();
}
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) => {
createOrder() {
return this.actionHandler()
.configuration()
.createOrder( null, null, {
updateCartOptions: {
keepShipping: true,
},
} );
}
resolve({
countryCode: data.country_code,
currencyCode: data.currency_code,
totalPriceStatus: 'FINAL',
totalPrice: data.total_str
});
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()
);
}
}, 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(),
);
}
products() {
return this.actionHandler().getProducts();
}
products() {
return this.actionHandler().getProducts();
}
}
export default SingleProductHandler;

View file

@ -1,10 +1,12 @@
export function createAppleErrors(errors) {
const errorList = []
for (const error of errors) {
const {contactField = null, code = null, message = null} = error
const appleError = contactField ? new ApplePayError(code, contactField, message) : new ApplePayError(code)
errorList.push(appleError)
}
export function createAppleErrors( errors ) {
const errorList = [];
for ( const error of errors ) {
const { contactField = null, code = null, message = null } = error;
const appleError = contactField
? new ApplePayError( code, contactField, message )
: new ApplePayError( code );
errorList.push( appleError );
}
return errorList
return errorList;
}

View file

@ -1,8 +1,8 @@
export const buttonID = 'applepay-container';
export const endpoints = {
validation: '_apple_pay_validation',
createOrderCart: '_apple_pay_create_order_cart',
createOrderProduct: '_apple_pay_create_order_product',
updateShippingMethod: '_apple_pay_update_shipping_contact',
updateShippingContact: '_apple_pay_update_billing_contact',
}
validation: '_apple_pay_validation',
createOrderCart: '_apple_pay_create_order_cart',
createOrderProduct: '_apple_pay_create_order_product',
updateShippingMethod: '_apple_pay_update_shipping_contact',
updateShippingContact: '_apple_pay_update_billing_contact',
};

View file

@ -6,106 +6,118 @@ import PreviewButtonManager from '../../../ppcp-button/resources/js/modules/Rend
* Accessor that creates and returns a single PreviewButtonManager instance.
*/
const buttonManager = () => {
if (!ApplePayPreviewButtonManager.instance) {
ApplePayPreviewButtonManager.instance = new ApplePayPreviewButtonManager();
}
if ( ! ApplePayPreviewButtonManager.instance ) {
ApplePayPreviewButtonManager.instance =
new ApplePayPreviewButtonManager();
}
return ApplePayPreviewButtonManager.instance;
return ApplePayPreviewButtonManager.instance;
};
/**
* Manages all Apple Pay preview buttons on this page.
*/
class ApplePayPreviewButtonManager extends PreviewButtonManager {
constructor() {
const args = {
methodName: 'ApplePay',
buttonConfig: window.wc_ppcp_applepay_admin,
};
constructor() {
const args = {
methodName: 'ApplePay',
buttonConfig: window.wc_ppcp_applepay_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?.Applepay()?.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?.Applepay()?.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 {};
}
return await apiMethod();
}
return await apiMethod();
}
/**
* This method is responsible for creating a new PreviewButton instance and returning it.
*
* @param {string} wrapperId - CSS ID of the wrapper element.
* @return {ApplePayPreviewButton}
*/
createButtonInstance(wrapperId) {
return new ApplePayPreviewButton({
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 {ApplePayPreviewButton}
*/
createButtonInstance( wrapperId ) {
return new ApplePayPreviewButton( {
selector: wrapperId,
apiConfig: this.apiConfig,
} );
}
}
/**
* A single Apple Pay preview button instance.
*/
class ApplePayPreviewButton extends PreviewButton {
constructor(args) {
super(args);
constructor( args ) {
super( args );
this.selector = `${args.selector}ApplePay`;
this.defaultAttributes = {
button: {
type: 'pay',
color: 'black',
lang: 'en',
},
};
}
this.selector = `${ args.selector }ApplePay`;
this.defaultAttributes = {
button: {
type: 'pay',
color: 'black',
lang: 'en',
},
};
}
createNewWrapper() {
const element = super.createNewWrapper();
element.addClass('ppcp-button-applepay');
createNewWrapper() {
const element = super.createNewWrapper();
element.addClass( 'ppcp-button-applepay' );
return element;
}
return element;
}
createButton(buttonConfig) {
const button = new ApplepayButton('preview', null, buttonConfig, this.ppcpConfig);
createButton( buttonConfig ) {
const button = new ApplepayButton(
'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) {
// The Apple Pay button expects the "wrapper" to be an ID without `#` prefix!
buttonConfig.button.wrapper = buttonConfig.button.wrapper.replace(/^#/, '');
/**
* Merge form details into the config object for preview.
* Mutates the previewConfig object; no return value.
* @param buttonConfig
* @param ppcpConfig
*/
dynamicPreviewConfig( buttonConfig, ppcpConfig ) {
// The Apple Pay button expects the "wrapper" to be an ID without `#` prefix!
buttonConfig.button.wrapper = buttonConfig.button.wrapper.replace(
/^#/,
''
);
// Merge the current form-values into the preview-button configuration.
if (ppcpConfig.button) {
buttonConfig.button.type = ppcpConfig.button.style.type;
buttonConfig.button.color = ppcpConfig.button.style.color;
buttonConfig.button.lang =
ppcpConfig.button.style?.lang || ppcpConfig.button.style.language;
}
}
// Merge the current form-values into the preview-button configuration.
if ( ppcpConfig.button ) {
buttonConfig.button.type = ppcpConfig.button.style.type;
buttonConfig.button.color = ppcpConfig.button.style.color;
buttonConfig.button.lang =
ppcpConfig.button.style?.lang ||
ppcpConfig.button.style.language;
}
}
}
// Initialize the preview button manager.

View file

@ -1,79 +1,81 @@
import {useEffect, useState} from '@wordpress/element';
import {registerExpressPaymentMethod} from '@woocommerce/blocks-registry';
import {loadPaypalScript} from '../../../ppcp-button/resources/js/modules/Helper/ScriptLoading'
import {cartHasSubscriptionProducts} from '../../../ppcp-blocks/resources/js/Helper/Subscription'
import {loadCustomScript} from "@paypal/paypal-js";
import CheckoutHandler from "./Context/CheckoutHandler";
import ApplepayManager from "./ApplepayManager";
import ApplepayManagerBlockEditor from "./ApplepayManagerBlockEditor";
import { useEffect, useState } from '@wordpress/element';
import { registerExpressPaymentMethod } from '@woocommerce/blocks-registry';
import { loadPaypalScript } from '../../../ppcp-button/resources/js/modules/Helper/ScriptLoading';
import { cartHasSubscriptionProducts } from '../../../ppcp-blocks/resources/js/Helper/Subscription';
import { loadCustomScript } from '@paypal/paypal-js';
import CheckoutHandler from './Context/CheckoutHandler';
import ApplepayManager from './ApplepayManager';
import ApplepayManagerBlockEditor from './ApplepayManagerBlockEditor';
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-applepay_data');
const buttonData = wc.wcSettings.getSetting( 'ppcp-applepay_data' );
const buttonConfig = buttonData.scriptData;
if (typeof window.PayPalCommerceGateway === 'undefined') {
window.PayPalCommerceGateway = ppcpConfig;
if ( typeof window.PayPalCommerceGateway === 'undefined' ) {
window.PayPalCommerceGateway = ppcpConfig;
}
const ApplePayComponent = ( props ) => {
const [bootstrapped, setBootstrapped] = useState(false);
const [paypalLoaded, setPaypalLoaded] = useState(false);
const [applePayLoaded, setApplePayLoaded] = useState(false);
const [ bootstrapped, setBootstrapped ] = useState( false );
const [ paypalLoaded, setPaypalLoaded ] = useState( false );
const [ applePayLoaded, setApplePayLoaded ] = useState( false );
const bootstrap = function () {
const ManagerClass = props.isEditing ? ApplepayManagerBlockEditor : ApplepayManager;
const manager = new ManagerClass(buttonConfig, ppcpConfig);
manager.init();
};
const bootstrap = function () {
const ManagerClass = props.isEditing
? ApplepayManagerBlockEditor
: ApplepayManager;
const manager = new ManagerClass( buttonConfig, ppcpConfig );
manager.init();
};
useEffect(() => {
// Load ApplePay SDK
loadCustomScript({ url: buttonConfig.sdk_url }).then(() => {
setApplePayLoaded(true);
});
useEffect( () => {
// Load ApplePay SDK
loadCustomScript( { url: buttonConfig.sdk_url } ).then( () => {
setApplePayLoaded( true );
} );
ppcpConfig.url_params.components += ',applepay';
ppcpConfig.url_params.components += ',applepay';
// Load PayPal
loadPaypalScript(ppcpConfig, () => {
setPaypalLoaded(true);
});
}, []);
// Load PayPal
loadPaypalScript( ppcpConfig, () => {
setPaypalLoaded( true );
} );
}, [] );
useEffect(() => {
if (!bootstrapped && paypalLoaded && applePayLoaded) {
setBootstrapped(true);
bootstrap();
}
}, [paypalLoaded, applePayLoaded]);
useEffect( () => {
if ( ! bootstrapped && paypalLoaded && applePayLoaded ) {
setBootstrapped( true );
bootstrap();
}
}, [ paypalLoaded, applePayLoaded ] );
return (
<div
id={buttonConfig.button.wrapper.replace('#', '')}
className="ppcp-button-apm ppcp-button-applepay">
</div>
);
}
return (
<div
id={ buttonConfig.button.wrapper.replace( '#', '' ) }
className="ppcp-button-apm ppcp-button-applepay"
></div>
);
};
const features = ['products'];
const features = [ 'products' ];
if (
cartHasSubscriptionProducts(ppcpConfig)
&& (new CheckoutHandler(buttonConfig, ppcpConfig)).isVaultV3Mode()
cartHasSubscriptionProducts( ppcpConfig ) &&
new CheckoutHandler( buttonConfig, ppcpConfig ).isVaultV3Mode()
) {
features.push('subscriptions');
features.push( 'subscriptions' );
}
registerExpressPaymentMethod({
name: buttonData.id,
label: <div dangerouslySetInnerHTML={{__html: buttonData.title}}/>,
content: <ApplePayComponent isEditing={false}/>,
edit: <ApplePayComponent isEditing={true}/>,
ariaLabel: buttonData.title,
canMakePayment: () => buttonData.enabled,
supports: {
features: features,
},
});
registerExpressPaymentMethod( {
name: buttonData.id,
label: <div dangerouslySetInnerHTML={ { __html: buttonData.title } } />,
content: <ApplePayComponent isEditing={ false } />,
edit: <ApplePayComponent isEditing={ true } />,
ariaLabel: buttonData.title,
canMakePayment: () => buttonData.enabled,
supports: {
features,
},
} );

View file

@ -1,71 +1,62 @@
import {loadCustomScript} from "@paypal/paypal-js";
import {loadPaypalScript} from "../../../ppcp-button/resources/js/modules/Helper/ScriptLoading";
import ApplepayManager from "./ApplepayManager";
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 ApplepayManager from './ApplepayManager';
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 ApplepayManager( buttonConfig, ppcpConfig );
manager.init();
};
const bootstrap = function () {
manager = new ApplepayManager(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'
) {
return;
}
const isMiniCart = ppcpConfig.mini_cart_buttons_enabled;
const isButton = jQuery( '#' + buttonConfig.button.wrapper ).length > 0;
// If button wrapper is not present then there is no need to load the scripts.
// minicart loads later?
if ( ! isMiniCart && ! isButton ) {
return;
}
document.addEventListener(
'DOMContentLoaded',
() => {
if (
(typeof (buttonConfig) === 'undefined') ||
(typeof (ppcpConfig) === 'undefined')
) {
return;
}
const isMiniCart = ppcpConfig.mini_cart_buttons_enabled;
const isButton = jQuery('#' + buttonConfig.button.wrapper).length > 0;
// If button wrapper is not present then there is no need to load the scripts.
// minicart loads later?
if (!isMiniCart && !isButton) {
return;
}
let bootstrapped = false;
let paypalLoaded = false;
let applePayLoaded = false;
let bootstrapped = false;
let paypalLoaded = false;
let applePayLoaded = false;
const tryToBoot = () => {
if ( ! bootstrapped && paypalLoaded && applePayLoaded ) {
bootstrapped = true;
bootstrap();
}
};
const tryToBoot = () => {
if (!bootstrapped && paypalLoaded && applePayLoaded) {
bootstrapped = true;
bootstrap();
}
}
// Load ApplePay SDK
loadCustomScript( { url: buttonConfig.sdk_url } ).then( () => {
applePayLoaded = true;
tryToBoot();
} );
// Load ApplePay SDK
loadCustomScript({ url: buttonConfig.sdk_url }).then(() => {
applePayLoaded = true;
tryToBoot();
});
// Load PayPal
loadPaypalScript(ppcpConfig, () => {
paypalLoaded = true;
tryToBoot();
});
},
);
})({
buttonConfig: window.wc_ppcp_applepay,
ppcpConfig: window.PayPalCommerceGateway,
jQuery: window.jQuery
});
// Load PayPal
loadPaypalScript( ppcpConfig, () => {
paypalLoaded = true;
tryToBoot();
} );
} );
} )( {
buttonConfig: window.wc_ppcp_applepay,
ppcpConfig: window.PayPalCommerceGateway,
jQuery: window.jQuery,
} );