Apple Pay
Last updated: Aug 4th, 9:04pm
Overview
This guide provides step-by-step instructions for integrating Apple Pay with PayPal's v6 Web SDK. The implementation enables merchants to accept Apple Pay payments and supports one-time payments with proper security requirements.
PayPal Developer Account
Create a PayPal developer account and configure your application for Apple Pay. You'll need to create a new application or configure an existing one, enable the Apple Pay feature in your app settings, and obtain your Client ID and Secret for server configuration.
Apple Developer Program
Apple Developer Program membership is required for processing live payments. You'll need to create a sandbox tester account for testing and add test credit cards to the Apple Pay wallet for development.
HTTPS Environment
Apple Pay only works over secure HTTPS connections. For local development, you can use ngrok to create a secure tunnel to your development server.
HTML Structure Setup
Create a basic HTML page with the Apple Pay button container and required SDK scripts. The structure includes containers for the payment button and loads both Apple Pay and PayPal SDKs.
1<!doctype html>2<html lang="en">3 <head>4 <meta charset="UTF-8" />5 <title>Apple Pay Integration</title>6 <meta name="viewport" content="width=device-width, initial-scale=1" />7 </head>8 <body>9 <h1>Apple Pay Payment</h1>10 <div id="apple-pay-button-container"></div>1112 <script src="https://applepay.cdn-apple.com/jsapi/v1/apple-pay-sdk.js"></script>13 <script14 async15 src="https://www.sandbox.paypal.com/web-sdk/v6/core"16 onload="onPayPalWebSdkLoaded()"17 ></script>18 <script src="app.js"></script>19 </body>20</html>
PayPal SDK Initialization
Initialize the PayPal SDK with Apple Pay components to enable payment processing. This step creates the SDK instance with the required Apple Pay components and authentication.
1async function onPayPalWebSdkLoaded() {2 try {3 const clientToken = await getBrowserSafeClientToken();4 const sdkInstance = await window.paypal.createInstance({5 clientToken,6 components: ["applepay-payments"],7 pageType: "checkout",8 });910 setupApplePayButton(sdkInstance);11 } catch (error) {12 console.error("SDK initialization failed:", error);13 }14}
Payment Request Configuration
Define the payment details and create the Apple Pay session with required billing and shipping information. This configuration specifies the payment amount, currency, merchant capabilities, and required contact fields.
1async function handleApplePayClick() {2 const paymentRequest = {3 countryCode: "US",4 currencyCode: "USD",5 merchantCapabilities,6 supportedNetworks,7 requiredBillingContactFields: ["name", "phone", "email", "postalAddress"],8 requiredShippingContactFields: [],9 total: {10 label: "Your Store Name",11 amount: "100.00",12 type: "final",13 },14 };1516 const applePaySession = new ApplePaySession(4, paymentRequest);17 setupApplePayEventHandlers(applePaySession, paypalSdkApplePayPaymentSession);18 applePaySession.begin();19}
Merchant Validation Handler
Handle the merchant validation process required by Apple Pay to verify your merchant credentials and domain registration.
1applePaySession.onvalidatemerchant = (event) => {2 paypalSession.validateMerchant({3 validationUrl: event.validationURL,4 }).then((payload) => {5 applePaySession.completeMerchantValidation(payload.merchantSession);6 }).catch((err) => {7 console.error("Merchant validation failed:", err);8 applePaySession.abort();9 });10};
Payment Method Selection Handler
Handle payment method selection events to update the payment total if needed based on the selected payment method.
1applePaySession.onpaymentmethodselected = () => {2 applePaySession.completePaymentMethodSelection({3 newTotal: paymentRequest.total,4 });5};
Payment Cancellation Handler
Handle cases where the user cancels the Apple Pay payment process to provide appropriate feedback and cleanup.
1applePaySession.oncancel = () => {2 console.log("Apple Pay cancelled");3 // Handle cancellation logic here4 // Such as returning to checkout or showing a message5};
Client Token API Endpoint
Implement a server endpoint to provide browser-safe client tokens for authentication without exposing sensitive credentials to the frontend.
1async function getBrowserSafeClientToken() {2 const response = await fetch("/paypal-api/auth/browser-safe-client-token", {3 method: "GET",4 headers: { "Content-Type": "application/json" },5 });6 const { accessToken } = await response.json();7 return accessToken;8}
Create Order API Endpoint
Create a server endpoint to generate PayPal orders with the payment details for Apple Pay processing.
1async function createOrder() {2 const response = await fetch("/paypal-api/checkout/orders/create-with-sample-data", {3 method: "POST",4 headers: { "Content-Type": "application/json" },5 });6 const { id } = await response.json();7 return { orderId: id };8}
Capture Order API Endpoint
Implement an endpoint to capture approved Apple Pay orders and finalize the payment transaction.
1async function captureOrder({ orderId }) {2 const response = await fetch(`/paypal-api/checkout/orders/${orderId}/capture`, {3 method: "POST",4 headers: { "Content-Type": "application/json" },5 });6 return await response.json();7}
Local Development Setup - ngrok Installation
Install and configure ngrok to create secure HTTPS tunnels for local development, which is required for Apple Pay testing.
1npm install -g ngrok2ngrok config add-authtoken YOUR_AUTHTOKEN3ngrok http 3000
Local Development Setup - Vite Configuration
Configure your Vite development server to work with ngrok domains and proxy PayPal API requests properly.
1// vite.config.js2export default defineConfig({3 server: {4 allowedHosts: ["your-ngrok-domain.ngrok-free.app"],5 proxy: {6 "/paypal-api": {7 target: "http://localhost:8080",8 changeOrigin: true,9 secure: false,10 },11 },12 },13});
Domain Registration Process
Register your ngrok domain with PayPal's Apple Pay settings and download the required domain association file to verify domain ownership.
Testing Requirements
Use Safari browser on macOS or iOS for testing, sign into a sandbox iCloud account, add test credit cards to the Apple Pay wallet, and test the complete payment flow end-to-end.
Common Issue - Merchant Validation Fails
When merchant validation fails, check the domain association file placement, verify PayPal domain registration, and confirm the ngrok domain is properly configured in your development setup.
Additional Resources
Follow this link for a full example on our public examples repo on Github.