On this page
Developer Portal References
Overview
Use this page to learn how to enable Apple Pay on the Web using the Payment Request API, Apple Pay JS API, or the Disbursement Request API. This demo preconfigures the Apple Pay button below with default values. Explore further by modifying values in the code blocks throughout the page to customize payment sheet experiences. This demo displays a transcript of server responses after each transaction for context. Click or tap the Show Transcript tab to view the transaction transcript.
In addition to letting you try out the Apple Pay JavaScript APIs, this demo can also serve as a tutorial for your own implementation. It assumes you’ve already set up your environment to process Apple Pay transactions, and are familiar with Apple Pay best practices. Before starting your integration, we recommend reviewing Planning for Apple Pay and the Apple Pay Human Interface Guidelines. For more information about supporting Apple Pay on your website, see Apple Pay on the Web.
This demo generates source code that you can copy into your own project. Click or tap the Show Source tab to view the source code. The demo updates the source code as you change values in the code blocks throughout the page. When you’re satisfied with the configuration, click or tap the Copy button inside the Show Source tab to copy the source code to your clipboard.
Requirements
This demo uses Apple Pay JS API, and to run this demo you need to use:
- iOS devices running iOS 11 or later
- Safari 11 with macOS 10.13 or later
Display an Apple Pay button
To display an Apple Pay button, use the following code to load the button script into your web page from the content delivery network:
<script crossorigin src="https://applepay.cdn-apple.com/jsapi/1.latest/apple-pay-sdk.js" ></script>
The JavaScript Apple Pay button provides a variety of Apple Pay button types that you can use on your website to initiate a transaction. You can specify the Apple Pay button style, type, and localization using attributes. Use CSS to set other properties, such as the size and corner radius. Using the official Apple Pay button element ensures your site displays the latest style, renders correctly across devices, and follows Apple guidelines. For design guidance, see Human Interface Guidelines > Apple Pay > Buttons and Marks.
Try it: Display settings
Use the following tools to try the different display settings on the button below:
Button Style
Button Type
Button Language
Button Box Sizing
<style> apple-pay-button { --apple-pay-button-width: 150px; --apple-pay-button-height: 30px; --apple-pay-button-border-radius: 3px; --apple-pay-button-padding: 0px 0px; --apple-pay-button-box-sizing: border-box; } </style> <apple-pay-button buttonstyle=" " type="plain" locale="en-US"></apple-pay-button>
Create a Payment Request
When your customer clicks or taps the Apple Pay button, you first need to construct an ApplePaySession
object, which
includes the ApplePayPaymentRequest
dictionary detailing the
transaction details the payment sheet will display.
The ApplePayPaymentRequest
requires details,
including the total payment for the transaction, the currency, and the supported payment networks. You can
optionally pass lineItems
to show additional charges and discounts, and
shippingMethods
to allow the customer to choose from
different shipping options. If you require address or contact details from your customer, request them by
passing values in the requiredShippingContactFields
or requiredBillingContactFields
.
You can set up recurring payments, such as subscriptions, that feature different payment intervals (such as
annually or monthly) and billing cycles (such as regular or trial) by passing ApplePayRecurringPaymentRequest
to the ApplePayPaymentRequest
with the ApplePayLineItem
that has a recurring
paymentTiming
value.
You can set up deferred payments, where a user pays at a later date, with the ApplePayLineItem
that has a recurring
paymentTiming
value and a valid date in the deferredPaymentDate
property.
You can set up automatic reload payments, such as store card top-ups, by passing automaticReloadPaymentRequest
to the ApplePayPaymentRequest
with the ApplePayLineItem
that has an automaticReload
paymentTiming
, the amount
to describe the reload amount, and the automaticReloadPaymentThresholdAmount
to
describe the threshold amount balance to reach before automatically applying the reload amount.
Note
You must also include managementURL
, the URL where the user can update or delete the payment method for the automatic payment,
and tokenNotificationURL
, an API endpoint on your web service to receive the life-cycle notifications from Apple Pay servers about the Apple Pay merchant token for the recurring payment.
See Apple Pay Merchant Token Management API for more details about implementing and interacting with Merchant Token APIs.
You can set up multitoken transactions to process and display payments with multiple merchants on one payment
sheet, such as a booking site where a user pays for a hotel, a flight, and a car rental from different
merchants in a single Apple Pay transaction. You can do this by passing ApplePayPaymentTokenContext
in the multiTokenContexts
property to the ApplePayPaymentRequest
.
See Creating an Apple Pay Session for more detail.
Try it: ApplePayPaymentRequest
Modify the values in the ApplePayPaymentRequest
below and click or tap the
Apple Pay button to view the payment sheet.
lineItems
)
ApplePayRecurringPaymentRequest
and the relevant fields in ApplePayLineItem
like recurringPaymentStartDate
)
ApplePayLineItem
like deferredPaymentDate
)
deferredPaymentRequest
structure)
ApplePayLineItem
like automaticReloadPaymentThresholdAmount
)
ApplePayPaymentTokenContext
for each
token in the multiTokenContexts
property)
Note
Only select credit and debit cards support multimerchant payments at this time.
If your card doesn’t support multimerchant payments, the payment sheet indicates that this
website doesn’t accept the selected payment card.
Complete merchant validation
Before you are able to display the payment sheet to the customer, you need to generate a valid payment session by
interacting with Apple Pay servers. For security reasons, your server needs to do this interaction, not your browser client
code, unlike everything else in this demo. To start the merchant validation process, call the begin
method on the session object you created above.
After calling the begin
method, the browser invokes your onvalidatemerchant
handler, which needs to fetch a merchant
session from your server.
Refer to the instructions in Requesting an Apple Pay Payment Session to implement your server endpoint responsible for fetching the merchant session object from Apple Pay servers. If the fetch is successful, Apple Pay servers return a merchant session object, which your server needs to then pass back as the response to the browser.
After you have the merchant session response object in the browser, you need to complete your
onvalidatemerchant
handler by passing that object to the
completeMerchantValidation
method on the session object.
The browser then displays the payment sheet.
The following code shows an example of how to validate a merchant to generate a payment session:
session.onvalidatemerchant = event => { // Call your own server to request a new merchant session. fetch(event.validationURL) .then(res => res.json()) // Parse the response as JSON. .then(merchantSession => { session.completeMerchantValidation(merchantSession); }) .catch(err => { console.error("Error fetching merchant session", err); }); };
Respond to payment sheet interactions
After merchant validation is complete, Apple Pay provides the information about your customer’s payment sheet
selections so that you can calculate the final transaction cost. The final details of a transaction may depend
on the user’s payment method, billing address, shipping address, or shipping method.
To handle these adjustments, implement the optional handlers onpaymentmethodselected
,
oncouponcodechanged
,
onshippingmethodselected
,
and
onshippingcontactselected
. When the browser calls one of
these handlers, you have 30 seconds to process it and call the corresponding callback function; otherwise, the
transaction times out. All callbacks accept an object with newTotal
(required), newLineItems
(optional), newMultiTokenContexts
(optional), newRecurringPaymentRequest
(optional), and newAutomaticReloadPaymentRequest
(optional)
keys. In addition, you may specify newShippingMethods
to update shipping methods, and an
errors
key containing an array of one or more ApplePayError
objects to indicate problems with the
user’s selected shipping address when calling the
completeCouponCodeChange
or the completeShippingContactSelection
.
Payment method selected
Event handler |
onpaymentmethodselected
|
---|---|
Callback function |
completePaymentMethodSelection
|
Update structure |
ApplePayPaymentMethodUpdate
|
Update properties |
newTotal (required)
newLineItems (optional)
newMultiTokenContexts (optional)
newRecurringPaymentRequest (optional)
newAutomaticReloadPaymentRequest (optional)
newShippingMethods (optional)
errors (optional)
|
Coupon code changed
Event handler |
oncouponcodechanged
|
---|---|
Callback function |
completeCouponCodeChange
|
Update structure |
ApplePayCouponCodeUpdate
|
Update properties |
newTotal (required)
newLineItems (optional)
newMultiTokenContexts (optional)
newRecurringPaymentRequest (optional)
newAutomaticReloadPaymentRequest (optional)
newShippingMethods (optional)
errors (optional)
|
Shipping method selected
Event handlers |
onshippingmethodselected
|
---|---|
Callback function |
completeShippingMethodSelection
|
Update structure |
ApplePayShippingMethodUpdate
|
Update properties |
newTotal (required)
newLineItems (optional)
newMultiTokenContexts (optional)
newRecurringPaymentRequest (optional)
newAutomaticReloadPaymentRequest (optional)
newShippingMethods (optional)
|
Shipping contact address selected
Event handlers |
onshippingcontactselected
|
---|---|
Callback function |
completeShippingContactSelection
|
Update structure |
ApplePayShippingContactUpdate
|
Update properties |
newTotal (required)
newLineItems (optional)
newMultiTokenContexts (optional)
newRecurringPaymentRequest (optional)
newAutomaticReloadPaymentRequest (optional)
newShippingMethods (optional)
errors (optional)
|
Demo Note
The test transaction passes in a default success response when it calls
completePaymentMethodSelection
. The test transaction passes in
newLineItems
and
newTotal
when it calls
completeShippingMethodSelection
. See the responses in the transcript.
Request a shipping address
If you pass
requiredShippingContactFields
in the
payment request with a postalAddress
value, Apple Pay provides redacted address information before the user
authenticates the transaction. After the user authenticates, Apple Pay provides the full contact information.
The redacted payment information includes only the data necessary to complete required transaction tasks, such as calculating taxes or shipping costs, and may differ based on the user’s geographic region.
The following code shows an example of redacted payment information:
onshippingcontactselected: { "administrativeArea": "CA", "country": "United States", "countryCode": "US", "familyName": "", "givenName": "", "locality": "San Francisco", "phoneticFamilyName": "", "phoneticGivenName": "", "postalCode": "94114", "subAdministrativeArea": "", "subLocality": "" }
Try it: completeShippingContactSelection
Select one of the Success options below (with or without updating line items and total) to see a successful response.
Select Failure to see a completeShippingContactSelection
response with custom
errors. You may edit the ApplePayShippingContactUpdate
response object below to
experiment with different responses. Click or tap the Apple Pay button below to see how the payment sheet
displays updates or address errors.
Authorize the payment
Finally, you need to implement the onpaymentauthorized
handler that’s responsible
for processing the transaction. After the user authenticates the transaction using Face ID, Touch ID, or their
device passcode, the system calls this handler with the encrypted Apple Pay token, as well as the shipping and
billing fields if you request them in the ApplePayPaymentRequest
. To finalize the transaction,
you need to pass the encrypted payment token to your payment processor using their API.
After you receive the response from your payment processor, call the completePayment
method on the session and indicate
either STATUS_SUCCESS
or STATUS_FAILURE
with an array of associated ApplePayError
objects.
Note
Starting with iOS 16 and macOS 13, you can send an additional
orderDetails
key in the completePayment
handler payload with order
information that is visible on users’ devices.
It’s safe to send this additional argument for older OS versions — it just doesn’t process unless the user is using a recent OS.
See the Order Tracking demo for details.
You may also validate the shipping and billing information, and invoke the completePayment
method
immediately, without calling the payment processor, if you detect a problem with the selected options (for
example, if a user selects a shipping address in a location that you don’t service). Use the contactField
key to specify the
exact field that’s causing the error.
Try it: completePayment
Use the following values to customize the completePayment
response
below:
"status": 0
to indicateSTATUS_SUCCESS
"status": 1
to indicateSTATUS_FAILURE
Select Success to default to STATUS_SUCCESS
. Select
Failure to see a completePayment
response with custom errors.
Click or tap the Apple Pay button to see how the payment sheet completes the payment.
Disbursements
Implement the Disbursement Request API to disburse funds to your customer. With the Disbursement Request API, you can allow your site visitors to transfer funds from your site to an account that is linked to a card in Wallet. The Disbursement Request API is only available as a subset of the Payment Request API.
Additional resources
Ready to integrate Apple Pay into your website? Here are a few links you may find useful:
Questions or feedback
Check out our developer forums or reach out to us.