Axo: Add PayPal Insights to the Block Checkout and fix the existing Classic Checkout integration

This commit is contained in:
Daniel Dudzic 2024-10-29 11:04:41 +01:00
parent c89da49e8f
commit 1204edb1ca
No known key found for this signature in database
GPG key ID: 31B40D33E3465483
12 changed files with 570 additions and 119 deletions

View file

@ -1,35 +1,259 @@
import { registerPlugin } from '@wordpress/plugins';
import { useEffect, useCallback, useState, useRef } from '@wordpress/element';
import { useSelect } from '@wordpress/data';
import { useEffect, useState } from '@wordpress/element';
import { PAYMENT_STORE_KEY } from '@woocommerce/block-data';
import PayPalInsights from '../../../../ppcp-axo/resources/js/Insights/PayPalInsights';
import { STORE_NAME } from '../stores/axoStore';
import usePayPalCommerceGateway from '../hooks/usePayPalCommerceGateway';
const PayPalInsightsLoader = () => {
const GATEWAY_HANDLE = 'ppcp-axo-gateway';
// Subscribe to checkout store data
const checkoutData = useSelect( ( select ) => {
return {
paymentMethod: select( 'wc/store/checkout' ).getPaymentMethod(),
orderTotal: select( 'wc/store/checkout' ).getOrderTotal(),
// Add other data points you need
};
const useEventTracking = () => {
const [ triggeredEvents, setTriggeredEvents ] = useState( {
initialized: false,
jsLoaded: false,
beginCheckout: false,
emailSubmitted: false,
} );
// Watch for changes and trigger analytics events
useEffect( () => {
if ( isScriptLoaded && window.YourAnalyticsObject ) {
// Example tracking calls
window.YourAnalyticsObject.track( 'checkout_updated', {
payment_method: checkoutData.paymentMethod,
order_total: checkoutData.orderTotal,
} );
}
}, [ isScriptLoaded, checkoutData ] );
const currentPaymentMethod = useRef( null );
return null; // This component doesn't render anything
const setEventTriggered = useCallback( ( eventName, value = true ) => {
setTriggeredEvents( ( prev ) => ( {
...prev,
[ eventName ]: value,
} ) );
}, [] );
const isEventTriggered = useCallback(
( eventName ) => triggeredEvents[ eventName ],
[ triggeredEvents ]
);
const setCurrentPaymentMethod = useCallback( ( methodName ) => {
currentPaymentMethod.current = methodName;
}, [] );
const getCurrentPaymentMethod = useCallback(
() => currentPaymentMethod.current,
[]
);
return {
setEventTriggered,
isEventTriggered,
setCurrentPaymentMethod,
getCurrentPaymentMethod,
};
};
const waitForPayPalInsight = () => {
return new Promise( ( resolve, reject ) => {
// If already loaded, resolve immediately
if ( window.paypalInsight ) {
resolve( window.paypalInsight );
return;
}
// Set a reasonable timeout
const timeoutId = setTimeout( () => {
observer.disconnect();
reject( new Error( 'PayPal Insights script load timeout' ) );
}, 10000 );
// Create MutationObserver to watch for script initialization
const observer = new MutationObserver( () => {
if ( window.paypalInsight ) {
observer.disconnect();
clearTimeout( timeoutId );
resolve( window.paypalInsight );
}
} );
// Start observing
observer.observe( document, {
childList: true,
subtree: true,
} );
} );
};
const usePayPalInsightsInit = ( axoConfig, ppcpConfig, eventTracking ) => {
const { setEventTriggered, isEventTriggered } = eventTracking;
const initialized = useRef( false );
useEffect( () => {
if (
! axoConfig?.insights?.enabled ||
! axoConfig?.insights?.client_id ||
! axoConfig?.insights?.session_id ||
initialized.current ||
isEventTriggered( 'initialized' )
) {
return;
}
const initializePayPalInsights = async () => {
try {
await waitForPayPalInsight();
if ( initialized.current ) {
return;
}
// Track JS load first
PayPalInsights.trackJsLoad();
setEventTriggered( 'jsLoaded' );
PayPalInsights.config( axoConfig.insights.client_id, {
debug: axoConfig?.wp_debug === '1',
} );
PayPalInsights.setSessionId( axoConfig.insights.session_id );
initialized.current = true;
setEventTriggered( 'initialized' );
if (
isEventTriggered( 'jsLoaded' ) &&
! isEventTriggered( 'beginCheckout' )
) {
PayPalInsights.trackBeginCheckout( {
amount: axoConfig.insights.amount,
page_type: 'checkout',
user_data: {
country: 'US',
is_store_member: false,
},
} );
setEventTriggered( 'beginCheckout' );
}
} catch ( error ) {
console.error(
'PayPal Insights initialization failed:',
error
);
}
};
initializePayPalInsights();
return () => {
initialized.current = false;
};
}, [ axoConfig, ppcpConfig, setEventTriggered, isEventTriggered ] );
};
const usePaymentMethodTracking = ( axoConfig, eventTracking ) => {
const { setCurrentPaymentMethod } = eventTracking;
const lastPaymentMethod = useRef( null );
const isInitialMount = useRef( true );
const activePaymentMethod = useSelect( ( select ) => {
return select( PAYMENT_STORE_KEY )?.getActivePaymentMethod();
}, [] );
const handlePaymentMethodChange = useCallback(
async ( paymentMethod ) => {
// Skip if no payment method or same as last one
if (
! paymentMethod ||
paymentMethod === lastPaymentMethod.current
) {
return;
}
try {
await waitForPayPalInsight();
// Only track if it's not the initial mount, and we have a previous payment method
if ( ! isInitialMount.current && lastPaymentMethod.current ) {
PayPalInsights.trackSelectPaymentMethod( {
payment_method_selected:
axoConfig?.insights?.payment_method_selected_map[
paymentMethod
] || 'other',
page_type: 'checkout',
} );
}
lastPaymentMethod.current = paymentMethod;
setCurrentPaymentMethod( paymentMethod );
} catch ( error ) {
console.error( 'Failed to track payment method:', error );
}
},
[
axoConfig?.insights?.payment_method_selected_map,
setCurrentPaymentMethod,
]
);
useEffect( () => {
if ( activePaymentMethod ) {
if ( isInitialMount.current ) {
// Just set the initial payment method without tracking
lastPaymentMethod.current = activePaymentMethod;
setCurrentPaymentMethod( activePaymentMethod );
isInitialMount.current = false;
} else {
handlePaymentMethodChange( activePaymentMethod );
}
}
}, [
activePaymentMethod,
handlePaymentMethodChange,
setCurrentPaymentMethod,
] );
useEffect( () => {
return () => {
lastPaymentMethod.current = null;
isInitialMount.current = true;
};
}, [] );
};
const PayPalInsightsLoader = () => {
const eventTracking = useEventTracking();
const { setEventTriggered, isEventTriggered } = eventTracking;
const initialConfig =
window?.wc?.wcSettings?.getSetting( `${ GATEWAY_HANDLE }_data` ) || {};
const { ppcpConfig } = usePayPalCommerceGateway( initialConfig );
const axoConfig = window?.wc_ppcp_axo;
const { isEmailSubmitted } = useSelect( ( select ) => {
const storeSelect = select( STORE_NAME );
return {
isEmailSubmitted: storeSelect?.getIsEmailSubmitted?.() ?? false,
};
}, [] );
usePayPalInsightsInit( axoConfig, ppcpConfig, eventTracking );
usePaymentMethodTracking( axoConfig, eventTracking );
useEffect( () => {
const trackEmail = async () => {
if ( isEmailSubmitted && ! isEventTriggered( 'emailSubmitted' ) ) {
try {
await waitForPayPalInsight();
PayPalInsights.trackSubmitCheckoutEmail();
setEventTriggered( 'emailSubmitted' );
} catch ( error ) {
console.error( 'Failed to track email submission:', error );
}
}
};
trackEmail();
}, [ isEmailSubmitted, setEventTriggered, isEventTriggered ] );
return null;
};
// Register the plugin to run with the checkout block
registerPlugin( 'wc-ppcp-paypal-insights', {
render: PayPalInsightsLoader,
scope: 'woocommerce-checkout',
} );
export default PayPalInsightsLoader;

View file

@ -1,4 +1,4 @@
import { createReduxStore, register, dispatch } from '@wordpress/data';
import { createReduxStore, register, dispatch, select } from '@wordpress/data';
export const STORE_NAME = 'woocommerce-paypal-payments/axo-block';
@ -100,13 +100,15 @@ const selectors = {
};
// Create and register the Redux store for the AXO block
const store = createReduxStore( STORE_NAME, {
reducer,
actions,
selectors,
} );
if ( ! select( STORE_NAME ) ) {
const store = createReduxStore( STORE_NAME, {
reducer,
actions,
selectors,
} );
register( store );
register( store );
}
// Action dispatchers

View file

@ -37,6 +37,7 @@ return array(
$container->get( 'wcgateway.settings' ),
$container->get( 'wcgateway.configuration.dcc' ),
$container->get( 'onboarding.environment' ),
$container->get( 'axo.payment_method_selected_map' ),
$container->get( 'wcgateway.url' )
);
},

View file

@ -134,11 +134,11 @@ class AxoBlockModule implements ServiceModule, ExtendingModule, ExecutableModule
}
);
// Enqueue the PayPal Insights script
// Enqueue the PayPal Insights script.
add_action(
'wp_enqueue_scripts',
function () use ($c) {
$this->enqueue_paypal_insights_script($c);
function () use ( $c ) {
$this->enqueue_paypal_insights_script( $c );
}
);
@ -183,7 +183,7 @@ class AxoBlockModule implements ServiceModule, ExtendingModule, ExecutableModule
* @return void
*/
private function enqueue_paypal_insights_script( ContainerInterface $c ): void {
if ( ! has_block( 'woocommerce/checkout' ) ) {
if ( ! has_block( 'woocommerce/checkout' ) || WC()->cart->is_empty() ) {
return;
}
@ -192,7 +192,7 @@ class AxoBlockModule implements ServiceModule, ExtendingModule, ExecutableModule
wp_register_script(
'wc-ppcp-paypal-insights',
untrailingslashit( $module_url ) . '/resources/js/plugins/PayPalInsights.js',
untrailingslashit( $module_url ) . '/assets/js/PayPalInsightsLoader.js',
array( 'wp-plugins', 'wp-data', 'wp-element', 'wc-blocks-registry' ),
$asset_version,
true

View file

@ -72,6 +72,13 @@ class AxoBlockPaymentMethod extends AbstractPaymentMethodType {
*/
private $environment;
/**
* Mapping of payment methods to the PayPal Insights 'payment_method_selected' types.
*
* @var array
*/
private array $payment_method_selected_map;
/**
* The WcGateway module URL.
*
@ -90,6 +97,7 @@ class AxoBlockPaymentMethod extends AbstractPaymentMethodType {
* @param Settings $settings The settings.
* @param DCCGatewayConfiguration $dcc_configuration The DCC gateway settings.
* @param Environment $environment The environment object.
* @param array $payment_method_selected_map Mapping of payment methods to the PayPal Insights 'payment_method_selected' types.
* @param string $wcgateway_module_url The WcGateway module URL.
*/
public function __construct(
@ -100,17 +108,19 @@ class AxoBlockPaymentMethod extends AbstractPaymentMethodType {
Settings $settings,
DCCGatewayConfiguration $dcc_configuration,
Environment $environment,
array $payment_method_selected_map,
string $wcgateway_module_url
) {
$this->name = AxoGateway::ID;
$this->module_url = $module_url;
$this->version = $version;
$this->gateway = $gateway;
$this->smart_button = $smart_button;
$this->settings = $settings;
$this->dcc_configuration = $dcc_configuration;
$this->environment = $environment;
$this->wcgateway_module_url = $wcgateway_module_url;
$this->name = AxoGateway::ID;
$this->module_url = $module_url;
$this->version = $version;
$this->gateway = $gateway;
$this->smart_button = $smart_button;
$this->settings = $settings;
$this->dcc_configuration = $dcc_configuration;
$this->environment = $environment;
$this->payment_method_selected_map = $payment_method_selected_map;
$this->wcgateway_module_url = $wcgateway_module_url;
}
@ -194,18 +204,19 @@ class AxoBlockPaymentMethod extends AbstractPaymentMethodType {
'email' => 'render',
),
'insights' => array(
'enabled' => defined( 'WP_DEBUG' ) && WP_DEBUG,
'client_id' => ( $this->settings->has( 'client_id' ) ? $this->settings->get( 'client_id' ) : null ),
'session_id' =>
'enabled' => defined( 'WP_DEBUG' ) && WP_DEBUG,
'client_id' => ( $this->settings->has( 'client_id' ) ? $this->settings->get( 'client_id' ) : null ),
'session_id' =>
( WC()->session && method_exists( WC()->session, 'get_customer_unique_id' ) )
? substr( md5( WC()->session->get_customer_unique_id() ), 0, 16 )
: '',
'amount' => array(
'amount' => array(
'currency_code' => get_woocommerce_currency(),
'value' => ( WC()->cart && method_exists( WC()->cart, 'get_total' ) )
? WC()->cart->get_total( 'numeric' )
: null, // Set to null if WC()->cart is null or get_total doesn't exist.
: null,
),
'payment_method_selected_map' => $this->payment_method_selected_map,
),
'style_options' => array(
'root' => array(

View file

@ -9,7 +9,10 @@ module.exports = {
target: 'web',
plugins: [ new DependencyExtractionWebpackPlugin() ],
entry: {
'index': path.resolve( './resources/js/index.js' ),
index: path.resolve( './resources/js/index.js' ),
PayPalInsightsLoader: path.resolve(
'./resources/js/plugins/PayPalInsightsLoader.js'
),
gateway: path.resolve( './resources/css/gateway.scss' ),
},
output: {