This solution integrates an Apple Pay payment method Button into your own checkout page, on your own site. The transaction total amount can be changed inside the Apple Pay payload, based on user choices, collected in the Apple Pay overlay. (This is one of the main differences between the Dynamic and Static JavaScript button solutions.)
For example, you can calculate the shipping price based on the billing address, or the shipping option selected, or the country/area for delivery, or taxes.
Steps
- Include the Nuvei “CDN” library by adding this script tag to your page.
This is a light JavaScript wrapper over the Apple API provided by Nuvei, which is used to verify identity, with Nuvei servers.<script type="text/javascript" src=" https://cdn.safecharge.com/safecharge_resources/v1/sc_api_applepay.min.js"></script>
- Create a button handler:
- Initialize the button handler.
- When the button is clicked, the overlay appears.
It displays data according to your business requirements, and allows the user to enter data.
For example, it displays:currency
,amount
,line items
,billing address
,shipping address
, etc. - The button handler also calls a function defined in
sc_api_applepay.min.js
, which handles the session and fetches the decrypted data from the device.
- The following data is returned by the method called by the button handler, defined in
sc_api_applepay.min.js
.
Create a result handler by defining a callback function to receive this data:- The authorized payment token (
mobileToken
) - Optional
address fields
- A completion function.
- The authorized payment token (
- Pass information from the frontend to the backend:
- Send the data gathered by the button handler to your server.
- It is preferable that all these operations use async hxr calls to the backend, while the Apple Pay overlay is open.
- To process the transaction using the Nuvei REST API do the following:
- Call the
payment
REST API method using the relevant Apple Pay parameters. - POST the data received on your server, by invoking the
payment
method, with the relevantexternalTokenProvider
request parameters values.
These are the additional mandatory parameters that you need to pass:externalTokenProvider=ApplePay
-
mobileToken=
[the encrypted data generated by Apple from the device, by a function defined insc_api_applepay.min.js
]
Note: Thecurrency
andamount
MUST match the ones stored in themobileToken
.The result is returned to your server.
- Call the
- Pass information from the backend to the frontend as follows:
- The button handler calls the completion function received earlier, to indicate the transaction succeeded (parameter
true
), or failed (parameterfalse
). - This closes the overlay correctly, and the user is informed of the transaction result.
- The button handler calls the completion function received earlier, to indicate the transaction succeeded (parameter
Notes
- A
User Payment Option ID
is not created for an Apple Pay payment. - A generated
mobileToken
can only be used once.
Example Code
/* define a button handler */ document.getElementById('apple-pay-button').addEventListener('click', function () { /* create initial apple pay overlay parameters */ let paymentRequest = { merchantSiteId: 183051, // ID received by Nuvei env:'int', // the environment you're running on, if omitted prod is default applicationData: "VGhlIExldmVsIEdyb3Vw", // merchantCapabilities : ['supports3DS','supportsCredit'] // optional overwrite of the default ['supports3DS'] // supportedNetworks: ['discover', 'visa', 'masterCard'] /* optional could be overwritten, default value is ['amex', 'chinaUnionPay', 'privateLabel', 'discover', 'visa', 'masterCard', 'jcb'], you can request only debit cards or only credit cards otherwise all are allowed */ requiredBillingContactFields: ['postalAddress', 'name', 'phone', 'email'], requiredShippingContactFields: ['postalAddress', 'name', 'phone', 'email'], shippingType: "shipping", // possible values: "delivery", "storePickup", "servicePickup" countryCode: 'GB', currencyCode: 'GBP', shippingMethods: [{ label: 'Standard Delivery', detail: 'Arrives 2-3 business days', amount: '5.83', identifier: 'std' }, { label: 'Ground Shipping', detail: 'Arrives 5-7 business days', amount: '55.83', identifier: 'ground' }, { label: 'Express Shipping', detail: 'Arrives 2-3 business days', amount: '155.83', identifier: 'express' }], lineItems: [{ type: 'final', label: 'Merchandise', amount: '4.95' }, { type: 'final', label: 'Standard Delivery', amount: '5.83' }, { type: 'final', label: 'Tax', amount: '60.16' }], total: { label: 'Your Company', amount: '19.99' } }; /* custom function which sends data to server */ let postTransactionData = function (url, trxData, callback) { let xhr = new XMLHttpRequest(); xhr.open('POST', url, true); xhr.setRequestHeader('Content-type', 'application/json; charset=UTF-8'); xhr.onload = function () { if (xhr.readyState === 4) { let data = {}; try { data = JSON.parse(this.responseText); } catch (e) { } callback (data); } }; let reject = function () { callback({}); }; xhr.onerror = reject; xhr.timeout = 30000; xhr.ontimeout = reject; xhr.send(JSON.stringify(trxData)); }; /* initialize session by calling sfc.applePay.buildSession, a function which defined in the external js file provided by Nuvei */ let session = sfc.applePay.buildSession(paymentRequest, (result, completion) => { /* postTransactionData is a function which calls server with provided data using Nuvei API and callback receives status from server */ postTransactionData(uploadUrl, result, function (srvResult) { // depending on status returned, completion method should be called with true or false if (srvResult.transactionStatus && srvResult.transactionStatus === 'APPROVED') { completion(true); } else { completion(false); } }) //session.abort(); }); /* you can define optional handlers of various events in session, for example: onshippingmethodselected, onshippingcontactselected, onpaymentmethodselected, oncancel */ session.onshippingmethodselected = (event) => { console.log('merchant - onshippingmethodselected:', event); setTimeout(() => { session.completeShippingMethodSelection({ newTotal: { label: 'new amount', amount: '115.94' } }) }, 1000); }; session.oncancel = (evt) => { console.log('cancelled', evt) }; /* overlay is triggered*/ session.begin(); });