Apple Pay Integration Guide

Integrating Apple Pay with Total Processing

Welcome to our guide for Apple Pay integration via the web. This is your go-to resource for seamlessly integrating Apple Pay with Total Processing as your payment gateway. Jumpstart the process by utilizing Total Processing's Apple Pay developer ID. This approach simplifies your setup and enhances security, removing the need to create your own ID.

Before you begin, we encourage you to explore our step-by-step overview for a clearer understanding of the process involved. When you're ready, proceed to the section below to begin your integration. Let's get started!

Account Setup & Requirements

This chapter introduces the initial stage of integrating Apple Pay with Total Processing as your payment gateway provider: setting up your account and ensuring compliance with all necessary requirements.


Account Setup

A successful integration with Total Processing requires an active account. This grants access to vital credentials, allows you to monitor transactions, and more. Here's what you need to get started:

Merchant Account An active test and/or production-based merchant account allows you to start making payments online.

Total Control 3 Account With your account, you'll get access to Total Control 3. This platform allows you to monitor both live and test environment transactions and provides you with access to view your Total Processing API credentials.

Get Started with Total Control 3 →

ApplePay Requirements

To successfully integrate with Total Processing, the following requirements should be met:

SSL & HTTPS Security Ensure your environment for testing and production is set up over a HTTPS connection. Your domain must have a valid SSL certificate.

Website Compliance Legal specifications for prohibited ApplePay use can be found here.

Supported Countries Review the supported countries for ApplePay here.


Domain Verification & Merchant Registration

This chapter provides you with steps for ensuring your domain has been verified and merchant registration with Apple Pay has been completed. These steps are essential to establish a secure and functional Apple Pay environment on your domain.


Domain Verification

Domain verification and enables you to prepare your website or domain to seamlessly integrate with Apple Pay. enable Apple Pay as a payment option on your site and assure all transactions are secure and correctly verified. Get started verifying your domain through three easy steps below.

01 Obtain a Verification File

Contact your Total Processing representative to acquire the necessary Apple Pay verification file for enabling Apple Pay on your website. This file is essential for registering your domain with Apple. Once received, please ensure this is served with the following header: Content-Type: text/plain.

02 Host the Verification File

Before making a Register Merchant request, host the domain-verification file at the following path for each domain you’re registering:

https://[DOMAIN_NAME]/.well-known/apple-developer-merchantid-domain-association

Ensure the domain-verification file is in place before invoking the Register Merchant API. This will be fully qualified domain name - E.G. Example.store.com - you will be registering with.

03 Domain Requirements

Apple's domain verification protocols require your domain name to be publicly accessible. This ensures transparency and compatibility with our services.To enable Apple Pay on your website, adhere to the following prerequisites:

  • All pages involving Apple Pay are secure and served over HTTPS

  • The domain must have a valid SSL certificate

  • The website must support TLS 1.2 or later with one of the cipher suites compatible as per standard web security guidelines. See Apple's Reference Guide for further information on TLS and cipher suites.

Merchant Registration

Merchant registration is a crucial first step for integrating Apple Pay into your business operations. By registering, you establish a secure transaction channel and obtain a unique identifier for your domain. This protocol, mandated by Apple, ensures the integrity of transactions, maintaining trust between your business and Apple device users.

Getting Started: Requirements

Before you start, ensure you have successfully integrated the verification file from the previous steps. Additionally, ensure you have read through the Account Setup & Requirements section to understand any additional requirements.

  1. Construct the request

    To register, you will need to send a POST request to an endpoint with specific parameters. Follow the API documentation, accessible via the navigation menu, for parameters, headers, and other necessary details to register.

  2. Register your account

    The API documentation also includes testing and production-ready registration POST request and response examples to help you understand and navigate the registration process seamlessly.

  3. Store the response identifier

    The response payload for a merchant registration includes a unique identifier known as the partnerInternalMerchantIdentifier. This identifier should be securely stored in your server environment, where your website or backend data is hosted. It should be encrypted and accessible only to authorized personnel. This identifier is crucial for all Apple Pay sessions associated with your domain as it ensures transactional security and identification.

Registration Parameters

Essential parameters required for merchant registration via POST request, including examples for testing and production environments.

Testing Domain Registration URL Content Type
application/json
Production Domain Registration URL Content Type
application/json

Parameter Format Sandbox Example Production Example
merchantName
A human-readable name for the merchant; the API does not parse this name programmatically.
String "mystore-testing" "mystore-production"
domainNames
A list of fully qualified domain names for which Apple Pay will process payments for this merchant. Items must be unique. The API is limited to 99 domain names per request.
Array ["example.com", "..."] ["example.com", "..."]
accessToken
Provided by us at total processing.
64 character String "8abcsek...85bh4==" "8a4gvsa...8egvh=="
entityId
Provided by us at total processing.
32 character String "8ac9a4c...4f8314abd" "8ac9fsd...314asdfbd"
Registration & Examples

The domain registration process begins with sending a POST request to the Total Processing server. After you've submitted the POST request, you will receive a Partnerinternalmerchantidentifier. This identifier should be securely stored in your server environment, where your website or backend data is hosted. This identifier is crucial for all Apple Pay sessions associated with your domain as it ensures transactional security and identification.

To assist you with this process, we've provided examples of requests for both Test and Production environments, below. Simply copy these code samples and use them as a template for your own registration. Remember to replace the example data in our code samples with your own information and credentials.

Attention needed

Please note, if you need to register more than one domain for a specific environment, please ensure these are entered into the domainNames array as follows: "domainNames": ["www.mystore.com, www.my2ndstore.com"]


Customisation & Styling

Explore the essentials of personalizing your Apple Pay interface. Learn to style and test the checkout process, enhancing its alignment with your brand's aesthetic while ensuring a seamless, streamlined user experience.


Designing Apple Pay

Get started integrating Apple Pay on your website, from setup to button styling, using the step-by-step tutorial guidance below and navigation guide steps. Resources for additional styles and customisations can also be found in the next steps. 

  1. Necessary Scripts

    Integration starts by incorporating two scripts into your HTML head section: jQuery and the Apple Pay SDK. These allow seamless interactions with the Apple Pay servers.

  2. Button Implementation

    The 'apple-pay-button' element will need to be added to your website, configured to fit your needs, to ensure proper functionality.

  3. Button Styling

    The Apple Pay button can be customized using CSS in the style tag in your HTML. Adjust its appearance to align with your site's design for a consistent user experience.

Including Necessary Scripts

This SDK allows you to create the Apple Pay button and manage essential interactions with the Apple Pay servers. Firstly, incorporate jQuery, which is a widespread JavaScript library that facilitates various tasks like HTML document traversal, event handling, and animation. Add it to the head section of your HTML:

1 <head>
2 <script  src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
3 <script  src="https://applepay.cdn-apple.com/jsapi/v1/apple-pay-sdk.js"></script>
4 </head>

Button Implementation

The Apple Pay button is a key element for the user to initiate a payment with Apple Pay. Here, we provide a detailed guide on how to successfully integrate the 'apple-pay-button' into your website.

Get started by adding the code below to your website. This includes all basic attributes like 'buttonstyle', 'type', and 'locale', which allow you to customize the button's appearance and localize it to match your user's language settings.

1 <body>
2 <apple-pay-button  buttonstyle="black"  type="plain"  locale="en"></apple-pay-button>
3 </body>
Information

For further capabilities involving customising your button or including specific text for specific Apple Pay button types, feel free to use the Apple resource listing below.

Button Interface Guidelines

https://developer.apple.com/design/human-interface-guidelines/apple-pay#Using-Apple-Pay-buttons

Button Types & Styles

Use the Apple developer documentation to get further CSS styles for variations of buttons, including the associated html.

ApplePay Button Design Demo

Use the 'Apple Pay on the web' Demo from Apple to get hands on demos of the different payment button styles you can use.

Styling the Apple Pay Button with CSS

Apple Pay offers several attributes for customizing the button's appearance and behavior, such as 'buttonstyle', 'type', and 'locale'. Here's an example of how to use these attributes:

Defining CSS Styles: The <style> HTML element helps define CSS styles in your document. Within this tag, create the CSS properties for the Apple Pay button:

Applying the Styles: Each CSS property affects a different aspect of the Apple Pay button's appearance:

1 <style>
2 apple-pay-button    {
3   --apple-pay-button-width:  150px;
4   --apple-pay-button-height:  30px;
5   --apple-pay-button-border-radius:  3px;
6   --apple-pay-button-padding:  0px 0px;
7   --apple-pay-button-box-sizing:  border-box;
8    }
9 </style>

Payment Creation & Authorization

Use the Apple Pay JavaScript API to integrate Apple Pay into online store's payment system. This chapter covers the technical implementation process, including creating and configuring the necessary code to enable secure payment processing through Apple Pay.


Payments Overview

This tutorial will involve creating a new project folder in your preferred code editor - we recommend Visual Studio Code. You'll include the index file you crafted in the previous step, as well as two additional files: payment.php and session.php.

  1. Checking Apple Availability

    Begin your Apple Pay integration by ensuring the necessary Apple Pay JavaScript API is available and enabled on your user's device. This step is vital in providing a seamless experience for your customers, and ensuring your setup proceeds without hitches.

  2. Creating a Payment Request

    Associate an 'onClick' function with the Apple Pay button to initiate a new Apple Pay session. This session establishes a secure communication link with Apple's servers, validates your website and kickstarts the payment request process.

  3. Complete Merchant Validation

    Merchant validation is a crucial step in the Apple Pay setup process. It confirms the legitimacy of your website and ensures a secure environment for transactions. During this phase, your website must make a server-to-server request to Apple's validation URL, receive a session object in response, and return it to the Apple Pay session. This two-way handshake builds a foundation of trust for all subsequent transactions.

  4. Authorizing Payments

    Once your Apple Pay session is established, you can execute a payment request. This triggers the Apple Pay payment sheet on the user's device, allowing them to authorize the payment securely. Once authorized, it's over to you and your backend server to process and finalize the transaction.

Checking for Apple Pay Availability

As we move forward, our initial task is to ascertain if the user's device supports Apple Pay. The 'canMakePayments' method, which we'll use in the forthcoming code snippets, is instrumental in achieving this.

The 'canMakePayments' function verifies if the device is compatible with Apple Pay. However, it does not confirm the existence of any provisioned cards in the Wallet. Available from Safari Desktop 10.0+ and Safari Mobile 10.0+, this method can be invoked at any time.

Now, let's inspect the code required to perform these checks:

1 if (window.ApplePaySession) {
2 // The Apple Pay JS API is available.
3 }
4 if (window.ApplePaySession) {
5 var merchantIdentifier = 'example.com.store';
6 var promise = ApplePaySession.canMakePaymentsWithActiveCard(merchantIdentifier);
7 promise.then(function (canMakePayments) {
8 if (canMakePayments)
9 // Display Apple Pay button here.
10 });
11 }
Information

To further your understanding of the Apple Pay JS API and its features, Apple provides extensive documentation. Below are a couple of resources that you might find useful in this context

supportsVersion This method is used to detect whether a web browser supports a particular Apple Pay version.
canMakePaymentsWithActiveCard This method indicates whether the device supports Apple Pay and whether the user has an active card in Wallet.

Creating a Payment Request

The essence of an Apple Pay transaction is the Payment Request, a data structure that contains all the necessary information for the purchase. This includes merchant details, supported payment networks, the total amount to be charged, and currency. It's crucial to note that Total Processing does not currently support recurring payments.

Line items, including the total, are also part of the Payment Request. Ensure your total amount is greater than or equal to zero with a non-empty label. The label should match your business name as customers would see it on their bank or credit card statement.

When setting up the Payment Request, the "amount" field is required. It must follow the regular expression -?[0-9]+(\.[0-9][0-9])? You can define the currency for the entire transaction, including line items, by setting the "currencyCode" property.

Here's an example of a Payment Request. This simple request sets up a payment for £0.01 in the UK, with the merchant supporting 3DS and accepting Visa, Mastercard, and Amex.

1 <script>
2 var paymentRequest = `{
3 "countryCode": "GB",
4 "currencyCode": "GBP",
5 "merchantCapabilities": ["supports3DS"],
6 "supportedNetworks": ["visa", "masterCard", "amex"],
7 "total": {"label": "Test", "type": "final", "amount": "0.01"}
8 }`;
9 </script>

Creating a Session

An Apple Pay Session, in the context of Apple Pay's JavaScript API, is the primary object that your website interacts with when processing an Apple Pay transaction.

When a user clicks the Apple Pay button on your website, you create an instance of an Apple Pay Session. This object manages the interaction between your website and the user's Apple device, facilitating the display of payment sheets, collection of user authorizations, and finally the processing of the transaction.

  1. Starting an Apple Pay session is the entry point for Apple Pay on the web. You will first need to create an Apple Pay button with an assigned ID like this:

    Attention needed

    When creating sessions, Please ensure you always use the merchantidentifier that is associated to the domain you're creating a session on. It is best practice to comment your merchantidentifiers as 'Test' or 'production' and include the domain names for each.


    1 <apple-pay-button
    2 id="apple-pay-button"
    3 buttonstyle="black"
    4 type="plain"
    5 locale="en">
    6 </apple-pay-button>
  2. Upon the readiness of your document, you'll need to add a click event listener to the button ID, which will start the Apple Pay session. This happens in your main script file.


    1 $(document).ready(function () {
    2 console.log("ready");
    3 $("#apple-pay-button").click(function () {
    4 console.log("starting Apple Pay session");
    5 var session = new ApplePaySession(3, JSON.parse(paymentRequest));
    6 session.begin();
    7 console.log(session);
    8 });
  3. After starting the Apple Pay session, you'll need to create a session on the server-side with validation URL. Here's an example of how to do this in PHP:


    1 ...
    2 // Make sure your postData information is correct. Replace this with your information.
    3 $postData = [
    4 "merchantIdentifier" => $merchantIdentifier,
    5 "displayName" => "Insert Here",
    6 "initiativeContext" => 'Insert Here',
    7 "initiative" => "web"
    8 ];
    9 ...
    10 $response = curl_exec($ch);
    11 curl_close($ch);
    12 echo $response;
    13 exit;
    14 ...

Merchant Validation

Merchant validation is a key step to ensure a secure Apple Pay transaction. This process involves Apple providing a validation URL, to which your server-side code must send a POST request. The purpose of this request is to verify your merchant session, which involves proving to Apple that you, as a merchant, are permitted to use Apple Pay and that you're the entity you say you are. This is done in the background, unbeknownst to the user.

Let's examine the code for the onvalidatemerchant function. This function undertakes the merchant validation process. Upon receiving the validationURL from Apple, it sends a POST request to your PHP session script. The script in turn sends a POST request to the validation URL and returns the response. This response (a session object), when received by your JavaScript, is then passed back to Apple to complete the validation process.

1 session.onvalidatemerchant = function (event) {
2 var promise = performValidation(event.validationURL);
3 promise.then(function (response) {
4 session.completeMerchantValidation(JSON.parse(response));
5 });
6 };

Payment Authorization

After the merchant validation, the next significant event in the Apple Pay lifecycle is the payment authorization. The user is prompted to authenticate using Touch ID, Face ID, or their device passcode. Upon successful user authentication, Apple Pay creates a payment token. This token contains the necessary payment information encrypted within it.

The onpaymentauthorized event handler is triggered when a payment is authorized. Within this handler, the payment token is sent to your server-side code for further processing. Here's how you handle payment authorization in your JavaScript code:

1 session.onpaymentauthorized = function (event) {
2 var promise = sendPayment(event.payment);
3 promise.then(function (response) {
4 session.completePayment(applePayPaymentAuthorizationResult);
5 });
6 };

1 <?php
2 // PartnerMerchantIdentifier for Your company. Replace with yours
3 $merchantIdentifier = "Youridentifer.totalprocessing.applepay-v2";
4 if ($_SERVER['REQUEST_METHOD'] === 'POST') {
5 // payment URL. Make sure you change the access and entity id to yours.
6 $paymentEndpoint = 'https://tpap2.totalprocessing.com/decrypt';
7 $entityId = '8asdfsdfsdfsdfsdfsdfsdfsdfsdfsdf';
8 $accessToken = 'OGFjN2E0Yzgsdfsdfsdfsdfsfsfsdfsdfsdfsfsfsd2RhUWg4eg==';
9 $body = file_get_contents('php://input');
10 // build payment data
11 $postData = [
12 'entityId' => $entityId,
13 'paymentType' => 'DB',
14 'amount' => '0.01',
15 'currency' => 'GBP',
16 'card.holder' => 'Mikey Mike',
17 'customParameters[SHOPPER_endpoint]' => 'eu-test.oppwa.com',
18 'customParameters[PAYMENT_source]' => 'yourwebsite.example.com',
19 'customer.ip' => $_SERVER['REMOTE_ADDR'],
20 'applePay.paymentToken' => json_decode($body)->token
21 ];
22 $headers = [
23 'content-type: application/json',
24 'Authorization: Bearer '. $accessToken
25 ];
26 $ch = curl_init($paymentEndpoint);
27 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
28 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
29 curl_setopt($ch, CURLOPT_POST, 1);
30 curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
31 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
32 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
33 $response = curl_exec($ch);
34 curl_close($ch);
35 echo $response;
36 exit;
37 } else {
38 curl_close($ch);
39 echo $response;
40 exit;
41 } else {
42 echo 'Unsupported HTTP Method';
43 }
44 ?>

Completion

Completion is the final step in the payment session. After your server processes the payment with the payment token it received during the authorization step, it needs to send a response back to the Apple Pay JavaScript running on your website. This response should indicate whether the payment processing was successful or not. Depending on this response, Apple Pay completes the payment and provides an appropriate message to the user.

In your JavaScript code, you can see that we call the completePayment method on the session object with the payment authorization result. The authorization result includes a status and an optional list of errors. Let's review this important step in the code:

1 var status = 1;
2 if (code != '000.000.000' && code != '000.100.110') {
3 status = 0;
4 }
5 var applePayPaymentAuthorizationResult = {
6 "status": status,
7 errors: errors
8 };

Cancellation

In an event where a user decides to cancel the payment process, it's essential to handle such cases in a manner that maintains a positive user experience. This is why the Apple Pay Session API provides an event handler for cancellation events, allowing developers to define custom behavior or fallbacks when a user cancels the payment process.

In your JavaScript code, you will notice the oncancel event handler for the Apple Pay session. This handler is called when the user decides to cancel the payment session. Here's the cancellation handler in your code:

1 session.oncancel = function(event) {
2 console.log("session cancelled");
3 console.log(event);
4 }

Testing & Going Live

Explore recommendations for effectively integrating Apple Pay on your website and transitioning from the testing phase to live operation. For any further questions or potential issues during your implementation, consult the included FAQs or contact our dedicated support team.


Switching to Live Operations: Integrating Apple Pay via Total Processing

Integrating Apple Pay into your webstore is a significant step to provide a seamless and secure shopping experience for your customers. When transitioning from the testing phase to live operations with Total Processing as your payment gateway, there are several key areas you need to focus on.

This includes extensive end-to-end testing, adhering to PCI DSS compliance, maintaining a smooth customer experience, providing effective customer support, and leveraging advanced features.

  • Rigorous Testing

    Performing comprehensive tests using varied scenarios can help identify any potential issues before they impact your customers. Make sure your payment process works seamlessly across different browsers, devices, and under different network conditions.

  • Ensure Security and Compliance

    Your Apple Pay integration must be secure and comply with Payment Card Industry Data Security Standard (PCI DSS) requirements. Regularly verify the security protocols and adhere to guidelines provided by Total Processing to keep your transactions secure.

  • User Experience

    User experience is paramount to the success of your Apple Pay integration. Ensure the Apple Pay button is prominently placed and the payment process is intuitive. Make it easy for your customers to choose Apple Pay as their preferred payment method.

Technical specifications

See the specification listing & further resources below to ensure you are fully prepared to go live.

Further Support

Contact

Accepted Models

iOS devices running iOS 11 or later

Safari 11 on macOS 10.13 or later

Additional Features

Shipping Details

Supported browsers

Safari