woocommerce-paypal-payments/modules/ppcp-applepay/resources/js/boot.js

83 lines
2.1 KiB
JavaScript
Raw Normal View History

2024-07-12 12:58:34 +02:00
import { loadCustomScript } from '@paypal/paypal-js';
import { loadPayPalScript } from '../../../ppcp-button/resources/js/modules/Helper/PayPalScriptLoading';
import ApplePayManager from './ApplepayManager';
2024-07-12 12:58:34 +02:00
import { setupButtonEvents } from '../../../ppcp-button/resources/js/modules/Helper/ButtonRefreshHelper';
2024-10-07 15:16:01 +02:00
( function ( { buttonConfig, ppcpConfig } ) {
const namespace = 'ppcpPaypalApplepay';
2024-10-07 15:18:51 +02:00
function bootstrapPayButton() {
if ( ! buttonConfig || ! ppcpConfig ) {
return;
}
const manager = new ApplePayManager(
namespace,
buttonConfig,
ppcpConfig
);
2024-07-12 12:58:34 +02:00
setupButtonEvents( function () {
2024-07-12 12:58:34 +02:00
manager.reinit();
} );
2024-10-07 15:18:51 +02:00
}
2024-10-07 15:18:51 +02:00
function bootstrap() {
bootstrapPayButton();
// Other Apple Pay bootstrapping could happen here.
}
2024-07-12 12:58:34 +02:00
document.addEventListener( 'DOMContentLoaded', () => {
if ( ! buttonConfig || ! ppcpConfig ) {
/*
* No PayPal buttons present on this page, but maybe a bootstrap module needs to be
* initialized. Skip loading the SDK or gateway configuration, and directly initialize
* the module.
*/
bootstrap();
2024-07-12 12:58:34 +02:00
return;
}
2024-10-07 15:16:01 +02:00
2024-10-07 15:18:51 +02:00
const usedInMiniCart = ppcpConfig.mini_cart_buttons_enabled;
const pageHasButton =
2024-10-07 15:16:01 +02:00
null !== document.getElementById( buttonConfig.button.wrapper );
2024-07-12 12:58:34 +02:00
// If button wrapper is not present then there is no need to load the scripts.
// minicart loads later?
2024-10-07 15:18:51 +02:00
if ( ! usedInMiniCart && ! pageHasButton ) {
2024-07-12 12:58:34 +02:00
return;
}
let bootstrapped = false;
let paypalLoaded = false;
let applePayLoaded = false;
const tryToBoot = () => {
if ( ! bootstrapped && paypalLoaded && applePayLoaded ) {
bootstrapped = true;
bootstrap();
}
};
// Load ApplePay SDK
loadCustomScript( { url: buttonConfig.sdk_url } ).then( () => {
applePayLoaded = true;
tryToBoot();
} );
// Load PayPal
loadPayPalScript( namespace, ppcpConfig )
.then( () => {
paypalLoaded = true;
tryToBoot();
} )
.catch( ( error ) => {
console.error( 'Failed to load PayPal script: ', error );
} );
2024-07-12 12:58:34 +02:00
} );
} )( {
buttonConfig: window.wc_ppcp_applepay,
ppcpConfig: window.PayPalCommerceGateway,
} );