Apple Pay Button Integration

A guide on integrating the Apple Pay button on a webpage.

This guide is not intended as a comprehensive tutorial for integrating with Apple Pay but it will discuss the steps to take to complete a basic implementation of an Apple Pay button on a web page.

More documentation can be found through Apple here:

To begin, the Apple Pay SDK must be loaded on your page. One way to accomplish this is by loading it through a script tag in your HTML using Apple's CDN.

<script src="https://applepay.cdn-apple.com/jsapi/v1/apple-pay-sdk.js"></script>

To render the button on your page the element can be added to your HTML document:

<apple-pay-button id="apple-pay-button" onclick="doApplePay();" buttonstyle="black" type="plain" locale="en"></apple-pay-button>

Because Apple Pay is only accepted on Safari or iOS devices the JavaScript file should check if the user's browser can make use of Apple Pay.

📘

Note

Apple recommends hiding the Apple Pay button until after making sure the service can be used. For more information, you can review Apple's documentation on Acceptable Use Guidelines for Apple Pay on the Web.

The following code block initially will create variables for storing the Apple Pay version supported by the client browser and another for saving the URL used to load the page.

Then it will check if the window.ApplePaySession and ApplePaySession.canMakePayments() methods from the Apple Pay SDK return true.

If the required conditions are met then the ApplePaySession.supportsVersion() method is called in a for loop.

This loop iterates through the most recent Apple Pay number versions to find the most recent that the browser in use supports and saves that value to the applePayVersion variable. This point in the flow would be a good time to actually display the Apple Pay button on the page.

If either of the required conditions does not evaluate as true then a message will print to the console.

// Create a variable to store the Apple Pay Version supported by the browser.
var applePayVersion;
// Create a string to store the referrer URL (will be used in Apple Pay functions)
var referringUrl = location.host

if (window.ApplePaySession && ApplePaySession.canMakePayments()) {
    document.getElementById('Apple-pay-supported').style.display = "none";
    document.getElementById('apple-pay-button').style.display = "inline-block";
    for (var i=15; i>0; i--){
        if (ApplePaySession.supportsVersion(i)){
            applePayVersion = i;
            break;
        }
    }
}
else {
    document.getElementById('Apple-pay-supported').innerHTML = "Apple Pay is not supported."
}

If the conditions are met then at that point the Apple Pay button can be rendered. The next step is to create a function to trigger when the Apple Pay button is clicked. In this example, the function is named doApplePay().

🚧

Note

The following code blocks are all part of the doApplePay() function. This section just steps through the different steps it takes to build the function.

function doApplePay(){
    // The data needed to set up the session
    // see https://developer.apple.com/documentation/apple_pay_on_the_web/applepaypaymentrequest
    const payData = {
        countryCode: 'US',
        currencyCode: 'USD',
        supportedNetworks: [
            "visa",
            "masterCard",
            "amex",
            "discover"
        ],
        merchantCapabilities:  [
            "supports3DS"
        ],
        requiredBillingContactFields: [
            "postalAddress",
            "name"
        ],
        ApplePayContactField: [
            "email",
            "name",
            "phone",
            "postalAddress",
        ],
        total: {label: 'my merchant name', amount: 10}
    }

With the payData variable defined the ApplePaySession() method can be used to create a new Apple Pay session. It requires the version number we save to the applePayVersion variable when the page was loaded, and the payData object defined in the last block.

// Create the session
session = new ApplePaySession(applePayVersion, payData);

Then a validation callback function needs to be attached to the Apple Pay session that was just created.

When the session is started at a later stage Apple Pay will attempt to validate the merchant and the Apple Pay SDK will call this function.

// Attach a validation callback
    session.onvalidatemerchant = event => {
        const myMerchantId = "180000000742";
        const myApplePayParams = {
            display_name: 'Test Display Name',
            referrer: referringUrl
        };
        
        console.log(JSON.stringify(myApplePayParams))

        // Call the PayConex API to fetch a payment session object
        fetch(`https://api-cert.payconex.net/api/v1/apple_pay/${myMerchantId}/get_apple_pay_session`, {
            method: 'POST',
            headers: new Headers({'content-type': 'application/json'}),
            body: JSON.stringify(myApplePayParams)
        })
            .then(res => res.json()) // Parse response as JSON.
            .then(merchantSession => {
                //Log the session data to the console.
                console.log(merchantSession)

                // Pass the session object to Apple
                session.completeMerchantValidation(merchantSession);
            })
            .catch(err => {
                console.error("Error fetching merchant session", err);
            });
    };

The final step before starting the session is to attach a callback function that will be called after the completeMerchantValidation() method is called by the Apple Pay SDK.

When the Apple Pay SDK makes it to this point in the process it will deliver the tokenized data for use in a payment. In this example, the token is just logged to the console for testing.

// Attach a payment authorized callback
    // This is the function that will be called after the user authenticates
    session.onpaymentauthorized = applePayment => {
        //For the example the token will be printed to the console in this case.
        console.log(JSON.stringify(applePayment.payment.token))

        /*
        // In this step you should send the token data to your own server.
        // which should submit a payment request to QSAPI to complete the payment with the token.
        fetch(`https://yourserver.com/your_path/`, {
            method: 'POST',
            body: JSON.stringify({'token': applePayment.payment.token})
        }).then(transactionResponse => {
            // Tell Apple about the result of the transaction
            if(transactionResponse.approved) {
                session.completePayment({status: ApplePaySession.STATUS_SUCCESS});
            } else {
                session.completePayment({status: ApplePaySession.STATUS_FAILURE});
            }
        })*/
    }

The last step in the function is to begin the session.

// Actually begin the session
session.begin();
}

What’s Next

Use the token result from the Apple Pay button to process a transaction.