Our JavaScript v3 SDK is made to work in tandem with Safari's Apple Pay API Reference.

Get the SDK

See the client SDK setup guide for JavaScript v3. Apple Pay on the web requires version 3.4.0 or higher.

If you are using script tags to load files, be sure to at least include:

HTML
<script src="https://js.braintreegateway.com/web/3.9.0/js/client.min.js"></script>
<script src="https://js.braintreegateway.com/web/3.9.0/js/apple-pay.min.js"></script>

Initialization

Check browser and device capabilities

Apple Pay on the web is supported on the following platforms:

  • iOS 10. Apple Pay JavaScript is supported on all iOS devices with a Secure Element. It is supported both in Safari and in SFSafariViewController objects.
  • macOS 10.12. Apple Pay JavaScript is supported in Safari. The user must have an iPhone or Apple Watch that can authorize the payment.

Check that the window.ApplePaySession class exists to ensure Apple Pay is supported and available in the browser. Then, call canMakePayments to ensure that the device is capable of making Apple Pay payments:

JavaScript
if (window.ApplePaySession && ApplePaySession.canMakePayments()) {
  // This device supports Apple Pay.
}

Set up your Apple Pay button

Before showing the Apple Pay button, make sure that an Apple Pay instance can be successfully created and the device is capable of making an Apple Pay payment.

If you're checking Apple Pay's availability before defaulting to Apple Pay during your checkout flow or adding an Apple Pay button to your product detail page, use ApplePaySession.canMakePaymentsWithActiveCard, an asynchronous call that requires your Braintree Apple Pay merchant ID.

note

Your Apple Pay merchant ID is a special merchant ID that represents the merchant association with Braintree. Always use applePayInstance.merchantIdentifier to access this merchant ID.

This ensures that the device is capable of making Apple Pay payments and that it has at least one provisioned card. If checking for Apple Pay availability at any other point, use canMakePayments instead.

important

When testing, you will need to be logged into an iCloud account that corresponds to your environment. Your test device will need to be logged into an iTunes Connect sandbox tester account when testing in sandbox. Similarly, you will need to be logged into a production iCloud account when testing in production.

JavaScript
if (!window.ApplePaySession) {
  console.error('This device does not support Apple Pay');
}

if (!ApplePaySession.canMakePayments()) {
  console.error('This device is not capable of making Apple Pay payments');
}

braintree.client.create({
  authorization: 'CLIENT_AUTHORIZATION'
}, function (clientErr, clientInstance) {
  if (clientErr) {
    console.error('Error creating client:', clientErr);
    return;
  }

  braintree.applePay.create({
    client: clientInstance
  }, function (applePayErr, applePayInstance) {
    if (applePayErr) {
      console.error('Error creating applePayInstance:', applePayErr);
      return;
    }

    // Alternatively, check if the device has an Apple Pay card available.
    // You can do this if your checkout flow defaults to Apple Pay
    // or if you are displaying Apple Pay buttons on a product detail page.

    // Use your Apple Pay merchant identifier
    // to check if payments can be made.

    var promise = ApplePaySession.canMakePaymentsWithActiveCard(applePayInstance.merchantIdentifier);
    promise.then(function (canMakePaymentsWithActiveCard) {
      if (canMakePaymentsWithActiveCard) {
        // Set up Apple Pay buttons
      }
    });
  });
});

Follow Apple's guidelines for designing your Apple Pay button; refer to WWDC 2016 - Session 703.

Integrate the JS Apple Pay component

Our Apple Pay component interacts with your JavaScript code in three areas:

  1. Creating an ApplePaySession
  2. Handling the onvalidatemerchant callback
  3. Handling the onpaymentauthorized callback

Create an ApplePaySession

A paymentRequest object is required to create an ApplePaySession. The properties of a paymentRequest can be found on Apple's API reference.

The Braintree JS SDK v3 provides createPaymentRequest, a method for providing four of the properties required for the paymentRequest.

These values are loaded from the Braintree gateway:

  • countryCode
  • currencyCode
  • merchantCapabilities
  • supportedNetworks

We recommend using this method rather than supplying the properties yourself:

JavaScript
var paymentRequest = applePayInstance.createPaymentRequest({
  total: {
    label: 'My Store',
    amount: '19.99'
  }
});
console.log(paymentRequest.countryCode);
console.log(paymentRequest.currencyCode);
console.log(paymentRequest.merchantCapabilities);
console.log(paymentRequest.supportedNetworks);

var session = new ApplePaySession(1, paymentRequest);

If you wish, you can still override any of the 4 provided properties by passing them in the argument to createPaymentRequest.

Creating an ApplePaySession object throws a JavaScript exception if any of the following occur:

  • Any Apple Pay JavaScript API is called from an insecure page.
  • You pass an invalid payment request. Payment requests are invalid if they contain missing, unknown, or invalid properties, or if they have a negative total.

onvalidatemerchant callback

In the onvalidatemerchant callback, use applePayInstance.performValidation to create a validated Apple Pay session object:

JavaScript
session.onvalidatemerchant = function (event) {
  applePayInstance.performValidation({
    validationURL: event.validationURL,
    displayName: 'My Store'
  }, function (validationErr, merchantSession) {
    if (validationErr) {
      // You should show an error to the user, e.g. 'Apple Pay failed to load.'
      console.error('Error validating merchant:', validationErr);
      session.abort();
      return;
    }
    session.completeMerchantValidation(merchantSession);
  });
};

onpaymentauthorized callback

Safari will call the onpaymentauthorized callback with an event object. This object contains a token which must be sent to Braintree to get a payment method nonce. It also contains objects representing shipping address (as shippingContact) and billing address (as billingContact), which can be used for your own needs.

Use applePayInstance.tokenize to send this Apple Pay token to Braintree and receive a payment method nonce in return:

JavaScript
session.onpaymentauthorized = function (event) {
  console.log('Your shipping address is:', event.payment.shippingContact);

  applePayInstance.tokenize({
    token: event.payment.token
  }, function (tokenizeErr, payload) {
    if (tokenizeErr) {
      console.error('Error tokenizing Apple Pay:', tokenizeErr);
      session.completePayment(ApplePaySession.STATUS_FAILURE);
      return;
    }
    session.completePayment(ApplePaySession.STATUS_SUCCESS);

    // Send payload.nonce to your server.
  });
};

Show the payment sheet

After you have created the session and added the callbacks, call the session's begin method to show the payment sheet. You can only call the begin method when a payment is explicitly requested by the customer – for example, inside an onclick event. If an action is not explicitly requested by the customer, the begin method will throw a JavaScript exception.

JavaScript
session.begin();

Once payment is initiated in the browser, transactions are authorized by the customer on either an iPhone or Apple Watch.

See also

Next: Server-side →

Still Have Questions?

If you can’t find an answer, give us a call at 877.434.2894 or contact our Support team