woocommerce-paypal-payments/modules/ppcp-axo-block/resources/js/hooks/useCardChange.js

56 lines
1.6 KiB
JavaScript
Raw Normal View History

import { useCallback } from '@wordpress/element';
2024-09-13 22:30:04 +02:00
import { useAddressEditing } from './useAddressEditing';
2024-09-13 23:09:51 +02:00
import useCustomerData from './useCustomerData';
2024-09-13 23:09:51 +02:00
export const useCardChange = ( fastlaneSdk, setCard ) => {
2024-09-13 22:30:04 +02:00
const { setBillingAddressEditing } = useAddressEditing();
2024-09-13 23:09:51 +02:00
const { setBillingAddress: setWooBillingAddress } = useCustomerData();
2024-09-13 22:30:04 +02:00
return useCallback( async () => {
if ( fastlaneSdk ) {
const { selectionChanged, selectedCard } =
await fastlaneSdk.profile.showCardSelector();
if ( selectionChanged ) {
setCard( selectedCard );
console.log( 'Selected card changed:', selectedCard );
console.log( 'Setting new billing details:', selectedCard );
const { name, billingAddress } =
selectedCard.paymentSource.card;
// Split the full name into first and last name
const nameParts = name.split( ' ' );
const firstName = nameParts[ 0 ];
const lastName = nameParts.slice( 1 ).join( ' ' );
2024-09-13 22:30:04 +02:00
const newBillingAddress = {
first_name: firstName,
last_name: lastName,
address_1: billingAddress.addressLine1,
address_2: billingAddress.addressLine2 || '',
city: billingAddress.adminArea2,
state: billingAddress.adminArea1,
postcode: billingAddress.postalCode,
country: billingAddress.countryCode,
2024-09-13 22:30:04 +02:00
};
await new Promise( ( resolve ) => {
setWooBillingAddress( newBillingAddress );
resolve();
} );
2024-09-13 22:30:04 +02:00
await new Promise( ( resolve ) => {
setBillingAddressEditing( false );
resolve();
} );
}
}
2024-09-13 22:30:04 +02:00
}, [
fastlaneSdk,
setCard,
setWooBillingAddress,
setBillingAddressEditing,
] );
};
export default useCardChange;