export const CheckoutComApplePayButton = () => {
const applePaySession = window.ApplePaySession;
const [canPayWithApplePay, setCanPayWithApplePay] = useState(false);
useEffect(() => {
// Check that the payment can be made with Apple Pay
if (applePaySession && applePaySession.canMakePayments()) {
setCanPayWithApplePay(true);
} else {
setCanPayWithApplePay(false);
}
}, [applePaySession]);
const handleClick = useHandleClick();
if (!canPayWithApplePay) {
return null;
}
return (
<div>
<div
className="apple-pay-button apple-pay-button-black"
lang='en'
onClick={handleClick}
></div>
{error && (
<strong className="block my-4 text-red-600 text-lg font-normal">
{error}
</strong>
)}
</div>
);
};
const useHandleClick = () => {
const { createPayment } = useCreatePayment();
return () => {
// Create the Apple Pay session
// see https://developer.apple.com/documentation/apple_pay_on_the_web/applepaysession
const session = new window.ApplePaySession(6, {
countryCode: 'US',
currencyCode: 'USD',
supportedNetworks: ['visa', 'masterCard'],
merchantCapabilities: ['supports3DS'],
total: {
label: 'My Store',
amount: '11.23'
}
});
// The event that occurs when you click the Apple Pay button
session.onvalidatemerchant = event => {
const validationURL = event.validationURL;
// "validateApplePaySession" should send the POST request to "/api/payment/checkout-com/wallet-session/applepay/validate?validateSessionUrl={validationURL}"
validateApplePaySession(validationURL)
.then(merchantSession => {
session.completeMerchantValidation(merchantSession);
})
.catch(error => {
console.error(error);
session.completePayment(window.ApplePaySession.STATUS_FAILURE);
});
};
// The event that occurs when the payment is authorized
session.onpaymentauthorized = event => {
const applePaymentToken = event.payment.token.paymentData;
createPayment(JSON.stringify(applePaymentToken), session);
};
session.begin();
};
};
const useCreatePayment = () => {
const createPayment = async (
applePaymentToken,
appleSession
) => {
const paymentRequest = {
name: 'Apple Pay',
type: 'APPLE_PAY',
gatewayType: 'CHECKOUT_COM',
amount: '11.23',
paymentMethodProperties: {
apple_pay_token: applePaymentToken
}
};
let paymentSummary;
try {
paymentSummary = await handleSubmitPaymentInfo(paymentRequest);
if (paymentSummary) {
appleSession.completePayment(window.ApplePaySession.STATUS_SUCCESS);
}
} catch (err) {
console.error('There was an error adding payment information', err);
appleSession.completePayment(window.ApplePaySession.STATUS_FAILURE);
}
};
return { createPayment };
};