Use this file to discover all available pages before exploring further.
Save Apple Pay as a payment method for future purchases without an initial transaction. Use PayPal’s JavaScript SDK to tokenize and save Apple Pay credentials for later use.
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:
{/* PayPal Web SDK */}<script src="https://www.paypal.com/web-sdk/v6/core"></script>{/* Apple Pay SDK */}<script src="https://applepay.cdn-apple.com/jsapi/v1/apple-pay-sdk.js"></script>
For sandbox environment:
{/* PayPal Web SDK (Sandbox) */}<script src="https://www.sandbox.paypal.com/web-sdk/v6/core"></script>{/* Apple Pay SDK */}<script src="https://applepay.cdn-apple.com/jsapi/v1/apple-pay-sdk.js"></script>
The browser-safe token is a client-side access token that authorizes an app to use the JavaScript SDK resources.
A browser-safe token is not the same as a server-side access token. The server-side access token helps PayPal authenticate an app when the app accesses PayPal REST API resources.
To get the browser-safe client token from your server-side code, make a POST call to the /v1/oauth2/token endpoint and include the following:
Encoded app credentials Client ID : Secret in Base64 format, in the Authorization header.
Data parameters:
Parameter
Action
grant_type
Set the parameter value to client_credentials to specify that the app is requesting to exchange client ID and secret for an access token.
response_type
Set the parameter value to client_token to request a client-side access token.
intent
Set the parameter value to sdk_init to specify that the purpose for the request is SDK initialization.
Response: Contains the browser-safe client token in the access_token response parameter.
Use the window.paypal.createInstance() method to create a PayPal SDK instance and include the following parameters:
Parameter
Action
clientToken
Pass the browser-safe client token.
components
Set to ["applepay-payments"] to indicate that you intend to render Apple Pay components.
Response: Contains an SDK instance object with the createApplePayOneTimePaymentSession() method for creating Apple Pay payment sessions and the findEligibleMethods() method 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.
Use the createApplePayOneTimePaymentSession() 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.
Use the paypalSdkApplePayPaymentSession.config() method to retrieve Apple Pay configuration. This method doesn’t require any parameters.Response: Contains the following:
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:
<section class="payment-method-container" id="applepay-section"> <h2>Apple Pay Button</h2> <p>This example uses the Apple Pay button web component to launch the vault without purchase flow.</p> {/* Button will be added dynamically if eligible */}</section>
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:
Attribute
Action
id
Set to a unique identifier for the button element.
buttonstyle
Set to the visual style of the button. Example: black.
type
Set to the button label type. Example: buy.
locale
Set to the language code for button text. Example: en.
Attach the event handler: Use addEventListener() to register the onClickApplePay callback handler that executes when customers select the Apple Pay button. This handler manages:
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.
async function onClickApplePay() { // Step 1: Create payment request object // Step 2: Verify Apple Pay availability // Step 3: Create new Apple Pay session // Step 4: Set up event handlers // Step 5: Start Apple Pay flow}
Check browser support and device capability for Apple Pay.
// Check Apple Pay availabilityif (!window.ApplePaySession) { console.log("Apple Pay is not available - ApplePaySession not found"); return;}if (!ApplePaySession.canMakePayments()) { console.log("Apple Pay is not available - canMakePayments returned false"); return;}console.log("Apple Pay version supported:", ApplePaySession.supportsVersion(4));console.log("Payment request:", paymentRequest);
Event handlers manage the different outcomes when your customers attempt to save Apple Pay. Configure event handlers for the Apple Pay session lifecycle.
In your app code, include the logic to validate the merchant identity with Apple Pay servers through PayPal.Use the paypalSdkApplePayPaymentSession.validateMerchant() method to validate the merchant with Apple Pay servers and include the following parameters:
Parameter
Action
validationUrl
Pass the validation URL provided by Apple Pay (from event.validationURL).
displayName
Set to the merchant display name.
domainName
Set to the merchant domain name.
Response: Contains merchantSession to pass to Apple Pay.
In your app code, include the logic to handle when the customer selects a different payment card in Apple Wallet.Use the completePaymentMethodSelection() 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.
In your app code, include the logic to process the Apple Pay payment authorization and create vault tokens.Use the completePayment() 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 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:
function encodePaymentToken(token) { var data = { partner: "paypal", paymentData: token.paymentData }; return btoa(JSON.stringify(data));}
In the server-side call to the /v3/vault/setup-tokens endpoint:
Use a Bearer token in the Authorization header.
Include the following parameter:
Parameter
Action
payment_source.apple_pay.token
Set to the Base64 encoded Apple Pay token containing payment data.
Response: Contains the setup token in the id response parameter.
// Client-side helper function to create vault setup tokenasync function createVaultSetupToken(vaultData) { setMessage("Creating vault setup token"); const defaultHeaders = { "Content-Type": "application/json", }; try { const response = await fetch( "/your-server/api/paypal/vault/setup-token", { headers: { ...defaultHeaders, }, method: "POST", body: JSON.stringify(vaultData), }, ); const data = await response.json(); if (!response.ok) { throw new Error(data.message || "Failed to create setup token"); } return data; } catch (error) { throw new Error(error); }}
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 parameters:
Parameter
Action
payment_source.token.type
Set to SETUP_TOKEN to specify the token type.
payment_source.token.id
Set to the setup token ID from the previous step.
Response: Contains the payment token in the id response parameter, which is the reusable token for future transactions.
// Convert the setup token to a reusable payment tokenconst vaultPmtTokenData = { payment_source: { token: { type: "SETUP_TOKEN", id: vaultSetupToken.setupToken, // The setup token ID from the previous step }, },};setMessage("Processing vault PaymentToken for Apple Pay...");const vaultPaymentToken = await createVpmtToken(vaultPmtTokenData);setMessage( "✅Payment Token created successfully: " + vaultPaymentToken.setupToken, // This is the reusable token for future transactions);// Store the payment token ID for future use// This token can be used to process payments without requiring the customer to re-authenticateconst paymentTokenId = vaultPaymentToken.setupToken;// Client-side helper functionasync function createVpmtToken(vaultData) { setMessage("Creating vault payment token"); const defaultHeaders = { "Content-Type": "application/json", }; try { const response = await fetch( "/your-server/api/paypal/vault/payment-token", { headers: { ...defaultHeaders, }, method: "POST", body: JSON.stringify(vaultData), }, ); const data = await response.json(); if (!response.ok) { throw new Error(data.message || "Failed to create payment token"); } return data; } catch (error) { throw new Error(error); }}
Complete transaction
Notify Apple Pay that the payment was processed successfully.
In your app code, include the logic to handle cancellation when the customer closes the Apple Pay payment sheet.Use the onCancel() 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.
In your app code, include the logic to handle errors that occur during the authentication flow.Use the onError() 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.
function onError(data) { console.log("onError: ", data); setMessage(data);}
In your app code, include the logic to handle when the authentication flow finishes.Use the onComplete() 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.
function onComplete(data) { console.log("onComplete: ", data);}
In your app code, start the Apple Pay payment session after configuring all event handlers.Use the appleSdkApplePayPaymentSession.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
// Start the Apple Pay payment sessionappleSdkApplePayPaymentSession.begin();