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:
-
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. -
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.
-
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,
errorsisnullandresultholds the token. See the Callback result section. On failure,resultisnullanderrorsis an array of strings. See the Callback errors section. -
In the
<head>of your page, add a listener for thePreczn.ApplePay.readyevent ondocumentthat callsinitApplePayButton. 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, seeaddEventListener.<script> document.addEventListener("Preczn.ApplePay.ready", () => { Preczn.ApplePay.initApplePayButton(1250, applePayCallback, "US", "USD"); }); </script>Parameter Type Required Description Amount numberYes An integer in the smallest currency unit, such as 1250for $12.50Callback functionYes Receives the result or the errors Country code stringNo ISO 3166-1 alpha-2. Defaults to USCurrency code stringNo ISO 4217. Defaults to USDCall
initApplePayButtononly after the client is ready. To check without the event, testPreczn?.ApplePay?.ready, which istrueonce 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.
-
After the listener, add the Preczn client to the
<head>, withresources=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 parameter Description merchantIdThe Preczn merchant ID that the button charges publicApiKeyYour platform's public API key resourcesA comma-separated list of client resources. Include applepay -
Send the token to your server and charge it. See the Charge the Apple Pay token section.
Callback result
| Property | Description |
|---|---|
token | The single-use token for this Apple Pay payment |
walletType | Always APPLEPAY |
type | CREDIT or DEBIT |
brand | VISA, MASTERCARD, AMEX, DISCOVER, or OTHER |
bin | The card's bank identification number |
last4 | The card number's last four digits |
expiration | The card's expiration date, as MMYY |
merchantId | The merchant that loaded the button |
billingContact | The 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:
| Error | Cause and fix |
|---|---|
Invalid API Key | publicApiKey isn't an active public key. Use your platform's public key |
Invalid Merchant ID | merchantId isn't a merchant on your platform. Check the ID |
ApplePay not enabled for merchant | Apple Pay is off for the merchant. See Wallets |
No domains configured for Apple Pay | Your 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) connection | Serve the page over HTTPS |
No apple-pay-button elements found on page | Add one <apple-pay-button> element |
Too many apple-pay-button elements ({count}) found on page | Keep only one <apple-pay-button> element |
Failed to create an Apple Pay Payment Session | Preczn couldn't start the session. Check the key, merchant ID, and domain |
Failed to decrypt and tokenize Apple Pay payment data | Preczn 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:
| Directive | Value |
|---|---|
script-src | api.preczn.com applepay.cdn-apple.com |
connect-src | api.preczn.com paymentrelayservice.apple.com |
font-src | applepay.cdn-apple.com |
frame-src | applepay.cdn-apple.com |
Charge the Apple Pay token
To charge the token, complete the following steps on your server:
-
Send
POST /v1/transactionswithtypeset tosale, themerchantIdthat loaded the button, the token inpayment.token, and theamount. Copy the customer's details frombillingContactintofirstName,lastName,email, andbillingAddress.Send the same
currencythat you passed toinitApplePayButton, or leave it out if you usedUSD. 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.
-
Check
authorization.statusin the response.Ameans approved.payment.walletTypeisAPPLEPAY. 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:
- Configuring Preczn:
- Adding and managing your Apple Pay domains.
- Giving each merchant a connection that processes Apple Pay.
- Integrating the Preczn Apple Pay client as this guide describes.
- Creating Apple sandbox tester accounts. See Create Sandbox Apple IDs.
- Adding test cards to each sandbox tester's Apple Wallet.
- Making sure your Apple Pay integration follows the Acceptable Use Guidelines for Apple Pay on the Web.
- Making sure your Apple Pay integration follows the Apple Pay Human Interface Guidelines.
Next
- To accept Google Pay too, see Accept Google Pay.
- To handle a transaction that returns
P(pending), see Handle synchronous and asynchronous results.
Updated 11 days ago
