Cardknox is now Sola
Learn More
LogoLogo
Contact Us
  • Introduction
  • 🔗API
    • Transaction API
      • Credit Card
      • Check (ACH)
      • EBT
      • Gift Card
      • Fraud
    • Customer and Recurring API
    • Reporting API
    • Account Boarding API
      • Account Boarding Merchant Agreement
      • Account Boarding Swagger UI
    • Code Samples
    • Error Codes
  • 📦SDK
    • .NET SDK
      • Transaction Workflow
    • iOS SDK
      • iOS SDK - Technical Guide
      • Workflow
    • Android SDK
      • Android SDK - Technical Guide
  • 🧰 Cardknox Products
    • 3D Secure 2.0
      • Client-Side Integration
        • Client-Side Integration (Non-iFields)
      • Server-Side Integration
    • Account Updater
    • Batch Processing
    • Browser-Based POS systems (BBPOS)
    • CloudIM Developer Guide
    • Deep Linking
      • Deep Linking Integration for Third-Party Websites
    • EBT Online
    • Gateway Emulators
    • iFields
      • Angular iFields
    • Merchant Portal
      • FAQ
    • Mobile App
    • Split Capture
    • Tap to Phone - Android
    • Partner Portal
    • PaymentSITE
      • QR Codes for PaymentSITE
    • Webhooks
  • 📱Mobile Wallets
    • Apple Pay Hosted Checkout
      • Apple Pay Hosted Checkout Initial Setup
      • Apple Pay Prerequisites
      • Apple Pay Hosted Checkout Objects Reference (Request)
      • Apple Pay Hosted Checkout Objects Reference (Response)
      • Apple Pay iFields Integration
      • Apple Pay Hosted Checkout Sample Code
      • Apple Pay Features
      • Set up Apple Pay Merchant ID with Cardknox
    • Click-To-Pay - Hosted Checkout
      • Click-To-Pay Initial Setup
      • Click-To-Pay Sample Code
      • Click-To-Pay iFields Integration
      • Click-To-Pay Objects Reference (Request)
      • Click-To-Pay Objects Reference (Response)
    • Google Pay Hosted Checkout
      • Google Pay Control Object
      • Google Pay Request Objects
      • Google Pay Response Objects
      • Google Pay Sample Code
      • iFields Integration
      • Google Pay FAQ
  • 🔌Plugins
    • Netsuite
      • NetSuite Features and Demo
    • WooCommerce
    • Magento Plugin
    • RMH (Retail Management Hero)
    • RMS (Retail Management Systems)
  • 📖Articles
    • Frequently Asked Questions
    • How to Build POS Integration Flows
    • Card Present Integration Guide
  • Glossary of Terms
Powered by GitBook
On this page
  • Initial Setup
  • Prerequisites
  • Implementing Apple Pay Hosted Checkout
  • Client-Side Integration
  • Server-Side Integration
  • Questions?

Was this helpful?

Export as PDF
  1. Mobile Wallets
  2. Apple Pay Hosted Checkout

Apple Pay Hosted Checkout Initial Setup

Last updated 3 months ago

Was this helpful?

Initial Setup

Contents

Prerequisites

Set up Apple Pay Merchant ID

Cardknox supports two solutions to help you set up your Apple Pay Merchant ID:

  1. - A simple solution where Cardknox handles all communications with Apple and takes care of all certificates.

  2. - in this case it will be your responsibility for mainlining account, domain and certificates up to date with Apple.

Implementing Apple Pay Hosted Checkout

Client-Side Integration

Adding Reference to iFields

Step 1: Add the iFields.js file after the <head> tag on your payment page:

<script src=https://cdn.cardknox.com/ifields/**ifields-version-number**/ifields.min.js></script>

Adding JavaScript Objects for Apple Pay button

Step 1: Add the following JS snippet inside the <body> where the Apple Pay button is desired.

<div id="ap-container">
</div>

Step 2: Create JavaScript object that holds all of the properties/methods required to process Apple Pay.

const window.apRequest = {
    buttonOptions: {
        buttonContainer: "ap-container",
        buttonColor: APButtonColor.black,
        buttonType: APButtonType.pay
    },
    ..............
    initAP: function() {
        return {
            buttonOptions: this.buttonOptions,
            merchantIdentifier: "<Your Apple Merchant Identifier provided by Cardknox>",
            requiredBillingContactFields: ['postalAddress', 'name', 'phone', 'email'],
            requiredShippingContactFields: ['postalAddress', 'name', 'phone', 'email'],
            onGetTransactionInfo: "apRequest.onGetTransactionInfo",
            onValidateMerchant: "apRequest.onValidateMerchant",
            onPaymentAuthorize: "apRequest.onPaymentAuthorize",
            onPaymentComplete: "apRequest.onPaymentComplete",
            onAPButtonLoaded: "apRequest.apButtonLoaded",
            isDebug: true
        };
    }
}

Step 3: Implement desired callbacks.

  • There are three main callbacks that must be implemented (the rest are optional):

    • onGetTransactionInfo - calculates the total amount based on the charge amount, fees, taxes, shipping costs, etc.

    • onValidateMerchant - a callback to be called to validate the Apple Pay Merchant.

    • onPaymentAuthorize - a callback that will be called after the consumer pays and Apple returns a token with all of the requested consumer information, like the billing address, shipping address, etc. This is where you need to make an ajax call to your server with the Apple Payload. The sample for making an ajax call is below.

Sample Code for Making Ajax Call:

validateApplePayMerchant: function (url) {
    return new Promise(function (resolve, reject) {
        try {
            var xhr = new XMLHttpRequest();
            xhr.open('POST', "https://api.cardknox.com/applepay/validate");
            xhr.onload = function () {
                if (this.status >= 200 && this.status < 300) {
                    resolve(xhr.response);
                } else {
                    reject({
                        status: this.status,
                        statusText: xhr.response
                    });
                }
            };
            xhr.onerror = function () {
                reject({
                    status: this.status,
                    statusText: xhr.statusText
                });
            };
            xhr.setRequestHeader("Content-Type", "application/json");
            xhr.send(JSON.stringify({ validationUrl: url}));
        } catch (err) {
            setTimeout(function () { alert("getApplePaySession error: " + exMsg(err)) }, 100);
        }
    });
},
authorize: function(applePayload, totalAmount) {
    return new Promise(function (resolve, reject) {
        var xhr = new XMLHttpRequest();
        xhr.open("POST", "https://<your domain>/<path to handle authorization>");
        xhr.onload = function () {
            if (this.status >= 200 && this.status < 300) {
                resolve(xhr.response);
            } else {
                reject({
                    status: this.status,
                    statusText: xhr.statusText
                });
            }
        };
        xhr.onerror = function () {
            reject({
                status: this.status,
                statusText: xhr.statusText
            });
        };
        const data = {
            amount: totalAmount,
            payload: applePayload
        };
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.send(JSON.stringify(data));
    });
}

Step 4: Create JavaScript function that will initialize iFields.

initAP: function() {
    return {
        buttonOptions: this.buttonOptions,
        merchantIdentifier: "merchant.cardknoxdev.com",
        requiredBillingContactFields: ['postalAddress', 'name', 'phone', 'email'],
        requiredShippingContactFields: ['postalAddress', 'name', 'phone', 'email'],
        onGetTransactionInfo: "apRequest.onGetTransactionInfo",
        onGetShippingMethods: "apRequest.onGetShippingMethods",
        onShippingContactSelected: "apRequest.onShippingContactSelected",
        onShippingMethodSelected: "apRequest.onShippingMethodSelected",
        onPaymentMethodSelected: "apRequest.onPaymentMethodSelected",
        onValidateMerchant: "apRequest.onValidateMerchant",
        onPaymentAuthorize: "apRequest.onPaymentAuthorize",
        onPaymentComplete: "apRequest.onPaymentComplete",
        onAPButtonLoaded: "apRequest.apButtonLoaded",
        isDebug: true
    };
}

Enable Apple Pay

window.ckApplePay object - controls initialization of Apple Pay button

Method

Call Required

Description

enableApplePay

Yes

updateAmount

Conditional

Updates amount on Apple Sheet.

You can provide either All, One, or None of the parameters for enableApplePay call.

  • initFunction Required - either function name or function itself to initialize Apple Pay.

  • amountField Optional - if specified, the Apple Pay total amount will be automatically updated whenever the amount has changed.

  • amountField is not specified - in this case, it’s up to you to provide the correct amount for Apple Pay. One of the ways to do it is to call window.ckApplePay.updateAmount manually.

EnableApplePayParams Object

Name

Type

Required

Description

initFunction

String|Object

Yes

Either function name or function itself to initialize Apple Pay

amountField

String|Object

No

Field containing amount. Could be either the name of the field (String) or the field itself (Object)

Enable Apple Pay example
ckApplePay.enableApplePay({
  initFunction: 'apRequest.initAP',
  amountField: 'amount'
});

Server-Side Integration

Server Endpoint Creation

A server endpoint is needed in order to accept the Apple Payload from Hosted Checkout.

const req = {
    amount: 1.45,
    payload: <Payload from Apple Response>
}

API Integration

Below are the steps to integrate Apple Pay with the Cardknox API:

Integration Steps:

  1. Extract the paymentData from the payload.

  2. Encode it with Base64 encoding.

  3. Set xCardNum field to the encoded value above.

  4. Set xDigitalWalletType to ApplePay.

  5. Set the remaining required fields:

    1. xAmount the Transaction Amount.

    2. xCommand - Set to one of the values that starts with cc: like cc:sale, cc:auth, etc.

    3. xBillFirstName

    4. xBillLastName

    5. xBillStreet

    6. xBillCity

    7. xBillState

    8. xBillZip

Sample Request:

public async Task<IActionResult> Authorize(AuthorizeRequest req) 
{
	var reqGateway = new
	{
		xKey = "Your xKey", 
		xAmount = (decimal)req.amount,
		xCommand = "cc:sale",
		xVersion = "4.5.4",
		xSoftwareName= "Your Software Name",
		xSoftwareVersion = "Your Software Version",
		xBillFirstName = req.paymentResponse.billingContact.givenName,
		xBillLastName = req.paymentResponse.billingContact.familyName,
		xBillStreet = req.paymentResponse.billingContact.addressLines[0],
		xBillCity = req.paymentResponse.billingContact.locality,
		xBillState = req.paymentResponse.billingContact.administrativeArea,
		xBillZip = req.paymentResponse.billingContact.postalCode,
		xShipFirstName = req.paymentResponse.shippingContact.givenName,
		xShipLastName = req.paymentResponse.shippingContact.familyName,
		xShipStreet = req.paymentResponse.shippingContact.addressLines[0],
		xShipCity = req.paymentResponse.shippingContact.locality,
		xShipState = req.paymentResponse.shippingContact.administrativeArea,
		xShipZip = req.paymentResponse.shippingContact.postalCode,
		xdigitalwallettype = "applepay",
		xcardnum = Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(req.payload.token.paymentData)))
	};
	var respMsg = "";
	using (var http = new HttpClient())
	{
		var resp = await http.PostAsJsonAsync("https://x1.cardknox.com/gatewayJSON", reqGateway);
		respMsg = await resp.Content.ReadAsStringAsync();
		.....
	}
	.....
}	

For more details, please contact your Cardknox Representative.

Questions?

Find the latest version of iFields at:

For a full sample code please refer to

For the list of available callbacks, please refer to .

For full sample code, please refer to

initAP function above returns .

Initializes and enables Apple Pay Button. Takes object.

Step 1: Create an endpoint and method for API Integration on your server side that takes an object containing total transaction amount and and makes a call to Cardknox. Sample Object:

This section assumes that you already know how to integrate other payments with

Once the consumer confirms the payment, Apple Pay API generates an in the form of a JSON string.

Contact

📱
https://cdn.cardknox.com/ifields/versions.htm
Apple Pay iFields Integration
Apple Pay Object
Apple Pay iFields Integration
Request Object
Cardknox API
support@cardknox.com
Set up Apple Pay Merchant ID through your Merchant Portal
Set up Apple Pay Merchant ID using your own Apple account
Prerequisites
Client-Side Integration
Adding Reference to iFields
Adding JavaScript Objects for Apple Pay button
Enabling Apple Pay
Server-Side Integration
Server Endpoint Creation
API Integration
EnableApplePayParams
Apple Payload
Apple Payload