Apple Pay: Difference between revisions

From Barion Documentation
Jump to navigation Jump to search
No edit summary
 
(19 intermediate revisions by 4 users not shown)
Line 1: Line 1:
{{PageTitle|title=Apple Pay integration}}
{{PageTitle|title=Apple Pay integration}}
{{TableOfContents}}
{{TableOfContents}}
Apple Pay™ is a payment option for the customer. Apple securely stores the customer's card information and hands it over to the merchant for processing.
{{NotificationBox|title=NOTE|text=We currently only support Apple Pay for the web, native iPhone app support is coming soon.|color=#1993c7}}


== Implementation modes ==
Learn to offer the Apple Pay button as a payment option in your Barion shop when the customer uses a supported browser (typically Safari) on an eligible device.
Apple Pay can be emebedded two ways into your payment flow. In the first case, it will be displayed on Barion Smart Gateway ("Hosted Gateway"), which needs no further configuration and/or development on your side. The second option is to display the Apple Pay button on your site ("integrated mode"), however this needs configuration and development on your side. This page will discuss the latter.
* Apple Pay Hosted Gateway demo: https://test.demomerchant.shop/en/DemoClub/Pay (click the Pay button)
* Apple Pay integrated mode demo: https://test.demomerchant.shop/en/DemoGame/Pay


== Prerequisits ==
<blockquote>This article is about directly integrating the Apple Pay button in your webshop.
{{NotificationBox|title=IMPORTANT|text=To integrate this feature you have to develop the integration yourself! You need to understand Javascript code and it is also required to modify your webshop's server code!|color=#FF7A3D}}
* you must have a Barion wallet
* the beforementioned Barion wallet must have and approved shop
* for every currency you plan to conduct payments in you have to make sure there is an account created in your Barion wallet. This means that if you plan to have USD payments then there should be an USD account created in your wallet.
* all the example codes assume the availability of jQuery


If you simply want to display Apple Pay as a payment option in the Barion Smart Gateway, no further configuration is necessary; pass "ApplePay" in [[FundingSources|the FundingSources array]] when preparing a payment.
</blockquote>
The appeal of Apple Pay is that it requires only two actions from the customer: selecting the ‘Pay with Apple Pay’ button, and confirming the payment with Touch ID or Face ID.
Another advantage to your Barion shop’s payment workflow is that customers aren’t navigated away from your checkout page when using Apple Pay.
<span id="prerequisites"></span>
== Prerequisites ==
<ul>
<li>access to and being able to modify both your webshop’s front-end and back-end code</li>
<li>your webshop using HTTPS (having a TLS 1.2 or higher certificate installed) for all its pages that include the Apple Pay button</li>
<li>Barion Wallet with an approved Barion shop
<ul>
<li>the Barion shop complies with [https://developer.apple.com/apple-pay/acceptable-use-guidelines-for-websites/ Apple’s acceptable use guidelines], including not selling prohibited products or services</li></ul>
<blockquote><p>Note that Apple’s policies regarding acceptable products and services are more limiting than those of Barion.</p>
<p>It may happen that even though Barion approves your Barion shop to sell a certain item, you will not be allowed to display the Apple Pay button as a payment option for customers to pay for that item.</p></blockquote></li>
<li>an account in the Barion Wallet for each of the currencies that you’d like to accept using Apple Pay</li></ul>
== Limitations ==
== Limitations ==
=== Technical ===
Using Apple Pay as a token payment is currently not possible.


=== Shopper ===
* you can’t yet tokenize your customer’s card details when using the Apple Pay button, so [[Token payment 3D Secure|recurring payments]] aren’t available
Apple Pay will only be visible to shoppers fulfilling the following criteria:
* Barion currently only supports Apple Pay button on the web, and not on native iOS apps
* Use an [https://support.apple.com/en-us/HT208531 Apple Pay-compatible device]
* regardless of the integration detailed here, the Apple Pay button will only be displayed to your customers if they comply with Apple’s requirements:
* Use [https://support.apple.com/en-us/HT208531#notes Safari]
** they’re using [https://support.apple.com/en-us/102896 an Apple Pay-compatible device]
* Located in a country or region where [https://support.apple.com/en-us/HT207957 Apple Pay is available]
** they’re viewing your webshop using a browser that supports Apple Pay
* Have an [https://support.apple.com/guide/iphone/set-up-apple-pay-iph9b7f53382/ios existing card added to their Apple Pay wallet]
** they’re located [https://support.apple.com/en-us/102775 in a country or region where Apple Pay is available]
== Steps ==
=== Setting up your Apple prerequisites ===
 
<blockquote>When using Barion’s Apple Pay API endpoints, Barion gives you [https://developer.apple.com/support/app-account/ an Apple developer account], and registers [https://developer.apple.com/documentation/applepaywebmerchantregistrationapi/registering_with_apple_pay_and_applying_to_use_the_api a Merchant ID], [https://help.apple.com/developer-account/#/devb2e62b839?sub=devf31990e3f Payment Processing Certificate], and [https://help.apple.com/developer-account/#/dev1731126fb Merchant Identity Certificate] for you as a subsidiary of Barion’s Apple Pay credentials.
</blockquote>
Verify and register your webshop’s domain name or names:
 
# Log in to your Barion Wallet, and go to your Barion shop’s Shops&gt;Actions&gt;Settings screen.
# Click the “Manage Apple Pay settings”, and then “Download domain verification file” to save the verification file for your shop’s domain.
# Save the domain verification file that you downloaded in the content root of all the sites that your specified domains use, making sure of the following:
#* the file should send the <code><mimeMap fileExtension="." mimeType="application/json" /></code> MIME data;
#* the file must be accessible externally, and not be password-protected, or behind a proxy or redirect;
#* the sites must be served over HTTPS.
# Enter all the domains that you’d like to use Apple Pay on (into whose root you’ve downloaded the domain verification file) in the text box provided, then click “Save”.
=== Configuring and displaying the Apple Pay button ===


=== Shop ===
<ol style="list-style-type: decimal;">
* Your shop must not sell [https://developer.apple.com/apple-pay/acceptable-use-guidelines-for-websites/ prohibited items by Apple]
<li><p>Load the button script into your checkout page by adding the following script tag inside the page head:</p>
* Your site must use https!
<syntaxhighlight lang="html"><script src="https://applepay.cdn-apple.com/jsapi/v1.1.0/apple-pay-sdk.js"></script></syntaxhighlight></li></ol>


==Payment Process==
<blockquote>This script makes an ApplePaySession available to your site front-end, among other things.
# The customer clicks the Apple Pay button.
</blockquote>
# Apple Pay session has to be created using the library provided by Apple as discussed [[#Create an Apple Pay session|here]].
<ol start="2" style="list-style-type: decimal;">
# The JS code receives a session data
<li><p>Add the <code>apple-pay-button</code> element (for example, <code>&lt;div id="apple-pay-button"&gt;&lt;/div&gt;</code>) to your checkout page, [https://developer.apple.com/documentation/apple_pay_on_the_web/displaying_apple_pay_buttons_using_css and use the CSS included in the button script to display it].</p></li>
# The JS code sends this information to the server side of the merchant
<li><p>Start a new ApplePaySession when the checkout page loads:</p>
# The server side gathers the information necessary to call the [[ApplePay-ValidateSession|/v2/ApplePay/ValidateSession]] endpoint.
<syntaxhighlight lang="javascript">  const request = {
# Apple Pay screen is displayed, where the customer can select the card, shipping address and contact details.
    countryCode: 'US',
# The JS code receives the encrypted card information.
    currencyCode: 'USD',
# The JS code sends the encrypted information to the sever side of the merchant
    supportedNetworks: ['visa', 'masterCard', 'amex', 'discover'],
# The server side gathers the information needed to call the [[ApplePay-StartPaymentWithAppleToken|/v2/ApplePay/StartPaymentWithAppleToken]] endpoint.
    merchantCapabilities: ['supports3DS'],
# The Barion API handles the request, decrypts the packages and charges the card. The result of the payment is sent back to the caller.
    total: { label: 'Your Merchant Name', amount: '10.00' }
# The merchant's server communicates the result to the client side and the webshop renders the result of the payment.
  }
  const applePlaySession = new ApplePaySession(3, request);


==  Configuration ==
  // add an isSessionCanceled boolean to easily be able to cancel the session if your user abandons the in-progress payment process
=== Domain verification file===
  var isSessionCanceled = false;</syntaxhighlight></li>
First head over to secure.barion.com, and under [https://secure.barion.com/Shop Manage My Shops] page select the appropriate one, and from the dropdown, click on settings. At the bottom click the Manage Apple Pay settings blue button under the Apple Pay Settings section. On the next page  Click on the Download domain verification file button, which will download a domain association file. You should place this file at the content root of all of your sites, you're about to use apple pay in integrated mode.
  <li>
The file must:
    <p>Make sure to only display the Apple Pay button to users who can use it, by have your webshop’s checkout pages do
* mimemap for extension "." should be set to "application/json", for eg.:
      the following when they load:</p>
*: <syntaxhighlight lang="xml"><mimeMap fileExtension="." mimeType="application/json" /></syntaxhighlight>
    <p>Call [https://developer.apple.com/documentation/apple_pay_on_the_web/applepaysession/1778027-canmakepayments
* be externally accessible.
        the <code>applePaySession.canMakePayments</code> method], passing it your Barion shop’s public ID.</p>
* not be password protected.
* the file cannot be behind a proxy or redirect.
* your site must use https.


===Configure Domains===
    <p>If Apple can verify your Barion shop as a registered Apple Pay provider, the method checks the following:</p>
On the exact same page you've downloaded the domain association file, enter all the domains (one in each line, without https:// or https://) you're intending to use Apple Pay.
    <ul>
      <li>that your customer's device is capable of using Apple Pay</li>
      <li>that Apple Pay is enabled on your customer's device, and</li>
      <li>that the customer has the details of at least one active and web payment-eligible bank card stored in their Apple
        Pay wallet.</li>
    </ul>
  </li>
  <li>Handle [https://developer.apple.com/documentation/apple_pay_on_the_web/paymentcredentialstatus the
        <code>PaymentCredentialStatus</code> object] that the method returns to make a decision about displaying the
        Apple Pay button.
  </li>
</ol>
=== Handling payments ===


== Development ==
Set up your webshop to perform these steps each time a user selects the Apple Pay button.
=== Include the Apple Pay SDK===
Include the following code snippet in the header of your checkout page:
<code><script src="https://applepay.cdn-apple.com/jsapi/v1/apple-pay-sdk.js"></script></code>
===Display the Apple Pay button===
Add the Apple Pay button to your checkout page as discussed [https://developer.apple.com/documentation/apple_pay_on_the_web/displaying_apple_pay_buttons_using_javascript here]
===Create an Apple Pay session===
When the user taps the Apple Pay button, provide a payment request and create the [https://developer.apple.com/documentation/apple_pay_on_the_web/applepaysession session] as discussed [https://developer.apple.com/documentation/apple_pay_on_the_web/apple_pay_js_api/creating_an_apple_pay_session here]


===Subscribe to the <code>[https://developer.apple.com/documentation/apple_pay_on_the_web/applepaysession/1778021-onvalidatemerchant onvalidatemerchant]</code> event===
<ol style="list-style-type: decimal;">
Call your backend, which will in turn call the Barion Api [[ApplePay-ValidateSession|ValidateSession]] endpoint in the event handler with the provided url as the payload:
<li><p>Set up an event handler for [https://developer.apple.com/documentation/apple_pay_on_the_web/applepaysession/1778021-onvalidatemerchant <code>ApplePaySession.onvalidatemerchant</code>] that notifies your site's back-end, and passes it the event response.</p><blockquote>Don't call the ValidateSession Barion API endpoint directly from the browser, as this could expose your Barion shop's POSKey.</blockquote></li>
<syntaxhighlight lang="javascript">
<li><p>Have your site's back-end call [[ApplePay-ValidateSession|the ValidateSession Barion API endpoint]], passing it the <code>onvalidatemerchant</code> event’s <code>ValidationUrl</code> attribute.</p>
appleSession.onvalidatemerchant = function (event) {
<syntaxhighlight lang="javascript">async function validateApplePaySession(POSKey, SessionRequestUrl, ShopUrl) {
// TODO: disable Apple Pay button
  const url = "https://api.test.barion.com/v2/ApplePay/ValidateSession";
const data = {
  const data = {
SessionValidationUrl: event.validationURL
    POSKey,
};
    SessionRequestUrl,
    ShopUrl,
  };
 
  try {
    const response = await fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(data),
    });
 
    if (!response.ok) {
      throw new Error(`Error: ${response.status} ${response.statusText}`);
    }


$.ajax({
    const result = await response.json();
method: "POST",
    return result;
url: "https://yourserver.com/ValidateApplePaySession",
  } catch (error) {
data: data,
    // handle the error according to your business logic
success: function (response, status, xhr) {
  }
const merchantSession = JSON.parse(response.ApplePaySessionResponse);
}
if(!isSessionCanceled) {
appleSession.completeMerchantValidation(merchantSession);
}
},
error: function (xhr, status, error) {
// failure callback
// TODO: enable Apple Pay button
}
});
};
</syntaxhighlight>


===Subscribe to the <code>[https://developer.apple.com/documentation/apple_pay_on_the_web/applepaysession/1778020-onpaymentauthorized onpaymentauthorized ]</code> event===
applePaySession.onvalidatemerchant = async function (event) {
Call your backend, which will in turn call the Barion Api [[ApplePay-StartPaymentWithAppleToken|StartPaymentWithAppleToken]] endpoint in the event handler with the provided payment payload:
  const validationResult = await validateApplePaySession(POSKey, event.validationURL, ShopUrl);
 
  applePaySession.completeMerchantValidation(validationResult.ApplePaySessionResponse);
};</syntaxhighlight>
<blockquote><p>This event is triggered when the Apple Pay payment sheet is displayed to the customer.</p></blockquote></li>
<li><p>Set up an event handler for [https://developer.apple.com/documentation/apple_pay_on_the_web/applepaysession/1778020-onpaymentauthorized <code>ApplePaySession.onpaymentauthorized</code>]</p><blockquote>Don't call the StartPaymentWithAppleToken Barion API endpoint directly from the browser, as this could expose your Barion shop's POSKey.</blockquote></li>
<li>that calls the [[ApplePay-StartPaymentWithAppleToken|StartPaymentWithAppleToken Barion API endpoint]], passing it the event’s following attributes:</p>
<ul>
<li>token</li>
<li>shippingContact</li>
<li>billingContact</li></ul>
<blockquote>Note that <code>StartPaymentWithAppleToken</code> is actually a specialized version of [[Payment-Start-v2|the payment/start API endpoint]], and so will also require all the usual parameters that you’d pass to that endpoint.
</blockquote>
<syntaxhighlight lang="javascript">
<syntaxhighlight lang="javascript">
appleSession.onpaymentauthorized = function (event) {
async function startApplePayPayment(
let cart = {
  POSKey,
Payload = event.payment
  ShippingContact,
PaymentType = "Immediate",
  BillingContact,
Mode = "",
  Token,
};
  /** include other required and optional Payment/Start params */
  PaymentStartProperties
) {
  const url =
    "https://api.test.barion.com/v2/ApplePay/StartPaymentWithAppleToken";
  const data = {
    POSKey,
    ShippingContact,
    BillingContact,
    Token,
    ...PaymentStartProperties,
  };


$.ajax({
  try {
method: "POST",
    const response = await fetch(url, {
url: "https://yourserver.com/StartApplePayment",
      method: "POST",
data: cart,
      headers: {
success: function (response, status, xhr) {
        "Content-Type": "application/json",
if (response.IsSuccessful && response.PaymentStatus === 40) {
      },
appleSession.completePayment(appleSession.STATUS_SUCCESS);
      body: JSON.stringify(data),
} else {
    });
appleSession.completePayment(appleSession.STATUS_FAILURE);
}
},
error: function (xhr, status, error) {
appleSession.completePayment(appleSession.STATUS_FAILURE);
}
});
};
</syntaxhighlight>


===Subscribe to the <code>[https://developer.apple.com/documentation/apple_pay_on_the_web/applepaysession/1778029-oncancel oncancel]</code> event===
    if (!response.ok) {
This method gets called every time the Apple Pay UI is dismissed. You should implement your needs accordingly (for eg. re-enable pay button).
      throw new Error(`Error: ${response.status} ${response.statusText}`);
    }


<syntaxhighlight lang="javascript">
    const result = await response.json();
appleSession.onpaymentauthorized = function (event) {
    return result;
          // TODO: enable Apple Pay button
  } catch (error) {
           
    // handle the error according to your business logic
            isSessionCanceled = true;
  }
};
}
</syntaxhighlight>


===Call <code>ApplePaySession.begin</code> method===
const PaymentStartProperties = {
Call the [https://developer.apple.com/documentation/apple_pay_on_the_web/applepaysession/1778001-begin begin] method, and the merchant validation process begins. So your final client side code will look like this:
  PaymentType: "Immediate",
<syntaxhighlight lang="javascript">
var request = {
  countryCode: 'HU',
  currencyCode: 'HUF',
  supportedNetworks: ['visa', 'masterCard', 'amex', 'discover'],
  merchantCapabilities: ['supports3DS'],
  total: { label: 'Your Merchant Name', amount: '1000.00' },
};
};
var isSessionCanceled = false;


var appleSession = new ApplePaySession(3, request);
applePaySession.onpaymentauthorized = function (event) {
appleSession.onvalidatemerchant = function (event) {...}
  startApplePayPayment(
appleSession.onpaymentauthorized = function (event) {...}
    POSKey,
appleSession.begin();
    event.paymentInfo.shippingContent,
    event.paymentInfo.billingContact,
    event.paymentInfo.Token,
    PaymentStartProperties
  );
};
</syntaxhighlight>
</syntaxhighlight>


== API reference ==
<blockquote>This event is triggered when the customer has authorized the Apple Pay payment using their Touch ID or Face ID.</blockquote>
* Barion
</li>
** [[ApplePay-ValidateSession|/v2/ApplePay/ValidateSession]]
<li><p>Set up an event handler for <code>oncancel</code> to implement your business logic for when the user abandons the Apple Pay payment.</p>
** [[ApplePay-StartPaymentWithAppleToken|/v2/ApplePay/StartPaymentWithAppleToken]]
<p>Make sure that your event handler indicates that the session is canceled so the ApplePaySession’s <code>completePayment</code> method doesn’t get executed.</p>
* Apple
<syntaxhighlight lang="javascript">  applePaySession.oncancel = function (event) {
** [https://developer.apple.com/documentation/apple_pay_on_the_web/applepaysession ApplePaySession interface]
    // your oncancel business logic
 
    isSessionCanceled = true;
  };</syntaxhighlight></li>
<li><p>Call [https://developer.apple.com/documentation/apple_pay_on_the_web/applepaysession/1778001-begin ApplePaySession.begin] to kick off the payment process.</p>
<syntaxhighlight lang="javascript">  applePaySession.begin();</syntaxhighlight>
<blockquote>This starts the merchant validation process that results in <code>ApplePaySession.onvalidatemerchant</code> being triggered.</blockquote></li></ol>
 
=== Testing your implementation ===
 
If you’re located in one of the countries or regions where the Apple Pay sandbox environment is available, [https://developer.apple.com/apple-pay/sandbox-testing/ use Apple’s Sandbox testing to try out your integration].
== Related links ==
 
[[ApplePay-ValidateSession|ValidateSession API endpoint]]
 
[[ApplePay-StartPaymentWithAppleToken|StartPaymentWithAppleToken API endpoint]]

Latest revision as of 11:11, 12 September 2024

Apple Pay integration

Learn to offer the Apple Pay button as a payment option in your Barion shop when the customer uses a supported browser (typically Safari) on an eligible device.

This article is about directly integrating the Apple Pay button in your webshop.

If you simply want to display Apple Pay as a payment option in the Barion Smart Gateway, no further configuration is necessary; pass "ApplePay" in the FundingSources array when preparing a payment.

The appeal of Apple Pay is that it requires only two actions from the customer: selecting the ‘Pay with Apple Pay’ button, and confirming the payment with Touch ID or Face ID.

Another advantage to your Barion shop’s payment workflow is that customers aren’t navigated away from your checkout page when using Apple Pay.

Prerequisites

  • access to and being able to modify both your webshop’s front-end and back-end code
  • your webshop using HTTPS (having a TLS 1.2 or higher certificate installed) for all its pages that include the Apple Pay button
  • Barion Wallet with an approved Barion shop

    Note that Apple’s policies regarding acceptable products and services are more limiting than those of Barion.

    It may happen that even though Barion approves your Barion shop to sell a certain item, you will not be allowed to display the Apple Pay button as a payment option for customers to pay for that item.

  • an account in the Barion Wallet for each of the currencies that you’d like to accept using Apple Pay

Limitations

  • you can’t yet tokenize your customer’s card details when using the Apple Pay button, so recurring payments aren’t available
  • Barion currently only supports Apple Pay button on the web, and not on native iOS apps
  • regardless of the integration detailed here, the Apple Pay button will only be displayed to your customers if they comply with Apple’s requirements:

Steps

Setting up your Apple prerequisites

When using Barion’s Apple Pay API endpoints, Barion gives you an Apple developer account, and registers a Merchant ID, Payment Processing Certificate, and Merchant Identity Certificate for you as a subsidiary of Barion’s Apple Pay credentials.

Verify and register your webshop’s domain name or names:

  1. Log in to your Barion Wallet, and go to your Barion shop’s Shops>Actions>Settings screen.
  2. Click the “Manage Apple Pay settings”, and then “Download domain verification file” to save the verification file for your shop’s domain.
  3. Save the domain verification file that you downloaded in the content root of all the sites that your specified domains use, making sure of the following:
    • the file should send the <mimeMap fileExtension="." mimeType="application/json" /> MIME data;
    • the file must be accessible externally, and not be password-protected, or behind a proxy or redirect;
    • the sites must be served over HTTPS.
  4. Enter all the domains that you’d like to use Apple Pay on (into whose root you’ve downloaded the domain verification file) in the text box provided, then click “Save”.

Configuring and displaying the Apple Pay button

  1. Load the button script into your checkout page by adding the following script tag inside the page head:

    <script src="https://applepay.cdn-apple.com/jsapi/v1.1.0/apple-pay-sdk.js"></script>

This script makes an ApplePaySession available to your site front-end, among other things.

  1. Add the apple-pay-button element (for example, <div id="apple-pay-button"></div>) to your checkout page, and use the CSS included in the button script to display it.

  2. Start a new ApplePaySession when the checkout page loads:

      const request = {
        countryCode: 'US',
        currencyCode: 'USD',
        supportedNetworks: ['visa', 'masterCard', 'amex', 'discover'],
        merchantCapabilities: ['supports3DS'],
        total: { label: 'Your Merchant Name', amount: '10.00' }
      }
      const applePlaySession = new ApplePaySession(3, request);
    
      // add an isSessionCanceled boolean to easily be able to cancel the session if your user abandons the in-progress payment process
      var isSessionCanceled = false;
  3. Make sure to only display the Apple Pay button to users who can use it, by have your webshop’s checkout pages do the following when they load:

    Call [https://developer.apple.com/documentation/apple_pay_on_the_web/applepaysession/1778027-canmakepayments the applePaySession.canMakePayments method], passing it your Barion shop’s public ID.

    If Apple can verify your Barion shop as a registered Apple Pay provider, the method checks the following:

    • that your customer's device is capable of using Apple Pay
    • that Apple Pay is enabled on your customer's device, and
    • that the customer has the details of at least one active and web payment-eligible bank card stored in their Apple Pay wallet.
  4. Handle [https://developer.apple.com/documentation/apple_pay_on_the_web/paymentcredentialstatus the PaymentCredentialStatus object] that the method returns to make a decision about displaying the Apple Pay button.

Handling payments

Set up your webshop to perform these steps each time a user selects the Apple Pay button.

  1. Set up an event handler for ApplePaySession.onvalidatemerchant that notifies your site's back-end, and passes it the event response.

    Don't call the ValidateSession Barion API endpoint directly from the browser, as this could expose your Barion shop's POSKey.

  2. Have your site's back-end call the ValidateSession Barion API endpoint, passing it the onvalidatemerchant event’s ValidationUrl attribute.

    async function validateApplePaySession(POSKey, SessionRequestUrl, ShopUrl) {
      const url = "https://api.test.barion.com/v2/ApplePay/ValidateSession";
      const data = {
        POSKey,
        SessionRequestUrl,
        ShopUrl,
      };
    
      try {
        const response = await fetch(url, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(data),
        });
    
        if (!response.ok) {
          throw new Error(`Error: ${response.status} ${response.statusText}`);
        }
    
        const result = await response.json();
        return result;
      } catch (error) {
        // handle the error according to your business logic
      }
    }
    
    applePaySession.onvalidatemerchant = async function (event) {
      const validationResult = await validateApplePaySession(POSKey, event.validationURL, ShopUrl);
      
      applePaySession.completeMerchantValidation(validationResult.ApplePaySessionResponse);
    };

    This event is triggered when the Apple Pay payment sheet is displayed to the customer.

  3. Set up an event handler for ApplePaySession.onpaymentauthorized

    Don't call the StartPaymentWithAppleToken Barion API endpoint directly from the browser, as this could expose your Barion shop's POSKey.

  4. that calls the StartPaymentWithAppleToken Barion API endpoint, passing it the event’s following attributes:

    • token
    • shippingContact
    • billingContact

    Note that StartPaymentWithAppleToken is actually a specialized version of the payment/start API endpoint, and so will also require all the usual parameters that you’d pass to that endpoint.

    async function startApplePayPayment(
      POSKey,
      ShippingContact,
      BillingContact,
      Token,
      /** include other required and optional Payment/Start params */
      PaymentStartProperties
    ) {
      const url =
        "https://api.test.barion.com/v2/ApplePay/StartPaymentWithAppleToken";
      const data = {
        POSKey,
        ShippingContact,
        BillingContact,
        Token,
        ...PaymentStartProperties,
      };
    
      try {
        const response = await fetch(url, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(data),
        });
    
        if (!response.ok) {
          throw new Error(`Error: ${response.status} ${response.statusText}`);
        }
    
        const result = await response.json();
        return result;
      } catch (error) {
        // handle the error according to your business logic
      }
    }
    
    const PaymentStartProperties = {
      PaymentType: "Immediate",
    };
    
    applePaySession.onpaymentauthorized = function (event) {
      startApplePayPayment(
        POSKey,
        event.paymentInfo.shippingContent,
        event.paymentInfo.billingContact,
        event.paymentInfo.Token,
        PaymentStartProperties
      );
    };

    This event is triggered when the customer has authorized the Apple Pay payment using their Touch ID or Face ID.

  5. Set up an event handler for oncancel to implement your business logic for when the user abandons the Apple Pay payment.

    Make sure that your event handler indicates that the session is canceled so the ApplePaySession’s completePayment method doesn’t get executed.

      applePaySession.oncancel = function (event) {
        // your oncancel business logic
    
        isSessionCanceled = true;
      };
  6. Call ApplePaySession.begin to kick off the payment process.

      applePaySession.begin();

    This starts the merchant validation process that results in ApplePaySession.onvalidatemerchant being triggered.

Testing your implementation

If you’re located in one of the countries or regions where the Apple Pay sandbox environment is available, use Apple’s Sandbox testing to try out your integration.

Related links

ValidateSession API endpoint

StartPaymentWithAppleToken API endpoint