Apple Pay

SDK

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>
    11
    12 <script src="https://applepay.cdn-apple.com/jsapi/v1/apple-pay-sdk.js"></script>
    13 <script
    14 async
    15 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 });
      9
      10 setupApplePayButton(sdkInstance);
      11 } catch (error) {
      12 console.error("SDK initialization failed:", error);
      13 }
      14}

      Apple Pay Button Setup

      Configure the Apple Pay button and create the payment session with merchant capabilities. This step creates the Apple Pay button element and configures it with the appropriate styling and click handling.

        1async function setupApplePayButton(sdkInstance) {
        2 const paypalSdkApplePayPaymentSession =
        3 await sdkInstance.createApplePayOneTimePaymentSession();
        4
        5 const { merchantCapabilities, supportedNetworks } =
        6 await paypalSdkApplePayPaymentSession.config();
        7
        8 document.getElementById("apple-pay-button-container").innerHTML =
        9 '<apple-pay-button id="apple-pay-button" buttonstyle="black" type="buy" locale="en">';
        10
        11 document.getElementById("apple-pay-button")
        12 .addEventListener("click", handleApplePayClick);
        13}

        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 };
          15
          16 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 Authorization Handler

              Process the payment authorization by creating a PayPal order, confirming it with the Apple Pay token, and capturing the payment.

                1applePaySession.onpaymentauthorized = async (event) => {
                2 try {
                3 const order = await createOrder();
                4
                5 await paypalSession.confirmOrder({
                6 orderId: order.orderId,
                7 token: event.payment.token,
                8 billingContact: event.payment.billingContact,
                9 shippingContact: event.payment.shippingContact,
                10 });
                11
                12 const result = await captureOrder({ orderId: order.orderId });
                13
                14 applePaySession.completePayment({
                15 status: window.ApplePaySession.STATUS_SUCCESS,
                16 });
                17
                18 console.log("Payment successful:", result);
                19 } catch (error) {
                20 console.error("Payment failed:", error);
                21 applePaySession.completePayment({
                22 status: window.ApplePaySession.STATUS_FAILURE,
                23 });
                24 }
                25};

                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 here
                  4 // Such as returning to checkout or showing a message
                  5};

                  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 ngrok
                          2ngrok config add-authtoken YOUR_AUTHTOKEN
                          3ngrok 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.js
                            2export 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 - Button Not Appearing

                            If the Apple Pay button doesn't appear, check Safari Apple Pay settings, verify domain registration with PayPal, and ensure you're using an HTTPS connection.

                            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.

                            Common Issue - Payment Authorization Fails

                            If payment authorization fails, ensure you're using a sandbox iCloud account, check that test credit cards are properly set up in Apple Pay, and verify all server endpoints are responding correctly.

                            Additional Resources

                            Follow this link for a full example on our public examples repo on Github.