Apple Pay on the Web Implementation

Learn how to implement Apple Pay on the Web.

Preczn's Apple Pay client is a client-side (browser) script which reduces the complexity of integrating to Apple Pay on the Web for transaction processing with Preczn.

You can add the Apple Pay button to your web interface and then initialize it's functionality using a secure Preczn-hosted JavaScript client. Once an Apple Pay payment method is obtained the Preczn client generates a secure single-use merchant-specific token, which you can then safely transmit from your client-side web application to your server-side for use processing a transaction.

πŸ“± Implementing Apple Pay

For a quick implementation crash course on the Preczn Apple Pay client, see the following recipe:

1. Add the Apple Pay button to your page

Include the Apple Pay JavaScript SDK and define the button element

πŸ“– Reference: Follow the Apple Developer Documentation guide for Displaying Apple Pay Buttons using JavaScript.

Add the <apple-pay-button> element on your page where you would like it displayed:

<apple-pay-button buttonstyle="black" type="buy" locale="en-US"></apple-pay-button>

ℹ️ Note that the Apple Pay SDK will automatically hide and disable the apple-pay-button in any browser that is not compatible, or where the ApplePaySession.canMakePayments() function returns false.

πŸ“˜

Be sure to create exactly one apple-pay-button element

The Preczn Apple Pay client will automatically discover the <apple-pay-button> element on your page (using getElementsByTagName('apple-pay-button')) and will render errors if zero or more than one <apple-pay-button> elements are discovered.

Customize the Apple Pay button

🎨 Customize the look and feel of the Apple Pay button with CSS and <apple-pay-button> element properties! See Apple Pay on the Web Interactive Demo for details and convenient tools for customizing the Apple Pay button.

❗Your website must comply with the Apple Pay acceptable use guidelines. For more information, see Apple's Acceptable Use Guidelines for Apple Pay on the Web.

2. Include the Preczn client on your page

Add the secure Preczn JavaScript client reference to the <head> of your page:

<script fetchPriority="high" src="https://api.preczn.com/v1/clients/preczn.min.js?resources=applepay&merchantId=mid_2zyd88xrnr90xskmjmqpd0x1vj&publicApiKey=2482re32338cd9z5048v7bhmb5"></script>

Β The following query parameters appended the script src URL are required:

ParameterDescription
merchantIdThe Preczn merchant ID for which you want to display the Apple Pay button.
publicApiKeyYour platform public API key for authentication.
resourcesA comma-delimited list of the client-side resources which you choose to utilize from the Preczn client. For Apple Pay, include applepay in this value.

❗️

Public Key Authentication

Ensure that you're using a public API key with PaymentFields, and not exposing and potentially compromising a sensitive private API key!

2.1. (Optional) Confirm all requisite Apple Pay resources have loaded and initialized

Preczn provides 2 mechanisms to ensure the Preczn client and the Apple Pay SDK have completed loading and initialization:

  1. The Preczn.ApplePay.ready value.
    1. If Preczn?.Apple?.ready is true you can proceed to initialize the Apple Pay button with the Preczn client.
    2. If the value is false or undefined then the resources have not yet loaded.
  2. A Preczn.ApplePay.ready event on the document object.
    1. When the Preczn client has completed loading requisite resources (such as the Apple Pay SDK) and initialization, it will dispatch an Event of the type Preczn.ApplePay.ready on the document.
    2. Add an event listener for the Preczn.ApplePay.ready event on document to be notified when loading and initialization have completed, then initialize the Apple Pay button.
      document.addEventListener(
        "Preczn.ApplePay.ready",
        (e) => {
          // Preczn and Apple Pay SDKs loaded, initialize Apple Pay button
          Preczn.ApplePay.initApplePayButton(123, callback);
        },
        false,
      );
      
    3. ℹ️ If you subscribe to the Preczn.ApplePay.loaded event, be sure to add your event listener to document before including the Preczn client on your page to avoid any chance the event is dispatched before the event listener is defined.

3. Define the required JavaScript callback function

Define a JavaScript callback function to handle tokenization result or errors:

var applepayCallback = function (result, errors) {
  if (!errors) {
    // Utilize resulting Preczn single-use token here
    var precznToken = result.token;
  } else {
    console.error(`Apple Pay errors:\r\n - ${errors.join("\r\n - ")}`);
  }
};

Callback function parameters

If no errors occurred the errors parameter value will be null, otherwise errors will contain an array of strings describing any error conditions.

Upon success Preczn creates a single-use merchant-specific token representing the Apple Pay payment method and provides it in the callback result object. The callback result parameter object will consist of following properties:

PropertyDescription
walletTypeThe walletType property of the single use token which was created. Always APPLEPAY.
typeThe account type of the card which the token represents: CREDIT or DEBIT.
brandThe brand of the card which the token represents: VISA, MASTERCARD, AMEX, DISCOVER, DINERS, JCB, UNIONPAY, or OTHER.
binThe bank identification number (BIN) of the card which the token represents. Typically the first 6 digits of the card number.
last4The last 4 digits of the card number which the token represents.
tokenThe Preczn token ID for the single-use, merchant-specific token representing this Apple Pay payment method.
billingContact *Object containing details about the billing contact associated with the payment method.
billingContact.addressAccount holder's Address line 1.
billingContact.address2Account holder's address line 2.
billingContact.cityAccount holder's city.
billingContact.regionAccount holder's region or state.
billingContact.postalAccount holder's postal or zip code.
billingContact.countryAccount holder's ISO 3166-1 alpha-3 country code.

* If made available by Apple Pay, the billingContact data will be included in the result object.

Example result object:

{
  "walletType": "APPLEPAY",
  "type": "CREDIT",
  "brand": "VISA",
  "bin": "432100",
  "last4": "0012",
  "expiration": "1234",
  "merchantId": "mid_2zyd88xrnr90xskmjmqpd0x1vj",
  "token": "tkn_apkwm89dr8br9zvqw4b3xgktk",
  "billingContact": {
    "firstName": "Bob",
    "lastName": "Smith",
    "address": "1 Infinite Loop",
    "address2": "Suite 1",
    "city": "Cupertino",
    "region": "CA",
    "postal": "95014",
    "country": "USA"
  }
}

πŸ“˜

Apple Pay Preczn Tokens are Single-use Only and Merchant-specific

Note that Preczn tokens returned for Apple Pay payment methods are merchant-specific and single-use only. Due to the nature of the underlying data, a multi-use token cannot be returned when the token is used for a transaction. Therefore it is advised that these tokens not be stored as card-on-file and not be used for a verify type transaction. Instead these tokens should be used to conduct a 'final' transaction such as a sale type transaction.

Callback errors

πŸ›‘ The following are errors which the Preczn Apple Pay client may send to your callback function:

  • Invalid API Key
    • Invalid Preczn public API key provided in publicApiKey query string parameter.
  • Invalid Merchant ID
    • Invalid Preczn merchant ID provided in merchantId query string parameter.
  • Unauthorized Request
    • HTTP 401 or 403 response received from Preczn API during attempt to validate merchant payment session or tokenize Apple Pay payment data. Confirm public API key and merchant ID values and try again. Contact Preczn support if the problem persists.
  • No domains configured for Apple Pay
    • You must add one or more Apple Pay domains to your configuration in the Preczn Dashboard .
    • Live mode Apple Pay will only work for your specific Preczn merchant IDs when the button is hosted and served on a domain which is registered with and verified by Preczn (to Apple Pay).
  • Referer domain not registered (checkout.example.com)
    • The domain from which the Preczn Apple Pay client has been loaded is not registered with Preczn. Confirm the domain serving your page is registered with Preczn.
  • Apple Pay not enabled for merchant
    • The merchant has had Apple Pay disabled, review the merchant settings and contact Preczn support if the problem persists.
  • Apple Pay can only be initialized on a secure (HTTPS) connection
    • Apple Pay will only work when the button is served via secure HTTPS connection.
  • No apple-pay-button elements found on page
    • The Preczn Apple Pay client found no apple-pay-button elements on your page. Ensure you have one apple-pay-button element on your page.
  • Too many apple-pay-button elements (N) found on page
    • The Preczn Apple Pay client found more than one apple-pay-button elements on your page, where N is the number of matching elements found. Ensure you have only one apple-pay-button element on your page.
  • Failed to create an Apple Pay Payment Session
    • The Preczn API failed to create an Apple Pay Payment Session. Confirm the domain in use is registered as an Apple Pay domain in the Preczn Dashboard. Contact Preczn support if the problem persists.
  • Failed to decrypt and tokenize Apple Pay payment data
    • The Preczn API failed to decrypt the Apple Pay payment data and create a single-use token from the result. Try again and contact Preczn support if the problem persists.

4. Initialize the Apple Pay button with the Preczn client

Call the Preczn JavaScript client to initialize the Apple Pay button:

<script type="text/javascript">
  Preczn.ApplePay.initApplePayButton(123, callback);
</script>

The initApplePayButton function takes up to 4 parameters, in this order:

ParametertypeDescription
Amount *NumberThe amount to charge for the transaction as a whole integer ($1.00 is 100).
Callback Function *functionThe function which is called when a single-use token is successfully generated for a cardholders Apple Pay payment method, or upon errors.
Country Codestring enum valueISO 3166-1 alpha-2 country code.
Defaults to US.
Currency Codestring enum valueISO-4217 3-character currency code.
Defaults to USD.

* Denotes a required parameter.

πŸ§ͺ Testing Apple Pay

Preczn Test Mode configurations utilize the Apple Pay Sandbox. See the Apple Pay Sandbox Testing Guide for information regarding sandbox test account setup and test card numbers.

Preczn performs as your Payment Service Provider ("PSP") for Apple Pay; handling automatic merchant registration, domain configuration and validation, and decryption and tokenization of payment data.

For testing Apple Pay, your responsibilities include:

Using with a Content Security Policy

If you are using a Content Security Policy to secure your client-side web application, you will need to extend your policy to allow applepay.min.js to load and connect to the Preczn API as well as allow Apple Pay resources.

Please add the following directives to your content security policy:

DirectiveValue
script-srcapi.preczn.com applepay.cdn-apple.com
connect-srcapi.preczn.com paymentrelayservice.apple.com
font-srcapplepay.cdn-apple.com
frame-srcapplepay.cdn-apple.com

πŸ’³ Process an Apple Pay Transaction

In order to process a transaction using the Apple Pay data you receive from this integration, send the merchant-specific single-use token and customer billing information, which you obtained from the client-side, to the Process Transaction API endpoint.

See the following recipe for an example:

🎨 Bonus Customization

The Apple Pay payment sheet will display an icon for the merchant if the page presenting the Apple Pay button has shortcut icon (favicon) and apple-touch-icon resources linked:

<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<link rel="apple-touch-icon" sizes="57x57" href="/apple-touch-icon-57x57.png" />
<link rel="apple-touch-icon" sizes="72x72" href="/apple-touch-icon-72x72.png" />
<link rel="apple-touch-icon" sizes="76x76" href="/apple-touch-icon-76x76.png" />
<link rel="apple-touch-icon" sizes="114x114" href="/apple-touch-icon-114x114.png" />
<link rel="apple-touch-icon" sizes="120x120" href="/apple-touch-icon-120x120.png" />
<link rel="apple-touch-icon" sizes="144x144" href="/apple-touch-icon-144x144.png" />
<link rel="apple-touch-icon" sizes="152x152" href="/apple-touch-icon-152x152.png" />
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon-180x180.png" />