Skip to content

Commit

Permalink
Shared normalization and event handlers for shortcode and blocks code
Browse files Browse the repository at this point in the history
  • Loading branch information
ricardo committed Apr 20, 2021
1 parent 789a27b commit 9aec227
Show file tree
Hide file tree
Showing 7 changed files with 323 additions and 352 deletions.
22 changes: 19 additions & 3 deletions client/checkout/api/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -290,19 +290,35 @@ export default class WCPayAPI {
} );
}

/**
* Updates cart with selected shipping option.
*
* @param {integer} shippingOption Shipping option id.
* @return {Promise} Promise for the request to the server.
*/
paymentRequestUpdateShippingDetails( shippingOption ) {
return this.request( '/?wc-ajax=wcpay_update_shipping_method', {
security: wcpayPaymentRequestParams.nonce.update_shipping,
/* eslint-disable camelcase */
shipping_method: [ shippingOption.id ],
is_product_page: wcpayPaymentRequestParams.is_product_page,
/* eslint-enable camelcase */
} ).then( ( response ) => {
return JSON.parse( response );
} );
}

/**
* Creates order based on Payment Request payment method.
*
* @param {string} paymentRequestType Payment Request type: 'apple_pay'|'google_pay'|'payment_request_api'
* @param {Object} paymentData Order data.
* @return {Promise} Promise for the request to the server.
*/
paymentRequestCreateOrder( paymentRequestType, paymentData ) {
paymentRequestCreateOrder( paymentData ) {
// - TODO: Get Ajax endpoint and nonce from helper function.
return this.request( '/?wc-ajax=wcpay_create_order', {
_wpnonce: wcpayPaymentRequestParams.nonce.checkout,
// eslint-disable-next-line camelcase
payment_request_type: paymentRequestType,
...paymentData,
} ).then( ( response ) => {
return JSON.parse( response );
Expand Down
163 changes: 53 additions & 110 deletions client/payment-request/blocks/use-initialization.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
/**
* External dependencies
*/
import { useEffect, useState, useRef, useCallback } from '@wordpress/element';
import { useEffect, useState, useCallback } from '@wordpress/element';
import { useStripe } from '@stripe/react-stripe-js';
import { __ } from '@wordpress/i18n';
import isShallowEqual from '@wordpress/is-shallow-equal';
// import isShallowEqual from '@wordpress/is-shallow-equal';

/**
* Internal dependencies
Expand All @@ -13,14 +13,16 @@ import {
getPaymentRequest,
updatePaymentRequest,
canDoPaymentRequest,
normalizeShippingAddressForCheckout,
normalizeShippingOptionSelectionsForCheckout,
normalizeShippingOptions,
normalizeOrderDataForCheckout,
getErrorMessageFromNotice,
pluckAddress,
} from '../stripe-utils';
import { useEventHandlers } from './use-event-handlers';

import {
shippingAddressChangeHandler,
shippingOptionChangeHandler,
paymentMethodHandler,
} from '../event-handlers.js';

// import { useEventHandlers } from './use-event-handlers';

/**
* @typedef {import('../stripe-utils/type-defs').StripePaymentRequest} StripePaymentRequest
Expand All @@ -46,17 +48,6 @@ export const useInitialization = ( {
const [ isProcessing, setIsProcessing ] = useState( false );
const [ canMakePayment, setCanMakePayment ] = useState( false );
const [ paymentRequestType, setPaymentRequestType ] = useState( '' );
const currentShipping = useRef( shippingData );
const {
paymentRequestEventHandlers,
clearPaymentRequestEventHandler,
setPaymentRequestEventHandler,
} = useEventHandlers();

// Update refs when any change.
useEffect( () => {
currentShipping.current = shippingData;
}, [ shippingData ] );

// Create the initial paymentRequest object. Note, we can't do anything if stripe isn't available yet or we have zero total.
useEffect( () => {
Expand Down Expand Up @@ -143,106 +134,58 @@ export const useInitialization = ( {
onClose();
};

const shippingAddressChangeHandler = async ( event ) => {
const newShippingAddress = normalizeShippingAddressForCheckout(
event.shippingAddress
);
if (
isShallowEqual(
pluckAddress( newShippingAddress ),
pluckAddress( currentShipping.current.shippingAddress )
)
) {
// the address is the same so no change needed.
event.updateWith( {
status: 'success',
shippingOptions: normalizeShippingOptions(
currentShipping.current.shippingRates
),
} );
} else {
// the address is different so let's set the new address and
// register the handler to be picked up by the shipping rate
// change event.
const response = await api.paymentRequestCalculateShippingOptions(
newShippingAddress
);

event.updateWith( {
status: response.result,
shippingOptions: response.shipping_options,
total: response.total,
displayItems: response.displayItems,
} );

setPaymentRequestEventHandler(
'shippingAddressChange',
event
);
}
};

const shippingOptionChangeHandler = ( event ) => {
currentShipping.current.setSelectedRates(
normalizeShippingOptionSelectionsForCheckout(
event.shippingOption
)
);
setPaymentRequestEventHandler( 'shippingOptionChange', event );
};

const paymentMethodHandler = async ( paymentMethod ) => {
// We retrieve `allowPrepaidCard` like this to ensure we default to false in the
// event `allowPrepaidCard` isn't present on the server data object.
// - TODO: Get prepaid card
// const { allowPrepaidCard = false } = getStripeServerData();
const allowPrepaidCard = true;
if ( ! allowPrepaidCard && paymentMethod.source.card.funding ) {
setExpressPaymentError(
__(
"Sorry, we're not accepting prepaid cards at this time.",
'woocommerce-gateway-stripe'
)
);
return;
}

// Kick off checkout processing step.
const response = await api.paymentRequestCreateOrder(
paymentRequestType,
normalizeOrderDataForCheckout( paymentMethod )
);

setPaymentRequestEventHandler(
'paymentMethodEvent',
paymentMethod
);

if ( 'success' === response.result ) {
paymentMethod.complete( 'success' );
window.location = response.redirect;
} else {
paymentMethod.complete( 'fail' );
setExpressPaymentError(
getErrorMessageFromNotice( response.messages )
);
}
};
// const paymentMethodHandler = async ( paymentMethod ) => {
// // We retrieve `allowPrepaidCard` like this to ensure we default to false in the
// // event `allowPrepaidCard` isn't present on the server data object.
// // - TODO: Get prepaid card
// // const { allowPrepaidCard = false } = getStripeServerData();
// const allowPrepaidCard = true;
// if ( ! allowPrepaidCard && paymentMethod.source.card.funding ) {
// setExpressPaymentError(
// __(
// "Sorry, we're not accepting prepaid cards at this time.",
// 'woocommerce-gateway-stripe'
// )
// );
// return;
// }

// // Kick off checkout processing step.
// const response = await api.paymentRequestCreateOrder(
// paymentRequestType,
// normalizeOrderDataForCheckout( paymentMethod )
// );

// // setPaymentRequestEventHandler(
// // 'paymentMethodEvent',
// // paymentMethod
// // );

// if ( 'success' === response.result ) {
// paymentMethod.complete( 'success' );
// window.location = response.redirect;
// } else {
// paymentMethod.complete( 'fail' );
// setExpressPaymentError(
// getErrorMessageFromNotice( response.messages )
// );
// }
// };

// @ts-ignore
shippingAddressChangeEvent = paymentRequest.on(
'shippingaddresschange',
shippingAddressChangeHandler
( event ) => shippingAddressChangeHandler( api, event )
);
// @ts-ignore
shippingOptionChangeEvent = paymentRequest.on(
'shippingoptionchange',
shippingOptionChangeHandler
( event ) => shippingOptionChangeHandler( api, event )
);
// @ts-ignore
paymentMethodChangeEvent = paymentRequest.on(
'paymentmethod',
paymentMethodHandler
( event ) => paymentMethodHandler( api, event )
);
// @ts-ignore
cancelChangeEvent = paymentRequest.on( 'cancel', cancelHandler );
Expand All @@ -260,16 +203,16 @@ export const useInitialization = ( {
paymentRequest,
canMakePayment,
isProcessing,
setPaymentRequestEventHandler,
// setPaymentRequestEventHandler,
setExpressPaymentError,
onSubmit,
onClose,
] );

return {
paymentRequest,
paymentRequestEventHandlers,
clearPaymentRequestEventHandler,
// paymentRequestEventHandlers,
// clearPaymentRequestEventHandler,
isProcessing,
canMakePayment,
onButtonClick,
Expand Down
75 changes: 75 additions & 0 deletions client/payment-request/event-handlers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
/**
* Internal dependencies
*/
import { normalizeShippingAddress, normalizeOrderData } from './utils';

const shippingAddressChangeHandler = async ( api, event ) => {
const response = await api.paymentRequestCalculateShippingOptions(
normalizeShippingAddress( event.shippingAddress )
);

// Possible statuses success, fail, invalid_payer_name, invalid_payer_email, invalid_payer_phone, invalid_shipping_address.
event.updateWith( {
status: response.result,
shippingOptions: response.shipping_options,
total: response.total,
displayItems: response.displayItems,
} );
};

const shippingOptionChangeHandler = async ( api, event ) => {
const response = await api.paymentRequestUpdateShippingDetails( event );

if ( 'success' === response.result ) {
event.updateWith( {
status: 'success',
total: response.total,
displayItems: response.displayItems,
} );
}

if ( 'fail' === response.result ) {
event.updateWith( { status: 'fail' } );
}
};

const paymentMethodHandler = async ( api, event ) => {
// We retrieve `allowPrepaidCard` like this to ensure we default to false in the
// event `allowPrepaidCard` isn't present on the server data object.
// - TODO: Get prepaid card
// const { allowPrepaidCard = false } = getStripeServerData();
const allowPrepaidCard = true;
if ( ! allowPrepaidCard && 'prepaid' === event.source.card.funding ) {
event.complete( 'fail' );
// - TODO: Fix error message
// setExpressPaymentError(
// __(
// "Sorry, we're not accepting prepaid cards at this time.",
// 'woocommerce-gateway-stripe'
// )
// );
return;
}

// Kick off checkout processing step.
const response = await api.paymentRequestCreateOrder(
normalizeOrderData( event )
);

if ( 'success' === response.result ) {
event.complete( 'success' );
window.location = response.redirect;
} else {
event.complete( 'fail' );
// - TODO: Fix error message
// setExpressPaymentError(
// getErrorMessageFromNotice( response.messages )
// );
}
};

export {
shippingAddressChangeHandler,
shippingOptionChangeHandler,
paymentMethodHandler,
};
Loading

0 comments on commit 9aec227

Please sign in to comment.