Accept Apple Pay

Add the Apple Pay button to your web checkout with the Preczn client, get a single-use token, and process an Apple Pay transaction.

Add an Apple Pay button to your checkout page and charge the customer's Apple Pay card. You place Apple's <apple-pay-button> element on your page, and the Preczn browser client runs the Apple Pay session. When the customer authorizes the payment, Preczn decrypts the Apple Pay data and sends a single-use token to your callback. Your server charges the token with Process Transaction.

The token works for one transaction and only for the merchant that loaded the button. See Wallets.


How it works

sequenceDiagram
    actor Customer
    participant Page as Your checkout page
    participant Apple as Apple Pay
    participant Preczn
    participant Server as Your server

    Page->>Preczn: Load the Preczn client (merchantId, public key)
    Preczn-->>Page: Client, after checking the key, merchant, and domain
    Customer->>Page: Select the Apple Pay button
    Page->>Preczn: Start an Apple Pay session
    Preczn->>Apple: Validate the merchant session
    Apple-->>Page: Show the payment sheet
    Customer->>Apple: Authorize the payment
    Apple-->>Page: Encrypted payment data
    Page->>Preczn: Send the encrypted payment data
    Preczn-->>Page: Single-use token, in your callback
    Page->>Server: Send the token and billing details
    Server->>Preczn: POST /v1/transactions
    Preczn-->>Server: Transaction result

Prerequisites

  • A public API key (pub_) for your platform. Never put a private key in browser code. See API keys.
  • A merchant with Apple Pay turned on and a connection that processes Apple Pay. See Wallets and the Apple Pay column in Supported connections.
  • Each domain that serves your checkout page, verified in the same mode as the merchant. See Verify Apple Pay domains.
  • A checkout page served over HTTPS.

Add Apple Pay to your page

To add the Apple Pay button, complete the following steps:

  1. Add one <apple-pay-button> element where you want the button:

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

    For the element's attributes, see Apple's Displaying Apple Pay Buttons using JavaScript. You don't need to load the Apple Pay SDK yourself. The Preczn client loads it.

    The Preczn client finds the element with getElementsByTagName('apple-pay-button'). If the page has no <apple-pay-button> element, or more than one, the client sends an error to your callback.

  2. Style the button with CSS and the element's attributes. Apple's Apple Pay on the Web Interactive Demo previews each style.

    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.

  3. Define the callback that receives the result or the errors:

    function applePayCallback(result, errors) {
      if (errors) {
        console.error(`Apple Pay errors:\n - ${errors.join("\n - ")}`);
        return;
      }
      // Send result.token and result.billingContact to your server.
    }

    On success, errors is null and result holds the token. See the Callback result section. On failure, result is null and errors is an array of strings. See the Callback errors section.

  4. In the <head> of your page, add a listener for the Preczn.ApplePay.ready event on document that calls initApplePayButton. The client dispatches the event when it and the Apple Pay SDK finish loading. Put the listener before the Preczn client's <script> tag, so it's in place when the event fires. For the listener syntax, see addEventListener.

    <script>
      document.addEventListener("Preczn.ApplePay.ready", () => {
        Preczn.ApplePay.initApplePayButton(1250, applePayCallback, "US", "USD");
      });
    </script>
    ParameterTypeRequiredDescription
    AmountnumberYesAn integer in the smallest currency unit, such as 1250 for $12.50
    CallbackfunctionYesReceives the result or the errors
    Country codestringNoISO 3166-1 alpha-2. Defaults to US
    Currency codestringNoISO 4217. Defaults to USD

    Call initApplePayButton only after the client is ready. To check without the event, test Preczn?.ApplePay?.ready, which is true once the client is ready.

    If the browser can't use Apple Pay, the client doesn't set up the button, and the Apple Pay SDK hides it.

  5. After the listener, add the Preczn client to the <head>, with resources=applepay:

    <script fetchpriority="high" src="https://api.preczn.com/v1/clients/preczn.min.js?resources=applepay&merchantId={merchantId}&publicApiKey={publicApiKey}"></script>

    For every loader option, such as loading several features with one script tag, see Browser client reference.

    Query parameterDescription
    merchantIdThe Preczn merchant ID that the button charges
    publicApiKeyYour platform's public API key
    resourcesA comma-separated list of client resources. Include applepay
  6. Send the token to your server and charge it. See the Charge the Apple Pay token section.

Callback result

PropertyDescription
tokenThe single-use token for this Apple Pay payment
walletTypeAlways APPLEPAY
typeCREDIT or DEBIT
brandVISA, MASTERCARD, AMEX, DISCOVER, or OTHER
binThe card's bank identification number
last4The card number's last four digits
expirationThe card's expiration date, as MMYY
merchantIdThe merchant that loaded the button
billingContactThe customer's name, billing address, and email, when Apple Pay provides them

The client asks Apple Pay for the customer's name, billing address, and email. billingContact.country is an ISO 3166-1 alpha-3 code.

{
  "walletType": "APPLEPAY",
  "type": "CREDIT",
  "brand": "VISA",
  "bin": "432100",
  "last4": "0012",
  "expiration": "1228",
  "merchantId": "mid_test_{merchantId}",
  "token": "tkn_test_{tokenId}",
  "billingContact": {
    "firstName": "{firstName}",
    "lastName": "{lastName}",
    "address": "123 Main Street",
    "address2": "Suite 100",
    "city": "Springfield",
    "region": "IL",
    "postal": "62701",
    "country": "USA",
    "email": "[email protected]"
  }
}

Callback errors

The client sends these errors to your callback:

ErrorCause and fix
Invalid API KeypublicApiKey isn't an active public key. Use your platform's public key
Invalid Merchant IDmerchantId isn't a merchant on your platform. Check the ID
ApplePay not enabled for merchantApple Pay is off for the merchant. See Wallets
No domains configured for Apple PayYour platform has no Apple Pay domains in this mode. See Verify Apple Pay domains
Referer domain not registered ({domain})The page's domain isn't verified in this mode. Verify it
Apple Pay can only be initialized on a secure (HTTPS) connectionServe the page over HTTPS
No apple-pay-button elements found on pageAdd one <apple-pay-button> element
Too many apple-pay-button elements ({count}) found on pageKeep only one <apple-pay-button> element
Failed to create an Apple Pay Payment SessionPreczn couldn't start the session. Check the key, merchant ID, and domain
Failed to decrypt and tokenize Apple Pay payment dataPreczn couldn't create the token. Try again

If an error persists, contact Preczn support.

Show your icon on the payment sheet

The Apple Pay payment sheet shows the merchant's icon when the page links a shortcut icon (favicon) and apple-touch-icon resources:

<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" />

Use a Content Security Policy

If your page uses a Content Security Policy, add these directives so the Preczn client and Apple Pay can load:

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

Charge the Apple Pay token

To charge the token, complete the following steps on your server:

  1. Send POST /v1/transactions with type set to sale, the merchantId that loaded the button, the token in payment.token, and the amount. Copy the customer's details from billingContact into firstName, lastName, email, and billingAddress.

    Send the same currency that you passed to initApplePayButton, or leave it out if you used USD. Preczn rejects the transaction when the currency doesn't match the token.

    {
        "merchantId": "mid_test_{merchantId}",
        "type": "sale",
        "amount": 1250,
        "currency": "USD",
        "payment": {
            "token": "tkn_test_{tokenId}"
        },
        "firstName": "{firstName}",
        "lastName": "{lastName}",
        "email": "[email protected]",
        "billingAddress": {
            "address": "123 Main Street",
            "address2": "Suite 100",
            "city": "Springfield",
            "region": "IL",
            "postal": "62701",
            "country": "USA"
        }
    }

    The token works once, so send an idempotency key to retry safely. See Idempotency keys.

  2. Check authorization.status in the response. A means approved. payment.walletType is APPLEPAY. For the other statuses, see Charge a payment.

    {
        "id": "txn_test_{transactionId}",
        "type": "sale",
        "amount": 1250,
        "currency": "USD",
        "merchantId": "mid_test_{merchantId}",
        "authorization": {
            "status": "A",
            "approvedAmount": 1250,
            "processorCode": "{processorCode}",
            "processorMessage": "{processorMessage}"
        },
        "payment": {
            "bin": "432100",
            "brand": "VISA",
            "last4": "0012",
            "type": "CREDIT",
            "walletType": "APPLEPAY"
        }
    }

    This response is abbreviated. For every field, see Process Transaction.


Test Apple Pay

In test mode, Preczn uses the Apple Pay sandbox. For sandbox tester accounts and test cards, see Apple's Apple Pay Sandbox Testing Guide.

Preczn acts as your Payment Service Provider (PSP) for Apple Pay. It registers your merchants and domains with Apple, validates each payment session, and decrypts and tokenizes the payment data.

To test Apple Pay, you're responsible for the following:


Next


Did this page help you?