Overview
Use this page to learn how to enable Apple Pay on the web using Apple Pay JS or the Payment 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.
As well as letting you try out the Apple Pay JavaScript APIs, this demo can also serve as a tutorial for your own implementation. It assumes you have 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 on the Web 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 through the page. After you are happy 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 Payment Request API, and to run this demo you need to use:
- iOS devices running iOS 11.3 or later
- Safari 11.1 on 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 webpage from the content delivery network:
<script src="https://applepay.cdn-apple.com/jsapi/v1/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 will display the latest style, render correctly across devices, and follow 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 shown 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"></apple-pay-button>
Create a Payment Request
When your customer clicks or taps the Apple Pay button, you construct a PaymentRequest
.
var request = null; if (window.PaymentRequest) request = new PaymentRequest(methods, details, options); else // Consider using Apple Pay JS instead.
The PaymentRequest
constructor takes three arguments:
- The payment methods you support
- The details to show to your customer (like shipping options and total amount)
- The options you require
Payment Methods
Payment methods represent the means by which you can accept payments from your customer using Payment Request.
You specify the payment methods you accept as a sequence of PaymentMethodData
dictionaries, each of which contains an identifier (supportedMethods
) and associated information (data
).
To accept payments using Apple Pay through the Payment Request, include it as a payment method. Apple Pay’s
URL-based payment method identifier is "https://apple.com/apple-pay"
,
and its associated data
is an ApplePayRequest
dictionary.
Safari supports only the Apple Pay payment method. Other browsers may support additional methods. The system determines which payment methods to present to show based on the capabilities of the device and on user preferences when more than one method is specified.
Try it: Apple Pay Method
You may configure the values in the PaymentMethodData
structure below.
Select Basic Request to see a payment sheet with only the required fields. Select Detailed Request to include optional fields.
Click or tap the Apple Pay button below to see how the payment sheet displays information.
Payment Details
Supply the payment details in the PaymentDetailsInit
dictionary. It contains your transaction’s total amount,
display items, shipping options, and payment method-specific modifiers. For more information on payment
modifiers, see Payment Modifiers below.
Select a default shipping option by setting the selected
attribute to true
as done in Try it: Payment Details for "Ground
Shipping"
when selecting More Details. The total amount needs to be $0.00 or greater, and when using Apple
Pay, all payment amounts in your request need to use the same ISO 4217 currency code. It
is up to you to ensure the correctness of your payment details; Safari doesn’t do any currency calculations on
your behalf.
Payment Modifiers
Apple Pay can update your transaction’s display items and total when you include optional modifiers
in your payment details. For example, you can adjust the price
based on the type of payment card.
Modifiers provide some of the functionality present in the
paymentmethodselected
event. For more information, see
ApplePayModifier
.
You can set up recurring payments, such as subscriptions, that feature different payment intervals (for example,
annually or monthly) and billing cycles (for example, regular or trial) by passing recurringPaymentRequest
to the ApplePayModifier
and with the ApplePayLineItem
that has recurring
paymentTiming
.
You can set up deferred payments, where a user pays at a later date by passing ApplePayLineItem
that has recurring
paymentTiming
and a valid date in the deferredPaymentDate
property in the ApplePayModifier
additionalLineItems
.
You can set up automatic reload payments, such as store card top-ups, by passing automaticReloadPaymentRequest
to the ApplePayModifier
and with the ApplePayLineItem
that has automaticReload
paymentTiming
, the amount
to describe reload amount, and the automaticReloadPaymentThresholdAmount
to
describe the threshold amount balance that is reached 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 that will receive 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 on 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, for example, a booking site where a user pays for a hotel, flight, and car rental from different
merchants. You can do this by passing ApplePayPaymentTokenContext
in the multiTokenContexts
property to the ApplePayModifier
.
Try it: Payment Details
Modify the values in the PaymentDetailsInit
structure below
and click or tap the Apple Pay button to view the payment sheet.
Note
Multimerchant payments are supported by select credit and debit cards only at this time.
If your card doesn’t support multimerchant payments, the payment sheet will indicate that your card is not accepted by this website.
Payment Options
Use PaymentOptions
to specify the information to request from your customer.
You can request your customer’s name, email address, or phone number, or request a certain type of shipping.
Try it: Payment Options
You may configure the values in the PaymentOptions
structure below.
Select Request Shipping Information to see a payment sheet with only a shipping request. Select Request All Information to see a payment sheet with all customer requests.
Click or tap the Apple Pay button below to see how the payment sheet displays information.
Complete Merchant Validation
Before being 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, not your browser client
code, unlike everything else in this demo. To start the merchant validation process, call the show
method on the PaymentRequest
you created above.
After you do, the browser will invoke your onmerchantvalidation
handler, which needs to fetch a merchant session from your
server.
Refer to the instructions in Requesting an Apple Pay Payment Session document to implement your server endpoint responsible for fetching the merchant session object from Apple Pay servers. If successful, Apple Pay servers will return a merchant session object, which your server needs to then pass back as the response to the browser.
You need to complete your onmerchantvalidation
handler by passing the promise containing the merchant
session response to the complete
method on the event.
The browser will then display the payment sheet.
The following code shows an example of how to validate merchant:
request.onmerchantvalidation = event => { // Call your own server to request a new merchant session. const merchantSessionPromise = fetch("/authorizeMerchant") .then(res => res.json()) // Parse response as JSON. .catch(err => { console.error("Error fetching merchant session", err); }); event.complete(merchantSessionPromise); };
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 user shipping address, or shipping method. To handle these adjusments, implement the optional handlers onpaymentmethodchange
, onshippingoptionchange
, and onshippingaddresschange
.
In the event handlers, you can determine the user’s selection using the PaymentRequest
shippingOption
and shippingAddress
attributes.
When the browser calls one of these handlers, you need to call the event object’s updateWith
callback function with a promise which resolves within 30 seconds to a PaymentDetailsUpdate
, otherwise, the transaction times out.
Note
In order for the displayItems
and the modifiers
to not get reset, you need to pass them to the PaymentDetailsUpdate
.
Request a Shipping Address
If you set requestShipping
to true
in the PaymentOptions
dictionary, Apple Pay provides redacted address information
before the user authenticates the transaction. After the user authenticates, Apple Pay provides the full contact
information in the PaymentResponse
resolved by the show
method’s returned promise.
The redacted payment information includes only the data needed 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 a redacted payment information:
shippingAddress: { "administrativeArea": "CA", "country": "United States", "countryCode": "US", "familyName": "", "givenName": "", "locality": "San Francisco", "phoneticFamilyName": "", "phoneticGivenName": "", "postalCode": "94114", "subAdministrativeArea": "", "subLocality": "" }
Try it: Updating Payment Details
You may customize the PaymentDetailsUpdate
below.
Select Success with or without updating display items and total below. Select Failure to see response with custom errors.
Click or tap the Apple Pay button below to see how the payment sheet displays updates or address errors.
Authorize the Payment
Finally, you receive a PaymentResponse
through the show
method’s returned promise to process the
transaction. After the user authenticates the transaction using Face ID, Touch ID, or their
device passcode, this promise will resolve with the encrypted Apple Pay token, as well as any fields requested
in the PaymentOptions
. 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 complete
method on the response and pass in a status of success
or fail
.
Note
Starting with iOS 16 and macOS Ventura, you can send an additional ApplePayPaymentCompleteDetails
argument to the complete
handler. This payload should include order
information that will be visible on user’s devices.
It is safe to send this additional argument even on older OS versions, it just will not be processed unless the user is on a recent OS.
See the new Order Tracking demo for details.
You may also validate the user’s info, and invoke the complete
method immediately, without calling the payment processor, if you
detect a problem with the selected options (for example, if a user has selected a shipping address in a
location that you don’t service).
Try it: complete
You may customize the complete
response
below.
Select Success below to default to success
. Select Failure to see a fail
response.
Click or tap the Apple Pay button below to see how the payment sheet completes the payment.
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.