Apple Pay for JavaScript Library

  Last updated: 

 

applepayicon-nobackground.png

What is Apple Pay?

Apple Pay is a wallet-based mobile payment service by Apple Inc. that lets users process payments using an iPhone, iPad or Mac. Customers benefit from a familiar and streamlined checkout experience, where their billing information can be pre-filled, ready for purchase. Customers are authenticated quickly by placing their finger on the built-in reader or through facial-recognition. Apple Pay uses tokens to ensure no sensitive payment information is stored with Apple, on the customer’s device or on your own servers.

This article explains how to integrate Apple Pay into your payment solution using our JavaScript Library.

  Only eligible customers can complete transactions using Apple Pay. For instance, customers must use a supported Apple device and be located within a country where Apple Pay operates. Please refer to   Apple’s documentation (link to external site) for the full list of requirements.

 


 

In May 2024, we simplified the process of integrating with Apple Pay


If you integrated Apple Pay with Trust Payments before this change:

 


 

Requirements

Ensure you have met the following requirements before integrating Apple Pay into your checkout solution:

Your acquiring bank must support
Apple Pay with Trust Payments.

  Contact Support Team if unsure

abank-nobackground.png

Your server must meet the following requirements:

In order to test your solution, you need to have access to a device that supports Apple’s sandbox testing for Apple Pay.

  Supported devices

You will need to have a sandbox tester account in order to add test cards to your wallet, in order to process Apple Pay test transactions.

  Learn about sandboxes

 

Setting up and verifying your domains

cluttereddesk-nobackground.png

  1. Begin by downloading the domain-verification file below and placing it on your domains where Apple Pay is to be displayed:

      Click here to download

    You must prepare each domain by hosting the received domain-verification file in this location, as this will be publicly queried to complete the domain registration process:

    https://[DOMAIN_NAME]/.well-known/apple-developer-merchantid-domain-association

    Ensure the file and the hidden .well-known directory are given read and execute permissions. (For Unix, this is typically done by using the command chmod 755 <filename or folder>).

      As part of the Apple Pay validation process, Apple requires that the validation file returns an HTTP 200 OK response. Any other HTTP response code, such as a 301 Moved Permanently, will be treated as a failure. To ensure Apple Pay works properly, the validation file must be configured to always return an HTTP 200 OK response.

  2. Have your authorised contact reach out to our Support Team and request to have Apple Pay enabled on your site reference(s). In your email, we require you to attach a CSV file that contains a list of all of the site references you intend to register and their associated domain(s).

    The format of the CSV file must be as follows:

    Site reference, Domain name

    For example:

    site10001, example.com
    site10002, trustpayments.com
    test_site10003, trustpayments.com

    Please include all relevant test and live site references and domains in the file.


      Format domains like this: example.com
      Do not send us this! www.example.com

    You can register up to 99 domains per site reference.

  3. Our Support Team will update you once the registration process for the specified domains is complete and that you can begin processing Apple Pay transactions.

      If you have previously integrated Apple Pay using our JavaScript Library but have since adopted the new registration process described above, you must ensure that the property merchantId in the configuration passed to the st.js ApplePay method has been updated to specify your site reference instead of the Apple Pay Merchant Id. This is because the domains are now linked to your site reference rather than your Apple Pay Merchant Id.

 

Configure Apple Pay solution

 

 

Once you have set up and verified your domains for Apple Pay, you will need to integrate using one of the following flows described below:

Flow 1 - JavaScript determines when the AUTH is submitted

    1. When the customer presses the Apple Pay button, the customer will be presented with the Apple Pay payment sheet.
    2. The customer approves the payment using Touch ID, Face ID or their passcode.
    3. When the customer agrees to the payment, an AUTH request is submitted to Trust Payments.
    4. Trust Payments contacts the acquiring bank to request authorisation for the transaction.
Instructions for Flow 1

Configure your JWT

JSON Web Tokens (JWT) are an open, industry standard RFC 7519 method for securely transmitting data between two parties. It protects against the modification of critical transaction data (e.g. the amount to be debited) by unauthorised parties during the payment session.

For this reason, this field is required in order to process payments with Trust Payments.

Click here to learn how to generate the JWT

  Depending on your preferred configuration, you may need to include an extra field in the payload when generating the JWT for your checkout form.

To allow the customer to choose a billing or delivery address stored on their Apple account from the payment sheet (instead of an address entered on your checkout), you must include the optional fields billingcontactdetailsoverride and customercontactdetailsoverride respectively, with the value “1”.

Otherwise, the JWT does not need to be modified to process Apple Pay transactions.


 

Apple Pay library

To allow our ST.js library to embed the Apple Pay button on the page which will subsequently launch the wallet sheet, you will need to allocate an appropriate content wrapper and make the appropriate ST.js library calls.

First, create a container where you want the Apple Pay button to be added in, and give it an appropriate ID:

<div id="st-apple-pay"></div>

Once configured, your Apple Pay button will appear as a child of this div element. Next, turn-on the Apple Pay feature within the JS library.

If we consider a scenario where you want to use Apple Pay’s wallet-sheet to charge your customer $10, using a linked credit or debit card. You might achieve that with the following code, where st refers to your instance of SecureTrading:

st.ApplePay({
buttonStyle: 'white-outline',
buttonText: 'plain',
merchantId: 'test_site12345',
paymentRequest: {
countryCode: 'US',
currencyCode: 'USD',
merchantCapabilities: ['supports3DS', 'supportsCredit', 'supportsDebit'],
supportedNetworks: ["visa","masterCard","amex"],
requiredBillingContactFields: ["postalAddress"],
requiredShippingContactFields: ["postalAddress","name", "phone", "email"],
total: {
label: 'Trust Payments Merchant',
amount: '10.00'
}
},
buttonPlacement: 'st-apple-pay'
});

The end result will be a HTML page that resembles the following example:

<html>
<head>
</head>
<body>
<div id="st-notification-frame"></div>
<form id="st-form" action="https://www.example.com"/>
<div id="st-apple-pay"></div>
<script src="https://cdn.eu.trustpayments.com/js/latest/st.js"></script>
<script>
(function() {
var st = SecureTrading({
jwt: 'INSERT YOUR JWT HERE',
});
st.ApplePay({
buttonStyle: 'white-outline',
buttonText: 'plain',
merchantId: 'test_site12345',
paymentRequest: {
countryCode: 'US',
currencyCode: 'USD',
merchantCapabilities: ['supports3DS', 'supportsCredit', 'supportsDebit'],
supportedNetworks: ["visa","masterCard","amex"],
requiredBillingContactFields: ["postalAddress"],
requiredShippingContactFields: ["postalAddress","name", "phone", "email"],
total: {
label: 'Trust Payments Merchant',
amount: '10.00'
}
},
buttonPlacement: 'st-apple-pay'
});
})();
</script>
</body>
</html>

Further into this document, you’ll be able to explore the possible values for each of the fields listed above, as well as other optional fields not listed above.


 

Field specification

 

Button fields

  Field Format Description
X1-EN.png buttonStyle Alphanumeric Used to change the appearance of the Apple Pay button.
  Click here for further information (link to external site).
X1-EN.png buttonText Alphanumeric Used to change the text that appears on the Apple Pay button.
  Click here for further information (link to external site).
X2-EN.png buttonPlacement Alphanumeric

By default, the library searches for a div id called "st-apple-pay" in order to determine where the Apple Pay button should be placed on the form.

If you are not using the default div id, you will need to specify your custom id as the value of the buttonPlacement property. e.g.

buttonPlacement: 'apple-button'

Apple has published guidelines on how to best position the Apple Pay button on your checkout.
Click here to learn more (link to external site).


 

Merchant fields

  Field Format Description
X1-EN.png merchantId Alphanumeric
& underscore (50)

The value assigned to merchantId must be the site reference that is associated with the domain that is calling the ApplePay method, as specified in the CSV sent to the Support Team during the domain verification process.

  The merchantId submitted here must be the same as the sitereference submitted in the JWT.

X1-EN.png paymentRequest Object This object contains information about the payment request. The specification mirrors those of the official Apple Pay Developer Documentation
X1-EN.png   countryCode Alpha (2) The merchant’s country code in ISO2a format.
X1-EN.png   merchantCapabilities List The payment capabilities supported by the merchant. The field must contain “supports3DS” (to enable Touch ID / Face ID verification), and at least one of the following additional values:
  • “supportsCredit” – To enable credit card payments.
  • “supportsDebit” – To enable debit card payments.
For a full specification, please refer to   Apple’s own documentation (link to external site).
X1-EN.png   supportedNetworks List

The payment networks supported by the merchant.

You must set this property to one or more of the payment network values specified in the official Apple Pay API specification. 

We support all payment networks up until version v14 of Apple Pay and will automatically omit any unsupported networks.

If a customer's browser/device has v14 support and a full payment network list is provided, the full-list will be passed to Apple. If the customer only has a v6 compatible browser/device, then we’ll reduce the full list given down to what was supported up until v6.

Please note: You must ensure that any supported payment network included in the list is also configured as a supported network on your site reference. Contact our Support Team for further information.

X3-EN.png   supportedCountries Array of strings

A list of two-character country codes you provide (in ISO2a format). Apple Pay transactions are limited to cards issued in countries listed in this property.

The supportedCountries list does not affect the currency used for the transaction, and it applies to all payment cards in the wallet.


 

Transaction fields

  Field Format Description
X3-EN.png callbacks Object containing all callback definitions 

Supported callbacks include:

  • onShippingMethodSelected
  • onShippingContactSelected
X3-EN.png     onShippingMethodSelected function

The onShippingMethodSelected callback function is triggered whenever a customer selects a different shipping method on the payment sheet. This function allows you to update the transaction details displayed to the customer.

Signature:

function (data, actions) {
  console.log(data.shippingOption)
  actions.resolve({ newTotal: { ... } });
}

data: Contains information about the selected shipping method.

actions: Includes the resolve function, which you use to update the payment sheet with the new transaction details.

For a full breakdown of the data object and the structure for the updated transaction details, please visit the Apple Pay Developer Documentation.

When resolving the callback, you can optionally provide a JSON Web Token (JWT) that will override the original JWT used during the initialisation. This ensures the final amount authorised matches the total shown on the payment sheet.

 

X3-EN.png     onShippingContactSelected function

 The onShippingContactSelected callback function is invoked whenever a customer selects a different shipping address. This allows you to update both the available shipping methods and the transaction details displayed on the payment sheet.

Signature:

function (data, actions) {
  console.log(data.shippingContact)
  actions.resolve({ newTotal: { ... } });
}

data: Contains the shipping contact information, which Apple Pay redacts to protect privacy. This data is sufficient for calculating taxes or shipping costs. actions: Includes the resolve function to update the payment sheet with new transaction details and shipping methods.

For detailed information about the data object and how to structure the updated details, refer to the Apple Pay Developer Documentation.

Similar to onShippingMethodSelected, you can provide a JWT to override the original one, ensuring the total amount aligns with what is displayed on the payment sheet.

 

X1-EN.png paymentRequest Object This object contains information about the payment, which will be sent off to Apple in the initial request (our Javascript sends this).
X2-EN.png   requiredBillingContactFields List On the payment sheet, this field is used to prompt the customer to choose their preferred billing address details from their Apple Pay account, prior to purchase. The payment sheet will NOT display any billing address details posted from your checkout. You can submit the following field values:
  • “postalAddress”

This is required when the customer is to complete the purchase using billing address fields saved on their Apple Pay account.

X2-EN.png   requiredShippingContactFields List On the payment sheet, this field is used to prompt the customer to choose their preferred delivery address details from their Apple Pay account, prior to purchase. The payment sheet will NOT display any delivery address details posted from your checkout. You can submit the following field values:
  • “postalAddress”
  • “name”
  • “phone”
  • “email”

This is required when the customer is to complete the purchase using delivery address fields saved on their Apple Pay account.

X3-EN.png   shippingMethods  List of dictionaries

The shippingMethods property allows you to define a list of shipping options available for your customers to select from within the payment sheet.

You can offer an unlimited number of shipping methods. For more detailed guidance on structuring your shippingMethods, please refer to the 

Apple Pay Developer Documentation

X3-EN.png   shippingType Alpha

The shippingType is an optional property that specifies how the customer's order will be fulfilled, such as whether it will be collected in-store or delivered to a specified address. To explore all possible values for this property, visit the Apple Pay Developer Documentation on shippingType.

X1-EN.png   currencyCode Alpha (3) The transaction currency code in ISO3a format.
X1-EN.png   total N/A A line item representing the total for the payment.
X1-EN.png     amount Numeric including decimal place (14) The amount of the transaction in main unitsusing a decimal point to denote decimal values, so £10 is returned as 10.00. This must be the same amount as submitted within the payload of the JWT. It’s critical that the amount submitted in the JWT is correct, as this is the value that determines the amount the customer is to debited.
X1-EN.png     label Alphanumeric including symbols This is a comment to be displayed on the Apple Pay payment sheet, next to the total amount, prior to the customer agreeing to the payment.

 


 

Enhancing your integration

The following section will introduce additional features offered by the library that go beyond a basic payment flow and will require an understanding of the callbacks object set in the ApplePay configuration.

Callbacks

If needed, the ApplePay configuration accepts a callbacks object which provides an option to configure any of our available callback options:

  • onShippingMethodSelected
  • onShippingContactSelected

Both callback functions have the same signature:

function (data, actions) {
  // Your implementation here
}

data

The values returned in each data object will match the Apple Pay JS API for the respective callbacks, i.e. shippingMethod and shippingContact.

For a comprehensive view of the data returned for both onShippingMethodSelected & onShippingContactSelected, you can refer to the official Apple Pay developer documentation :

onShippingMethodSelected

onShippingContactSelected

actions

The actions argument is an object that provides access to a single function, named resolve. It accepts a single object argument, whose expected values will match the Apple Pay JS API contracts laid out by

completeShippingContactSelection and completeShippingMethodSelection.

The only deviation from this from specification is that we also allow you to provide an additional, but optional key named jwt, which will take care of aligning your JWT payload with the prices and addresses shown on the wallet-sheet.

Offering your customers multiple shipping options

When using Apple Pay, you can provide customers with multiple shipping options within the payment sheet. This enables you to offer choices like standard and express shipping, enhancing the customer experience by providing flexibility and transparency regarding shipping costs and delivery times.

You can implement multiple shipping methods by following these steps:

Define your shipping methods:

Begin by specifying the available shipping methods in the shippingMethods property of the paymentRequest. Each shipping method should include a label, a description, the cost, and a unique identifier.

st.ApplePay({
  paymentRequest: {
    shippingMethods: [
      {
        "label": "Free Shipping",
        "detail": "Arrives in 5 to 7 days",
        "amount": "0.00",
        "identifier": "FreeShip"
      },
      {
        "label": "Express Shipping",
        "detail": "Arrives in 1 to 2 days",
        "amount": "10.00",
        "identifier": "ExpressShip"
      }
    ],
    ...
  }
});

The example above shows how to configure two shipping options: Free Shipping and Express Shipping. It’s possible to add as many shipping methods as necessary.

Please note: The ordering of shipping methods displayed on the wallet-sheet is determined based on the first object in the array, unless another object in the array is explicitly marked with the selected: true attribute.

Handling Shipping Method Selection:

Use the onShippingMethodChanged callback to react when a customer changes the shipping method from the available options. This callback allows you to adjust the transaction details, such as the total cost, based on the selected shipping method.

"callbacks": {
    "onShippingMethodSelected": (data, actions) = {
      const payloadJwt = loadYourPayload();

      actions.resolve({
        newTotal: {
          label: "Your Merchant Name",
          amount: calculateTotal(...), // Adjust the total amount
        },
        newLineItems: [
          { label: "Subtotal", amount: ... },
          { label: data.label, amount: ... } // Include selected shipping method
        ],
        jwt: payloadJwt,
      });
    },
  };
}

In this example, when the customer changes the shipping method, the total transaction amount is recalculated, and the payment sheet is updated with the new details.

Customise Shipping Type (Optional):

Optionally, specify the shippingType property to define how the order will be fulfilled, such as delivery to a customer's address or in-store collection. This provides additional clarity to the customer.

st.ApplePay({
  paymentRequest: {
    shippingType: "shipping", // Options include 'shipping', 'delivery', 'storePickUp', etc.
    ...
  }
});

Use this option to align the payment sheet with the merchant's fulfilment process.


Managing a Change in Shipping Contact

Apple Pay also enables you to manage scenarios where a customer updates their shipping contact information, such as changing their delivery address. This flexibility allows you to adjust available shipping methods and recalculate costs based on the new shipping contact.

You can manage a change in shipping contact information by following these steps:

Reacting to Shipping Contact Changes:

The onShippingContactSelected callback is triggered when the wallet sheet is opened and when a customer changes the shipping contact information. This is particularly useful for recalculating shipping costs, taxes, or even changing available shipping methods based on the new address.


"callbacks": {
    "onShippingContactSelected": (data, actions) = {
      const payloadJwt = loadYourPayload();

      actions.resolve({
        newTotal: {
          label: "Your Merchant Name",
          amount: calculateTotal(...), // Adjust the total amount
        },
        newLineItems: [
          { label: "Subtotal", amount: payload.baseamount },
          { label: "Shipping", amount: calculateShipping(data) } // Recalculate shipping costs
        ],
        newShippingMethods: determineAvailableMethods(data), // Optionally, adjust available shipping methods
        jwt: payloadJwt,
      });
    },
  };
}

In this example, the SDK handles the change in shipping contact by recalculating relevant costs and updating the payment sheet accordingly.

Update Available Shipping Methods:

If necessary, adjust the available shipping methods based on the new shipping contact. For example, certain shipping options may not be available for international addresses or specific regions.

function determineAvailableMethods(data) {
  if (data.countryCode === "US") {
    return [
      {
        "label": "Standard Shipping",
        "detail": "Arrives in 5 to 7 days",
        "amount": "5.00",
        "identifier": "StandardShip"
      },
      {
        "label": "Overnight Shipping",
        "detail": "Arrives next day",
        "amount": "25.00",
        "identifier": "OvernightShip"
      }
    ];
  } else {
    return [
      {
        "label": "International Shipping",
        "detail": "Arrives in 10 to 15 days",
        "amount": "20.00",
        "identifier": "IntlShip"
      }
    ];
  }
}

In this pseudocode, the available shipping methods are adjusted based on the customer's country, offering the appropriate options.

Flow 2 - Merchant determines when the AUTH is submitted

For merchants who would rather receive the Apple wallettoken data and send an API request to process the AUTH themselves, the property merchantUrl should be set in the st.js st.ApplePay method config.

  1. When the customer presses the Apple Pay button, the customer will be presented with the Apple Pay payment sheet.
  2. The customer approves the payment using Touch ID, Face ID or their passcode.
  3. merchantUrl is sent a request from the JavaScript containing the wallet details.
  4. An AUTH request is sent by the merchantUrl to Trust Payments using our Webservices API.
  5. Once the payment result is returned by Trust Payments to the merchantUrl, a response JWT should be sent back to the st.js library to update the Apple Payment sheet
Instructions for Flow 2

First, we add the merchantUrl property to the ApplePay method config:

st.ApplePay({
  buttonStyle: 'white-outline',
  buttonText: 'plain',
  merchantId: 'test_site12345',
  paymentRequest: {
    countryCode: 'US',
    currencyCode: 'USD',
    merchantCapabilities: ['supports3DS', 'supportsCredit', 'supportsDebit'],
    supportedNetworks: ["visa","masterCard"],
    requiredBillingContactFields: ["postalAddress"],
    requiredShippingContactFields: ["postalAddress","name", "phone", "email"],
    total: {
      label: 'Trust Payments Merchant',
      amount: '10.00'
    }
  },
  buttonPlacement: 'st-apple-pay'
  merchantUrl:'<payment URL endpoint>'
});

The following is an example request sent from the JavaScript to merchantUrl once the customer has authenticated the transaction using Touch ID, Face ID or passcode:

{​​​​​​​​​​​​​​
"request": [
{​​​​​​​​​​​​​​
"walletsource": "APPLEPAY",
"wallettoken": "<json encoded string>",
}​​​​​​​​​​​​​​
],
"jwt": "<jwt token>",
"acceptcustomeroutput": "2.00",
"version": "1.00",
"versioninfo": "STJS::N/A::3.2.0::N/A"
}​​​​​​​​​​​​​​

At this point, it is assumed that the merchantUrl will make an API request to Trust Payments to process the authorisation.

For an example of how to send the AUTH using our webservices API, please refer to the "AUTH request" section on this article.

The merchantUrl response to the st.js should be a JWT response. You will need to parse the AUTH response and include the returned fields in the payload of the response <JWT Token>, as shown below.

{
  jwt:<JWT Token>
}

The payload of the JWT token should be encoded with the following object:

{​​​​​​​​​​​​​​'version': '1.00',
'response': [{
'walletsource': 'APPLEPAY',
'errormessage': 'Ok',
'sitereference': '<test or live sitereference>',
'errorcode': '0',
'requesttypedescription': 'AUTH'
}​​​​​​​​​​​​​​]
}​​​​​​​​​​​​​​

 

Understanding the payment sheet

cardandapple-nobackground.png

Prior to completing the purchase, the payment sheet is displayed to the customer. This presents the customer with cards previously-saved on their account, options for delivery, contact information and the full purchase amount (including tax and fees). They can review the order and optionally make adjustments before proceeding.

Card

The customer will be able to select from the cards saved in their   Apple Wallet (link to external site).
The cards supported for payment are dependent on the merchantCapabilities field posted on the checkout.
e.g. If “supportsDebit” is not included in the field, the customer will not be able to complete their payment with a debit card.

Address

The billing and shipping address will only be displayed on the payment sheet if the fields requiredBillingContactFields and requiredShippingContactFields have been submitted with valid values. This allows the customer to select from billing and/or shipping addresses saved on their Apple account.

The address selected on the payment sheet will only be included in the AUTH request if the fields billingcontactdetailsoverride and customercontactdetailsoverride have been submitted, with the value “1”.

CJ16-EN.png

Label and amount

The mainamount value is displayed on the payment sheet, alongside the label, posted on the checkout. In the example here, the label was submitted with the value “Outstanding balance”.

CJ17-EN.png

Authentication

The method of authentication will differ based on the device being used to complete the payment. The customer may be prompted to place their finger on the Touch ID sensor, or look at the Face ID sensor.
  Click here for further information on Apple Pay authentication (link to external site).

 

Payment completion

 

Once the customer has been successfully authenticated on the payment sheet, the next step is to process the transaction:

  • If utilising Flow 1, the authorisation will be performed automatically by st.js.
  • If utilising Flow 2, your configuration will need to process the AUTH request manually using the Webservices API and update the payment sheet with the result.

The Apple Pay payment sheet will update to show either a success or failure message, depending on the outcome of the payment. Following a success case, the payment sheet will close to indicate the payment is complete.

CJ18-EN.png

 

Portal

As with regular card payments, records of all AUTH transactions processed using Apple Pay can be viewed in Portal. When viewing Apple Pay transactions in Portal, the “Wallet source” will be displayed as “APPLEPAY”. Click here to view our Portal documentation.

CF19-EN.png

 

Testing

 

Your test site reference will connect to the Apple Pay testing sandbox. Therefore, in order to process payments on your test site reference, you will need to add test card details to the Apple Wallet on your supported device(s).

You will be required to use the test card details provided by Apple. Please refer to the following URL:
  https://developer.apple.com/support/apple-pay-sandbox/ (link to external site)

The above assumes you are signed in to your device with an Apple sandbox account.

  Please be aware that the test card details we provide in our testing documentation cannot be used when processing Apple Pay test transactions.

  If you have enabled User-Defined Rules (UDR) on you site reference(s), you will need to ensure that you understand how they may affect your Apple Pay transactions.
If you require any assistance, please contact our Support Team.

 

Performing additional requests

 

When processing e-commerce payments using Apple Pay, you can configure your solution to include additional requests to perform extra tasks. These are as follows:

You will need to update the JWT payload to include the list requesttypedescriptions with the following supported request combinations:

  If your app is offering other card payment methods alongside Apple Pay, it is imperative that you include “THREEDQUERY” in the requesttypedescriptions list, because without it 3-D Secure authentication would not be performed for the aforementioned card payment methods. If the customer chooses to process the payment using Apple Pay, the gateway will purposely omit the THREEDQUERY automatically as it would not be needed in that case.

  • [“THREEDQUERY”, “ACCOUNTCHECK”]
  • [“THREEDQUERY”, “ACCOUNTCHECK”, “SUBSCRIPTION”]
  • [“THREEDQUERY”, “AUTH”]
  • [“THREEDQUERY”, “AUTH”, “SUBSCRIPTION”]
Was this article helpful?
0 out of 0 found this helpful