Prerequisites
- Ensure you have PayPal business account approved for Expanded Checkout.
- Ensure you set up developer, sandbox, and production environment accounts.
- Ensure you create an Apple Pay sandbox account for testing in the sandbox environment.
Load PayPal JS SDK
PayPal’s JavaScript SDK provides the necessary pre-built tools to render the Apple Pay button on your webpage and handle payment authorization. Include the PayPal SDK core and Apple Pay SDK as<script>
tags in the HTML file that renders your webpage.
For production environment:
Create browser-safe client token
The browser-safe token is a client-side access token that authorizes the app to use the JavaScript SDK resources. Configure your server to call PayPal’s OAuth API and parse theaccess_token
from the response for your client-side application.
In the server-side call to the /v1/oauth2/token
endpoint:
- Encode app credentials
Client ID : Secret
in Base64 format and use it in theAuthorization
header. - Include the following data parameters:
grant_type
: Set the parameter value toclient_credentials
to specify that the app is requesting to exchange client ID and secret for an access token.response_type
: Set the parameter value toclient_token
to request for a client-side access token.intent
: Set the parameter value tosdk_init
to specify that the purpose for the request is SDK initialization.
access_token
response parameter.
Initialize JS SDK and create SDK instance
Use thewindow.paypal.createInstance()
method to create a PayPal SDK instance and include the following parameters:
clientToken
: The browser-safe client token.components
: Set to["applepay-payments"]
to indicate that you intend to render Apple Pay components.
createApplePayOneTimePaymentSession()
for creating Apple Pay payment sessions and findEligibleMethods()
for checking payment method availability.
Create PayPal’s Apple Pay one-time payment session
Create PayPal’s session that handles Apple Pay configuration and merchant validation. This session manages PayPal-specific operations and provides the settings needed for the native Apple Pay session created later.Create payment session
Use thecreateApplePayOneTimePaymentSession()
method to create the session. This method doesn’t require any parameters as it uses the configuration from SDK initialization.
Response: Contains config()
to get Apple Pay configuration and validateMerchant()
to validate merchant with Apple Pay servers.
Get Apple Pay configuration
Use thepaypalSdkApplePayPaymentSession.config()
method to retrieve Apple Pay configuration. This method doesn’t require any parameters.
Response: Contains the following:
merchantCapabilities
(array): Supported payment processing capabilities.supportedNetworks
(array): Supported card networks.isEligible
(boolean): Indicates if Apple Pay is eligible.merchantCountry
(string): Merchant’s country code.
Verify eligibility
Use the following methods to determine if you are eligible to offer Apple Pay as a payment method:findEligibleMethods
- Returns all the eligible payment methods.isEligible
- Boolean method that determines if Apple Pay is an eligible payment method.
findEligibleMethods()
with an options
object containing the following:
apiCode
: Set torestApi
to specify the API methodology.countryCode
: Set to the two-letter country code. Example:US
.currencyCode
: Set to the three-letter currency code. Example:USD
.paymentMethods
: Set to["APPLE_PAY"]
to check Apple Pay eligibility.
paymentMethods
object with isEligible()
method to check if Apple Pay is eligible.
Render Apple Pay button
After confirming eligibility, render the Apple Pay button on your webpage. To render the Apple Pay button:- Define the container for the Apple Pay button: In the HTML file corresponding to the webpage where you want to render the button, include a container element as shown in the sample code:
- Add the Apple Pay button element: Dynamically insert the Apple Pay button HTML element into the container. The
<apple-pay-button>
web component supports the following attributes:id
: Unique identifier for the button element.buttonstyle
: Visual style of the button. Example:black
.type
: Button label type. Example:buy
.locale
: Language code for button text. Example:en
.
- Attach the event handler: Use
addEventListener()
to register theonClickApplePay
callback handler that executes when customers select the Apple Pay button. This handler manages:- Apple Pay session creation.
- Merchant validation with Apple Pay servers.
- Payment authorization and token creation.
- Vault setup token and payment token generation.
- Sets up the Apple Pay button on your webpage.
- Defines the on-click flow for your button.
Define on-click event handler function
Create an event handler to process Apple Pay button clicks and start the payment session. This function contains all the logic needed to handle the Apple Pay vault flow.1. Create payment request object
Define the payment request with required billing fields and zero amount.2. Verify Apple Pay availability
Check browser support and device capability for Apple Pay.3. Create new Apple Pay session
Initialize a new Apple Pay session with the payment request details.4. Set up event handlers
Event handlers manage the different outcomes when your customers attempt to save Apple Pay. Configure event handlers for the Apple Pay session lifecycle.a. Handle merchant validation
In your app code, include the logic to validate the merchant identity with Apple Pay servers through PayPal. Use thepaypalSdkApplePayPaymentSession.validateMerchant()
method to validate the merchant with Apple Pay servers and include the following parameters:
validationUrl
: The validation URL provided by Apple Pay (fromevent.validationURL
).displayName
(optional): Merchant display name.domainName
(optional): Merchant domain name.
merchantSession
: the merchant session object to pass to Apple Pay.
b. Handle payment method selection
In your app code, include the logic to handle when the customer selects a different payment card in Apple Wallet. Use thecompletePaymentMethodSelection()
method to confirm the selection with newTotal
parameter set to the payment total object (from paymentRequest.total
).
Response: Updates the Apple Pay sheet with the confirmed selection.
c. Handle payment authorization
In your app code, include the logic to process the Apple Pay payment authorization and create vault tokens. Use thecompletePayment()
method to notify Apple Pay of the transaction status with status
parameter set to the payment status (window.ApplePaySession.STATUS_SUCCESS
or window.ApplePaySession.STATUS_FAILURE
).
Response: Closes the Apple Pay sheet and displays the appropriate success or failure message to the customer.
Create vault setup token
Create a setup token for saving payment methods without an initial payment. This token is different from the browser-safe client token and is used to generate the payment method token. First, encode the Apple Pay payment data using a helper function that formats the token data in the required structure for PayPal’s Vault API:/v3/vault/setup-tokens
endpoint:
- Use a Bearer token in the
Authorization
header. - Include the following in the request body:
payment_source.apple_pay.token
: Set to the Base64 encoded Apple Pay token containing payment data.
id
response parameter.
Create Payment Method Token (PMT)
Convert the setup token to a reusable payment method token for future transactions. In the server-side call to the/v3/vault/payment-tokens
endpoint:
- Use a Bearer token in the
Authorization
header. - Include the following in the request body:
payment_source.token.type
: Set toSETUP_TOKEN
to specify the token type.payment_source.token.id
: Set to the setup token ID from the previous step.
id
response parameter, which is the reusable token for future transactions.
Complete transaction
Notify Apple Pay that the payment was processed successfully.d. Handle cancellation
In your app code, include the logic to handle cancellation when the customer closes the Apple Pay payment sheet. Use theonCancel()
callback function to handle cleanup operations when the customer cancels. This method doesn’t require any parameters.
Response: Performs any necessary cleanup and resets the payment flow state.
e. Handle errors
In your app code, include the logic to handle errors that occur during the authentication flow. Use theonError()
callback function to handle errors with data
parameter containing the error details.
Response: Logs the error and displays an appropriate error message to the customer.
f. Handle completion
In your app code, include the logic to handle when the authentication flow finishes. Use theonComplete()
callback function to handle completion with an optional data
parameter that may contain completion details.
Response: Performs any final cleanup or UI updates needed after the authentication flow completes.
5. Start Apple Pay flow
In your app code, start the Apple Pay payment session after configuring all event handlers. Use theappleSdkApplePayPaymentSession.begin()
method to display the Apple Pay payment sheet. This method doesn’t require any parameters.
Response: The Apple Pay payment sheet appears, allowing the customer to:
- View the payment request details
- Select their preferred payment method from Apple Wallet
- Authorize the payment
- Complete the save payment method flow