Apple Pay

Client-Side Implementationanchor

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

If you are using our Drop-in UI, follow the Drop-in guide for client-side integration instructions.

Get the SDKanchor

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:

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

Initializationanchor

Check browser and device capabilitiesanchor

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 supportsVersion with the ApplePaySession that will be used. Finally, call canMakePayments to ensure that the device is capable of making Apple Pay payments:

  1. JavaScript
if (window.ApplePaySession && ApplePaySession.supportsVersion(3) && ApplePaySession.canMakePayments()) {
  // This device supports version 3 of Apple Pay.
}

Set up your Apple Pay buttonanchor

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.

Use ApplePaySession.canMakePayments to ensure that the device is capable of making Apple Pay payments.

important

When testing, you will need to be logged into an iCloud account that corresponds to your environment. Testing in sandbox requires you to be logged into an iTunes Connect sandbox tester account, which you can create with an Apple Developer account. Similarly, you will need to be logged into a production iCloud account when testing in production.

  1. Callback
  2. Promise
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;
    }

    // Set up your Apple Pay button here
  });
});

You can find more details on how to set up the Apple Pay button in Apple's developer documentation.

Integrate the JS Apple Pay componentanchor

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 ApplePaySessionanchor

The ApplePaySession object manages the Apple Pay payment process on the web. A new ApplePaySession should be created each time a payment is explicitly requested by a customer, such as inside an onclick event. Otherwise, it throws a JavaScript exception.

For each ApplePaySession, create a paymentRequest object, which includes information about payment processing capabilities, the payment amount, and shipping information.

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 these properties yourself.

Also, you will need to pass in an object that includes the rest of the paymentRequest properties that you wish to use. See the ApplePayPaymentRequest API reference for the properties available.

For example:

  1. JavaScript
var paymentRequest = applePayInstance.createPaymentRequest({
  total: {
    label: 'My Store',
    amount: '19.99'
  },

  // We recommend collecting billing address information, at minimum
  // billing postal code, and passing that billing postal code with
  // all Apple Pay transactions as a best practice.
  requiredBillingContactFields: ["postalAddress"]
});
console.log(paymentRequest.countryCode);
console.log(paymentRequest.currencyCode);
console.log(paymentRequest.merchantCapabilities);
console.log(paymentRequest.supportedNetworks);

var session = new ApplePaySession(3, paymentRequest);

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

As stated earlier, a new ApplePaySession must be inside of a gesture handler, such as an onclick event or an addEventListener "click" handler.

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 callbackanchor

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

  1. Callback
  2. Promise
session.onvalidatemerchant = function (event) {
  applePayInstance.performValidation({
    validationURL: event.validationURL,
    displayName: 'My Store'
  }, function (err, merchantSession) {
    if (err) {
      // You should show an error to the user, e.g. 'Apple Pay failed to load.'
      return;
    }
    session.completeMerchantValidation(merchantSession);
  });
};

onpaymentauthorized callbackanchor

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:

  1. Callback
  2. Promise
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;
    }

    // Send payload.nonce to your server.
    console.log('nonce:', payload.nonce);

    // If requested, address information is accessible in event.payment
    // and may also be sent to your server.
    console.log('billingPostalCode:', event.payment.billingContact.postalCode);

    // After you have transacted with the payload.nonce,
    // call 'completePayment' to dismiss the Apple Pay sheet.
    session.completePayment(ApplePaySession.STATUS_SUCCESS);
  });
};

Show the payment sheetanchor

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.

  1. 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 Page: Server-side