Integration
Initial Setup
Step 1: Add the Apple Pay Script
Include the following script tag in the <head>
section of your HTML page:
<script src='https://test-pay.dnapayments.com/components/apple-pay/apple-pay-component.js'></script>
Step 2: Create a DOM Element
Create a container where the Apple Pay Express Checkout button will be rendered:
<div id='apple-pay-btn-container'></div>
Step 3: Set up Apple Pay Express Checkout to provide the shopper's details
Create a payload that sets the requiredBillingContactFields
, requiredShippingContactFields
and
shipping methods:
const payload = {
requiredShippingContactFields: ['postalAddress', 'email', 'phone'],
requiredBillingContactFields: ['postalAddress'],
shippingMethods: [
{
'label': 'Free Shipping',
'detail': 'Arrives in 5 to 7 days',
'amount': '0.00',
'identifier': 'FreeShip'
},
{
'label': 'Fast Shipping',
'detail': 'Arrives in 2 days',
'amount': '5.00',
'identifier': 'FastShip'
},
{
'label': 'Collect yourself',
'detail': 'Collect today',
'amount': '0.00',
'identifier': 'Collect'
}
]
};
Event Handlers for Apple Pay Express Checkout
Step 4: Handling the onClick Event
The onClick
event is triggered when the Apple Pay Express Checkout button is clicked. You can use this handler to manage the click event:
function onClick() {
console.log('Apple Pay button has been clicked');
}
Step 5: Handling Errors with onError
The onError
event handles errors that occur during the Apple Pay process. It is essential to handle these errors gracefully to ensure a good user experience:
function onError(error) {
console.log('Error occurred:', error);
// Implement additional error handling logic
}
Step 6: Handling the onCancel Event
The onCancel
event is triggered when a user cancels the Apple Pay transaction. Implement this callback to reset the checkout process or notify the user:
function onCancel(event) {
console.log('Payment was cancelled:', event);
// Reset the checkout state
}
Step 7: Handling the onShippingContactSelected Event
The onShippingContactSelected
event is triggered when the user selects or updates the shipping address. This event allows you to adjust the shipping methods and total amount accordingly:
async function onShippingContactSelected(resolve, reject, event) {
const { countryCode } = event.shippingContact;
if (countryCode !== 'GB') {
const update = {
newTotal: {
amount: 'NEW_PAYMENT_AMOUNT', // Adjusted total amount
type: 'final'
},
errors: [new ApplePayError('shippingContactInvalid', 'countryCode', 'Cannot ship to the selected Country')]
};
resolve(update);
return;
}
const update = {
newTotal: {
amount: 'NEW_PAYMENT_AMOUNT',
type: 'final'
},
newShippingMethods: [
{
'label': 'Fast Shipping',
'detail': 'Arrives in 2 days',
'amount': '5.00',
'identifier': 'FastShip'
},
{
'label': 'Collect yourself',
'detail': 'Collect today',
'amount': '0.00',
'identifier': 'Collect'
}
]
};
resolve(update);
}
Step 8: Handling the onShippingMethodSelected Event
The onShippingMethodSelected
event is triggered when the user selects a shipping method. You can use this event to update the total amount based on the selected shipping method:
async function onShippingMethodSelected(resolve, reject, event) {
const shippingMethod = event?.shippingMethod;
const update = {
newTotal: {
amount: 'OLD_PAYMENT_AMOUNT' + parseFloat(shippingMethod.amount),
type: 'final'
}
};
resolve(update);
}
Step 9: Handling the onPaymentSuccess Event
The onPaymentSuccess
event is triggered when a payment is successfully processed. Use this handler to finalize the transaction and retrieve customer details:
function onPaymentSuccess(result) {
console.log('Payment has successfully been processed', result);
// Implement further actions such as redirecting to a success page or storing the payment details
}
Step 10: Creating a Combined Events Object
You can create an events object that consolidates all event handlers for easier management:
const events = {
onClick,
onError,
onPaymentSuccess,
onCancel,
onShippingContactSelected,
onShippingMethodSelected
};
Button Initialization
Step 11: Configure paymentData
Before initializing the Apple Pay Express Checkout button, you need to configure the paymentData
object, which contains the details of the payment transaction, such as the currency, amount, and customer details.
const paymentData = {
currency: 'GBP', // The currency of the transaction
description: 'Shoes', // A brief description of the items or services being purchased
paymentSettings: {
terminalId: 'YOUR_TERMINAL_ID', // Your terminal ID
returnUrl: 'https://example.com/success.html', // URL to redirect upon successful payment
failureReturnUrl: 'https://example.com/failure.html', // URL to redirect upon payment failure
callbackUrl: 'https://example.com/callback', // URL for server-to-server callbacks
failureCallbackUrl: 'https://example.com/failure-callback' // URL for handling callback failures
},
customerDetails: {
accountDetails: {
accountId: 'uuid000001' // Unique identifier for the customer account
},
billingAddress: {
firstName: 'John',
lastName: 'Doe',
addressLine1: 'Fulham Rd',
postalCode: 'SW6 1HS',
city: 'London',
country: 'GB'
},
deliveryDetails: {
deliveryAddress: {
firstName: 'John',
lastName: 'Doe',
addressLine1: 'Fulham Rd',
addressLine2: 'Fulham',
postalCode: 'SW6 1HS',
city: 'London',
phone: '0475662834',
country: 'GB'
}
},
email: 'example@email.com',
mobilePhone: '+441234567890'
},
orderLines: [
{
name: 'Running shoe', // Item name
quantity: 1, // Quantity of the item
unitPrice: 24, // Price per unit
taxRate: 20, // Tax rate applied
totalAmount: 24, // Total amount for this item
totalTaxAmount: 4, // Total tax amount for this item
imageUrl: 'https://www.example.com/logo.png', // URL of the item's image
productUrl: 'https://www.example.com/AD6654412.html' // URL to the product page
}
],
deliveryType: 'service', // Type of delivery (e.g., service, physical)
invoiceId: 'YOUR_INVOICE_ID', // Unique identifier for the transaction invoice
amount: 24 // Total transaction amount
};
Step 12: Initialize the Button
To initialize the Apple Pay Express Checkout button and configure it for processing transactions, use the following method:
window.DNAPayments.ApplePayComponent.create(
document.getElementById('apple-pay-btn-container'), // The container element where the button will be rendered
paymentData, // Your configured payment data
events, // The events object containing all your event handlers
'YOUR_ACCESS_TOKEN', // Your access token
payload // The payload configuration
);
The access token returned from the API is an object that includes several fields such as access_token
, expires_in
, token_type
, and others. Only the access_token
field should be passed during button initialization. For more details on how to obtain the access token, follow the instructions outlined here.
When obtaining the access token, make sure to pass the following scopes to ensure proper initialization of the button: payment integration_seamless
.