woocommerce-paypal-payments/modules/ppcp-googlepay/resources/js/GooglepayManager.js

86 lines
2.2 KiB
JavaScript
Raw Normal View History

2024-07-15 11:21:56 +02:00
import buttonModuleWatcher from '../../../ppcp-button/resources/js/modules/ButtonModuleWatcher';
import GooglepayButton from './GooglepayButton';
import ContextHandlerFactory from './Context/ContextHandlerFactory';
2023-08-22 11:34:52 +01:00
class GooglepayManager {
2024-07-15 11:21:56 +02:00
constructor( buttonConfig, ppcpConfig ) {
this.buttonConfig = buttonConfig;
this.ppcpConfig = ppcpConfig;
this.googlePayConfig = null;
this.transactionInfo = null;
this.contextHandler = null;
2023-08-22 11:34:52 +01:00
2024-07-15 11:21:56 +02:00
this.buttons = [];
2023-08-22 11:34:52 +01:00
2024-07-15 11:21:56 +02:00
buttonModuleWatcher.watchContextBootstrap( async ( bootstrap ) => {
if ( ! this.contextHandler ) {
this.contextHandler = ContextHandlerFactory.create(
bootstrap.context,
buttonConfig,
ppcpConfig,
bootstrap.handler
);
}
2023-08-22 11:34:52 +01:00
2024-07-15 11:21:56 +02:00
const button = new GooglepayButton(
bootstrap.context,
bootstrap.handler,
buttonConfig,
ppcpConfig,
this.contextHandler
);
2023-08-28 17:19:07 +01:00
2024-07-15 11:21:56 +02:00
this.buttons.push( button );
2024-07-15 11:21:56 +02:00
// 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 );
}
}
} );
}
2023-08-22 11:34:52 +01:00
2024-07-15 11:21:56 +02:00
async init() {
try {
if ( ! this.googlePayConfig ) {
// Gets GooglePay configuration of the PayPal merchant.
this.googlePayConfig = await paypal.Googlepay().config();
}
2023-08-22 11:34:52 +01:00
2024-07-15 11:21:56 +02:00
if ( ! this.transactionInfo ) {
this.transactionInfo = await this.fetchTransactionInfo();
}
2023-08-22 11:34:52 +01:00
2024-07-15 11:21:56 +02:00
for ( const button of this.buttons ) {
button.init( this.googlePayConfig, this.transactionInfo );
}
} catch ( error ) {
console.error( 'Error during initialization:', error );
}
}
2024-07-15 11:21:56 +02:00
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;
}
}
2024-07-15 11:21:56 +02:00
reinit() {
for ( const button of this.buttons ) {
button.reinit();
}
}
2023-08-22 11:34:52 +01:00
}
export default GooglepayManager;