> For the complete documentation index, see [llms.txt](https://docs.2checkout.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.2checkout.com/get-started-with-the-2checkout-api/get-started-with-the-2checkout-api/authentication-and-use-cases/2checkout-api-use-cases/payment-flow-with-apple-pay.md).

# Payment flow with Apple Pay

The following payment method is specific to Apple devices.

## Availability

Available for all 2Checkout merchants (2Sell, 2Subscribe, 2Monetize & 4Enterprise) using all or any of our ordering engines (hosted shopping cart, ConvertPlus, and InLine).

For more information on availability, see the main documentation page for Apple Pay [here](/payments/payments/payment-methods/apple-pay.md).

## Requirements

Shoppers can use any device that supports Apple Pay and is located in one of the selected [countries](https://support.apple.com/en-us/HT207957).&#x20;

For more information on requirements, see the main documentation page for Apple Pay [here](/payments/payments/payment-methods/apple-pay.md).

## Activation

For activation, you need to have Apple Pay enabled on your 2Checkout account. Contact the [Merchant Support](mailto:supportplus@2checkout.com) team to enable it. After 2Checkout sets up our domain, we will provide you with a domain verification file.

Host your domain verification file at the following path on our server: https\://\[DOMAIN\_NAME]/.well-known/apple-developer-merchantid-domain-association.

## Setting up Apple Pay

To set up Apple Pay, you need to build the frontend component and to initialize the session using the **startApplePaySession** method, providing the `validationUrl` to the payload. Once the token is received from the frontend component, it has to be sent to the **decryptApplePayData** endpoint in the 2Checkout API. This will return a data response from Apple Pay that needs to be used in the **placeOrder** call.

### Frontend component

To set up an Apple Pay session in the shopper’s browser, follow these steps:

1. Include the Apple Pay library.<br>

   ```html
   <script src="https://applepay.cdn-apple.com/jsapi/v1/apple-pay-sdk.js"></script>
   ```
2. Add the Apple Pay button.<br>

   ```html
   <div class="apple-pay-button apple-pay-button-black" onclick="onApplePayButtonClicked()"></div>
   <style>
          .apple-pay-button {
              display: inline-block;
              -webkit-appearance: -apple-pay-button;
              -apple-pay-button-type: buy; /* Use any supported button type. */
          }
          .apple-pay-button-black {
              -apple-pay-button-style: black;
          }
          .apple-pay-button-white {
              -apple-pay-button-style: white;
          }
          .apple-pay-button-white-with-line {
              -apple-pay-button-style: white-outline;
          }
   </style>
   ```
3. Set up the Apple Pay function and create a session instance.<br>

   ```javascript
   function onApplePayButtonClicked() {
          // Ensure browser supports Apple Pay
          if (!ApplePaySession) {
              return;
          }

          // Define ApplePayPaymentRequest
          /* Define the country code and currency being sent to the library, as well as
          the list of supported networks and the descriptor and amount of the transaction.*/
          const request = {
              "countryCode": "US",
              "currencyCode": "USD",
              "merchantCapabilities": [
                  "supports3DS"
              ],
              "supportedNetworks": [
                  "visa",
                  "masterCard",
                  "amex",
                  "discover"
              ],
              "total": {
                  "label": "Example Transaction",
                  "type": "final",
                  "amount": "0.01"
              }
          };

          // Create ApplePaySession
          const session = new ApplePaySession(3, request);

          session.onvalidatemerchant = async event => {
              // Call your own server to request a new merchant session (call 2checkout API /rest/6.0/payments/startapplepaysession)
              fetch("/startApplePay.php")
                  .then(res => res.json()) // Parse response as JSON.
                  .then(merchantSession => {
                      response = JSON.parse(merchantSession.ApplePaySessionData.response);
                      session.completeMerchantValidation(response);
                  })
                  .catch(err => {
                    console.error("Error fetching merchant session", err);
                  });
          };

          session.onpaymentmethodselected = event => {
              // Define ApplePayPaymentMethodUpdate based on the selected payment method.
              // No updates or errors are needed, pass an empty object.
              const update = {
                  newTotal: {
                      label: "Demo (Card is not charged)",
                      type: "final",
                      amount: "0.01"
                  }
              }
              session.completePaymentMethodSelection(update);
          };

          session.onshippingmethodselected = event => {
              // Define ApplePayShippingMethodUpdate based on the selected shipping method.
              // No updates or errors are needed, pass an empty object.
              const update = {
                  newTotal: {
                      label: "Demo (Card is not charged)",
                      type: "final",
                      amount: "0.01"
                  }
              }
              session.completeShippingMethodSelection(update);
          };

          session.onshippingcontactselected = event => {
              // Define ApplePayShippingContactUpdate based on the selected shipping contact.
              const update = {
                  newTotal: {
                      label: "Demo (Card is not charged)",
                      type: "final",
                      amount: "0.01"
                  }
              }
              session.completeShippingContactSelection(update);
          };

          session.onpaymentauthorized = event => {
              // Call your own server to request the Apply Pay token decryption and pass the decoded token to the place order call (call 2checkout APIs /rest/6.0/payments/decryptapplepaydata and /rest/6.0/orders/)
              // Define ApplePayPaymentAuthorizationResult based on the place order response
              payload = {
                  token: event.payment.token,
              };
              fetch("/finishApplePay.php", {
                  method: "POST",
                  headers: {"Content-Type": "application/json"},
                  body: JSON.stringify(payload),
              }).then((res) => res.json())
                  .then((res) => {
                      if (res.Status.includes('AUTHRECEIVED', 'COMPLETE')) {
                        session.completePayment(session.STATUS_SUCCESS);
                      }
                      console.log("INFO - RECEIVED ECOM RESPONSE: ", res.Status);
                      })
                      .catch((err) => console.log(err));
          };

          session.oncancel = event => {
              // Payment cancelled by WebKit
          };
          session.begin();
   }
   ```

### Backend component

Create endpoints on your server to interact with the 2Checkout API for Apple Pay. Follow these steps:

{% stepper %}
{% step %}

#### Initiate an Apple Pay session

Create an endpoint on your server to call to initiate an Apple Pay session. In order for a valid Apple Pay session to be created, an API call to the 2Checkout API needs to be sent, with the `validationURL` set to the **ApplePay** payment service.

<table><thead><tr><th width="115.0001220703125">Protocol</th><th>Endpoint</th></tr></thead><tbody><tr><td>REST</td><td>POST <a href="https://api.2checkout.com/rest/6.0/payments/startapplepaysession">https://api.2checkout.com/rest/6.0/payments/startapplepaysession</a></td></tr><tr><td>JSON-RPC</td><td><strong>startApplePaySession</strong></td></tr><tr><td>SOAP</td><td><strong>startApplePaySession</strong></td></tr></tbody></table>

startApplePaySession payload

```javascript
{
      "validationURL":"https://apple-pay-gateway.apple.com/paymentservices/startSession"
}
```

{% endstep %}

{% step %}

#### Decrypt the Apple Pay token

Once the token is received from the frontend component, it has to be sent to the **decryptApplePayData** endpoint in the 2Checkout API. This will return a data response from Apple Pay that needs to be used in the **placeOrder** call.

<table><thead><tr><th width="110.2000732421875">Protocol</th><th>Endpoint</th></tr></thead><tbody><tr><td>REST</td><td>POST <a href="https://api.2checkout.com/rest/6.0/payments/decryptapplepaydata">api.2checkout.com/rest/6.0/payments/decryptapplepaydata</a></td></tr><tr><td>JSON-RPC</td><td><strong>decryptApplePayData</strong></td></tr><tr><td>SOAP</td><td><strong>decryptApplePayData</strong></td></tr></tbody></table>

**decryptApplePayData payload**

**BODY**: (**ApplePayData** property value should be the `event.payment.token` from the `onpaymentauthorized` event)

```javascript
{
      "ApplePayData":"543a07601ed9f8b8ee226e9630a24e2a91da8fdb08e6786fa02bf628f395bb91"
}
```

{% endstep %}

{% step %}

#### Place the order

Once the Apple Pay data is received from 2Checkout, this needs to be used in the Payment Method object of the Payment Details object in the API call to place an order.

<table><thead><tr><th width="116.2000732421875">Protocol</th><th>Endpoint</th></tr></thead><tbody><tr><td>REST</td><td>POST <a href="https://api.2checkout.com/rest/6.0/orders">https://api.2checkout.com/rest/6.0/orders</a></td></tr><tr><td>JSON-RPC</td><td><strong>placeOrder</strong></td></tr><tr><td>SOAP</td><td><strong>placeOrder</strong></td></tr></tbody></table>

Example placeOrder payload:

```javascript
{
      "Items":[
         {
            "Code":"5DCB30C6B0",
            "Quantity":1
         }
      ],
      "BillingDetails":{
         "Email":"example@email.com",
         "FirstName":"Customer First Name",
         "LastName":"Customer Last Name",
         "CountryCode":"US",
         "State":"California",
         "City":"San Francisco",
         "Address1":"Example Street",
         "Zip":"90210"
      },
      "PaymentDetails":{
         "Type":"APPLE_PAY",
         "Currency":"USD",
         "CustomerIP":"10.10.10.10",
         "PaymentMethod":{
            "ApplePayToken":"ApplePayDataToken"
         }
      },
      "Language":"en",
      "Country":"US",
      "CustomerIP":"10.10.10.10",
      "Source":"Website",
      "ExternalCustomerReference":"externalCustomerId",
      "Currency":"USD",
      "MachineId":"123456789"
}
```

{% endstep %}
{% endstepper %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.2checkout.com/get-started-with-the-2checkout-api/get-started-with-the-2checkout-api/authentication-and-use-cases/2checkout-api-use-cases/payment-flow-with-apple-pay.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
