• Documentation
  • API Reference
  • Documentation
  • API Reference
Expand All Collapse All
  • Payment Overview
    • Introduction
  • Accept Payment
    • Checkout Page
      • Quick Start for Checkout
      • Input Parameters
      • Output Parameters
    • Web SDK
      • Quick Start for Web SDK
      • Nuvei Fields
      • Nuvei Fields Stylizing
      • APMs for Web SDK
      • Web SDK Additional Functions
      • Web SDK FAQs
    • Checkout SDK
      • Checkout SDK Payment Form - UI Styling
    • Server-to-Server
    • Plugins
    • Mobile SDKs
      • Android Mobile SDK
      • iOS Mobile SDK
    • Payment Scenarios
    • Flow Diagrams
  • Features
    • API Authentication and the Session Token
    • PCI and Tokenization
    • 3D-Secure
    • Card-on-File
    • Merchant-Initiated Transactions (MIT)
    • Alternative Payment Methods (APMs)
    • Refund
    • Void
    • Auth, PreAuth, Sale and Settle
    • Direct Merchant Notifications (DMNs)
    • Subscription (Rebilling)
    • Zero-Authorization
    • Partial Approval
    • Marketplaces
  • Guides
    • Plugins
      • Magento 1
      • Magento 2
      • WooCommerce
      • PrestaShop
      • Open Cart
      • Shopify (via AsiaBill)
      • Mirakl
    • Choosing an Integration Method
    • Testing Cards, APIs and APMs
      • Testing Cards
      • Testing APMs
      • Testing APIs with Postman
      • Web SDK Scenarios
    • Response Handling and Errors
      • Error Handling
      • Error Codes
    • Country and Currency Codes
    • Direct Merchant Notifications (DMNs)
    • 3D-Secure
      • 3D-Secure Explained
      • 3D-Secure How-To Guide
      • 3D-Secure MPI-Only for Web SDK
      • 3D-Secure MPI-Only for Server-to-Server
      • 3D-Secure Fingerprinting
      • 3D-Secure Authentication Challenge
      • External MPI (Third-Party 3D-Secure)
      • 3D-Secure Response Values
    • Alternative Payments Guide
      • APM Input Fields
      • APM subMethod Classes
      • APM Supported Countries and Currencies
    • Apple Pay
      • Register in the Apple System
        • Create an Apple ID
        • Enroll in the Apple Developer Program
          • Submit an Enrollment Request
          • Complete the Enrollment Process
          • Activate your Apple Developer Program Account
        • Register a Merchant ID in the Apple System
          • Create a Merchant ID
          • Create a Payment Processing Certificate
          • Create a Merchant Identity Certificate
          • Register and Verify your Domain
      • Apple Pay Integration
        • Nuvei Apple Pay Integration Solutions
          • Nuvei Checkout Page IFrame Solution – Main Solution for Cashier
          • Static Apple Pay Button Solution on Merchant Site
          • Dynamic Apple Pay Button Solution on Merchant Site
        • Apple Pay Integration Testing
    • Payment Facilitators (PayFac)
    • Cashier
      • Cashier Events Guide
    • Withdrawal Guide
    • Risk Guide
    • eKYC Guide
    • Server SDKs
      • Java SDK
      • .NET SDK
      • PHP SDK
      • Node.JS SDK
    • Fast Track Onboarding Developer Guide
    • Currency Conversion Services
      • Multiple Currency Pricing (MCP)
        • Accepting Payment for a Sale using MCP Values
      • Dynamic Currency Conversion (DCC)
        • DCC in Cashier or Checkout Page
        • DCC in REST API Workflows
        • DCC in Web SDK Workflows
  • Additional Links
    • FAQs
    • API Reference
    • Release Notes

Dynamic Apple Pay Button Solution on Merchant Site

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

  1. 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>
  2. 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.
  3. 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.
  4. 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.
  5. To process the transaction using the Nuvei REST API do the following:
    1. Call the payment REST API method using the relevant Apple Pay parameters.
    2. POST the data received on your server, by invoking the payment method, with the relevant externalTokenProvider 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 in sc_api_applepay.min.js]

      Note: The currency and amount MUST match the ones stored in the mobileToken.

      The result is returned to your server.

  6. 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 (parameter false).
    • This closes the overlay correctly, and the user is informed of the transaction result.

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();
});
Previous Step
Next Step
2021 Nuvei. All rights reserved.