Apple Pay Hosted Checkout Objects Reference (Request)

For complete sample code please refer here

Available dictionary objects


iStatus

const iStatus = {
    success: 100,
    unsupported: -100,
    error: -200
}

Use: iStatus.success

APButtonColor

const APButtonColor = {
    black: "black",
    white: "white",
    whiteOutline: "white-outline"
}    

Use: APButtonColor.black

APButtonType

const APButtonType = {
    buy: "buy",
    pay: "pay",
    plain: "plain",
    order: "order",
    donate: "donate",
    continue: "continue",
    checkout: "check-out"
}     

Use: APButtonType.buy

APRequiredFeatures

const APRequiredFeatures = {
    address_validation: "address_validation",
    support_recurring: "support_recurring",
    support_subscription : "support_subscription"
}  

Use: APRequiredFeatures.address_validation

APErrorCode

const APErrorCode = {
    shippingContactInvalid: "shippingContactInvalid",
    billingContactInvalid: "billingContactInvalid",
    addressUnserviceable: "addressUnserviceable",
    couponCodeInvalid: "couponCodeInvalid",
    couponCodeExpired: "couponCodeExpired",
    unknown: "unknown"
} 

Use: APErrorCode.addressUnserviceable

APErrorContactField

const APErrorContactField = {
    phoneNumber: "phoneNumber",
    emailAddress: "emailAddress",
    name: "name",
    phoneticName: "phoneticName",
    postalAddress: "postalAddress",
    addressLines: "addressLines",
    locality: "locality",
    subLocality: "subLocality",
    postalCode: "postalCode",
    administrativeArea: "administrativeArea",
    subAdministrativeArea: "subAdministrativeArea",
    country: "country",
    countryCode: "countryCode"
}

Use: APErrorContactField.administrativeArea

Request objects


ApplePayRequest

The Main object that contains all the information necessary to communicate with Apple Pay API.

Name

Type

Required

Description

merchantIdentifier

String

Yes

For merchants integrating their own Apple Developer account must be Merchant Identifier from the account, otherwise must be merchant.cardknox.com

buttonOptions

No

Provides Apple Pay button customization options. For more information please click the link

requiredFeatures

No

Features required by Merchant. Each Feature is available with the certain iOS version. Therefore if device doesn’t support that version (Feature) - Apple Pay Button won’t be displayed.

requiredBillingContactFields

No

List of field names used for requesting contact information in a payment request.

requiredShippingContactFields

No

List of field names used for requesting contact information in a payment request.

onAPButtonLoaded

String

Yes

Name of a callback function to be called when Apple Pay button is loaded. Accepts an object of type APButtonLoadedResult Please click here for the sample code

onGetTransactionInfo

String

Yes

Name of a callback function to be called that returns the final price and tax calculations. Please click here for the sample code

onGetShippingMethods

String

Yes

Name of a callback function to be called that returns a list of available Shipping Methods. Please click here for the sample code

onShippingContactSelected

String

Yes

Name of a callback function to be called when Shipping Contact is selected/changed. Accepts a parameter PaymentContact. Returns ShippingContactResponse. If address_validation is part of requiredFeatures in your ApplePay Request object you can return an Error as part of ShippingContactResponse. Please click here for the sample code

onShippingMethodSelected

String

Yes

Name of a callback function to be called when Shipping Method is selected/changed. Accepts a parameter ShippingMethod. Please click here for the sample code

onPaymentMethodSelected

String

Yes

Name of a callback function to be called when Payment Method is selected/changed. Accepts a parameter PaymentMethod. Please click here for the sample code

onBeforeProcessPayment

String

Yes

Name of a callback function to be called when consumer clicked the button but before Apple Pay sheet is loaded. Usually used to make validations before the payment. Please click here for the sample code

onValidateMerchant

String

Yes

Name of a callback function to be called to validate the Merchant. This functions accepts a parameter validationUrl. Please click here for the sample code

onPaymentAuthorize

String

Yes

Name of a callback function to be called when Apple Payment is authorized for the completion of the transaction. This function accepts a parameter of PaymentResponse. Please click here for the sample code

onPaymentComplete

String

Yes

Name of a callback function to be called when Apple confirms the completion of the transaction. This function accepts a parameter of PaymentComplete. Please click here for the sample code

onCancel

String

Yes

Name of a callback function to be called when user cancels. Please click here for the sample code

Request Examples

Payment Request example

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"
  };
}

onAPButtonLoaded callback example

apButtonLoaded: function(resp) {
    if (!resp) return;
    if (resp.status === iStatus.success) {
        showHide(this.buttonOptions.buttonContainer, true);
        showHide("lbAPPayload", true);
    } else if (resp.reason) {
        alert(resp.reason);
    }
}

onGetTransactionInfo callback example

taxAmt: null,
shippingMethod: null,
creditType: null,
getTransactionInfo: function (taxAmt, shippingMethod, creditType) {
  try {
    this.shippingMethod = shippingMethod || this.shippingMethod || {
                "label": "Free Shipping",
                "amount": "0.00",
                "type": "final"
            };
    this.taxAmt = roundToNumber(taxAmt, 4) || this.taxAmt || 0.07;
    this.creditType = creditType || this.creditType;
    const amt = getAmount();
    const lineItems = [
        {
            "label": "Subtotal",
            "type": "final",
            "amount": amt
        },
        this.shippingMethod
    ];
    if (this.creditType === "credit") {
        lineItems.push({
            "label": "Credit Card Fee",
            "amount": roundTo(0.0275*amt, 2),
            "type": "final"
        });
    }
    lineItems.push({
        "label": "Estimated Tax",
        "amount": roundTo(this.taxAmt*amt, 2),
        "type": "final"
    });
    let totalAmt = 0;
    lineItems.forEach((item) => {
        totalAmt += parseFloat(item.amount)||0;
    });
    totalAmt = roundTo(totalAmt, 2);

    return {
        'lineItems': lineItems,  
        total: {
                type:  'final',
                label: 'Total',
                amount: totalAmt,
            }
    };                        
  } catch (err) {
    console.error("getTransactionInfo error ", exMsg(err));
    if (isDebugEnv) {
        alert("getTransactionInfo error: "+exMsg(err));
    }
}
},  
onGetTransactionInfo: function () {
  try {
    return this.getTransactionInfo();
  } catch (err) {
    console.error("onGetTransactionInfo error ", exMsg(err));
    if (isDebugEnv) {
        alert("onGetTransactionInfo error: "+exMsg(err));
    }
  }
}

onGetShippingMethods callback example

onGetShippingMethods: function()  {
  return [
    {
        label: 'Free Shipping',
        amount: '0.00',
        identifier: 'free',
        detail: 'Delivers in five business days',
    },
    {
        label: 'Express Shipping',
        amount: '5.00',
        identifier: 'express',
        detail: 'Delivers in two business days',
    },
  ];
}

onShippingContactSelected callback example

onShippingContactSelected: function(shippingContact) {
  const self = this;
  return new Promise(function (resolve, reject) {
    try {
      console.log("shippingContact", JSON.stringify(shippingContact));
      let taxAmt = 0.1;
      const newShippingMethods = [
        {
          label: 'Free Shipping',
          amount: '0.00',
          identifier: 'free',
          detail: 'Delivers in five business days',
        }                                
      ];
      if (shippingContact && shippingContact.administrativeArea) {
        if (shippingContact.administrativeArea === "NY") {
          taxAmt = 0.0875;
          newShippingMethods.push(
            {
              label: 'Overnight Shipping',
              amount: '10.00',
              identifier: 'overnight',
              detail: 'Delivers in one business days',
            }
          );
        } else if (shippingContact.administrativeArea === "NJ") {
          taxAmt = 0.07;
          newShippingMethods.push(
            {
              label: 'Express Shipping',
              amount: '5.00',
              identifier: 'express',
              detail: 'Delivers in two business days',
            }
          );
        }
      }
      const resp = self.getTransactionInfo(taxAmt, newShippingMethods[0]);
      resp.shippingMethods = newShippingMethods;
      resolve(resp);                            
    } catch (err) {
      const apErr = {
        code: "-101",
        contactField: "",
        message: exMsg(err)
      }
      console.error("onShippingContactSelected error.", exMsg(err));
      if (isDebugEnv) {
        setTimeout(function(){ alert("onShippingContactSelected error: "+exMsg(err))}, 100);
      }
      reject({errors: [err]});
    }
  })                
}

onShippingMethodSelected callback example

onShippingMethodSelected: function(shippingMethod) {
  const self = this;
  return new Promise(function (resolve, reject) {
    try {
      console.log("shippingMethod", JSON.stringify(shippingMethod));
      const resp = self.getTransactionInfo(null, shippingMethod);
      resolve(resp);                            
    } catch (err) {
      const apErr = {
          code: "-102",
          contactField: "",
          message: exMsg(err)
      }
      console.error("onShippingMethodSelected error.", exMsg(err));
      if (isDebugEnv) {
          setTimeout(function(){ alert("onShippingMethodSelected error: "+exMsg(err))}, 100);
      }
      reject({errors: [err]});
    }
  })                
}

onPaymentMethodSelected callback example

onPaymentMethodSelected: function(paymentMethod) {
  const self = this;
  return new Promise(function (resolve, reject) {
    try {
      console.log("paymentMethod", JSON.stringify(paymentMethod));
      const resp = self.getTransactionInfo(null, null, paymentMethod.type);
      resolve(resp);                            
    } catch (err) {
      const apErr = {
          code: "-102",
          contactField: "",
          message: exMsg(err)
      }
      console.error("onPaymentMethodSelected error.", exMsg(err));
      if (isDebugEnv) {
          setTimeout(function(){ alert("onPaymentMethodSelected error: "+exMsg(err))}, 100);
      }
      reject({errors: [err]});
    }
  })                
}

onBeforeProcessPayment callback example

onBeforeProcessPayment: function () {
    return new Promise(function (resolve, reject) {
        try {
            //Do some validation here
            resolve(iStatus.success);
        } catch (err) {
            reject(err);
        }
    });
}
Payment callback example

onValidateMerchant callback example

onValidateMerchant: function(validationUrl) {
  return new Promise(function (resolve, reject) {
    try {
      if (isDebugEnv) {
        alert("onValidateMerchant: "+JSON.stringify(event), validationUrl);
      }

      getApplePaySession(validationUrl)
        .then(function (response) {
          try {
            console.log(response);
            resolve(response);
        } catch (err) {
            console.error("getApplePaySession exception.", JSON.stringify(err));
            setTimeout(function(){ alert("onValidateMerchant error: "+exMsg(err))}, 100);
            reject(err);
        }
      })
      .catch(function(err) {
        console.error("getApplePaySession error.", JSON.stringify(err));
        setTimeout(function(){ alert("getApplePaySession error: "+exMsg(err))}, 100);
        reject(err);
      });    
    } catch (err) {
      console.error("onValidateMerchant error.", JSON.stringify(err));
      if (isDebugEnv) {
          setTimeout(function(){ alert("onValidateMerchant error: "+exMsg(err))}, 100);
      }
      reject(err);
    }
  })
}

onPaymentAuthorize callback example

onPaymentAuthorize: function(paymentResponse) {
  return new Promise(function (resolve, reject) {
    try {
      authorizeAPay(paymentResponse.token)
      .then(function (response) {
        try {
            console.log(response);
            setAPPayload(JSON.stringify(paymentResponse, null, 2));
            const resp = JSON.parse(response);
            if (!resp)
                throw "Invalid response: "+ response;
            if (resp.xError) {
                throw resp;
            }
            resolve(response);
        } catch (err) {
            throw err;
            // console.error("authorizeAPay exception.", JSON.stringify(err));
            // setTimeout(function(){ alert("onPaymentAuthorize error: "+exMsg(err))}, 100);
            // reject(err);
        }
      })
      .catch(function(err) {
        console.error("authorizeAPay error.", JSON.stringify(err));
        apRequest.handleAPError(err);
        reject(err);
      });    
    } catch (err) {
      console.error("onPaymentAuthorize error.", JSON.stringify(err));
      apRequest.handleAPError(err);
      reject(err);
    }
  })
}

onPaymentComplete callback example

onPaymentComplete: function(paymentComplete) {
  if (paymentComplete.response) { //Success
    const resp = JSON.parse(paymentComplete.response);
    if (resp.xRefNum) {
      setTimeout(function(){ alert("Thank you for your order:("+resp.xRefNum+")")}, 100);
    } else {
      setTimeout(function(){ alert("Thank you for your order.")}, 100);
    }
  } else if (paymentComplete.error) {
    console.error("onPaymentComplete", exMsg(paymentComplete.error));
    handleAPError(paymentComplete.error);
  }                    
}

onCancel callback example

onCancel: function() {
  setTimeout(function () { alert("Payment was canceled") }, 500);
}

ButtonOptions Object

Name

Type

Required

Description

buttonContainer

String

Yes

Name of the <div> where Apple Pay Button will be loaded

buttonColor

No

From Google documentation:

  • default: A Google-selected default value. Currently black but it may change over time (default).

  • black: A black button suitable for use on white or light backgrounds.

  • white: A white button suitable for use on colorful backgrounds.

buttonType

No

From Google documentation:

  • buy: "Buy with Google Pay" button (default).

  • donate: "Donate with Google Pay" button.

  • plain: Google Pay button without additional text.

Button Options example

buttonOptions: {
    buttonContainer: "ap-container",
    buttonColor: APButtonColor.black,
    buttonType: APButtonType.pay
}

APButtonLoadedResult Object

Name

Type

Description

status

iStatus

There are 3 possible cases:

  • Apple Pay Button loaded successfully: status = iStatus.success

  • Apple Pay not supported: status = iStatus.unsupported

  • An error occurred while loading Apple Pay Button: status = iStatus.error

reason

String

If Apple Pay Button failed to load this field will be populated with the reason.


ApplePayContactField

Field names used for requesting contact information in a payment request.

Available fields:

  • name

  • email

  • phone

  • postalAddress

ApplePay Contact Field example

...
requiredBillingContactFields: ['postalAddress', 'name', 'phone', 'email'],
requiredShippingContactFields: ['postalAddress', 'name', 'phone', 'email'],
...

PaymentContact Object

Name

Type

Description

phoneNumber

String

A phone number for the contact

emailAddress

String

An email address for the contact

givenName

String

The contact’s given name

familyName

String

The contact’s family name

addressLines

String[]

The street portion of the address for the contact

subLocality

String

Additional information associated with the location, typically defined at the city or town level (such as district or neighborhood), in a postal address

locality

String

The city for the contact

postalCode

String

The zip code or postal code, where applicable, for the contact

subAdministrativeArea

String

The subadministrative area (such as a county or other region) in a postal address

administrativeArea

String

The state for the contact

country

String

The name of the country or region for the contact

countryCode

String

The contact’s two-letter ISO 3166 country code

ShippingContactResponse Object

Name

Type

Description

lineItems

A set of line items that explain recurring payments and additional charges and discounts.

total

A line item that represents the total for the payment.

shippingMethods

A list of Shipping Methods

error

Error code

LineItem Object

We’re now supporting Recurring and Deferred Payments as well as Subscriptions. These features are supported starting iOS 15.4.

These features are available if support_recurring and/or support_subscription is part of requiredFeatures list.

NameTypeDescription

type

ApplePayLineItemType

A value that indicates whether the line item is final or pending

label

String

A required value that’s a short, description of the line item

amount

String

A required value that’s the monetary amount of the line item.

Recurring and Subscription

paymentTiming

ApplePayPaymentTiming object

The time that the payment occurs as part of a successful transaction

recurringPaymentStartDate

Date

The date of the first payment

recurringPaymentEndDate

Date

The date of the final payment

recurringPaymentIntervalUnit

ApplePayRecurringPaymentDateUnit

The amount of time — in calendar units, such as day, month, or year — that represents a fraction of the total payment interval

recurringPaymentIntervalCount

Long

The number of interval units that make up the total payment interval

deferredPaymentDate

Date

The date, in the future, of the payment

automaticReloadPaymentThresholdAmount

String

The balance an account reaches before the merchant applies the automatic reload amount

ApplePayLineItemType

  • final - A line item representing the known, final cost.

  • pending - A line item representing an estimated or unknown cost.

ApplePayRecurringPaymentDateUnit

  • year

  • month

  • day

  • hour

  • minute

Recurring Line Item Example (Charging $20 starting today for the next year)

const startDate = new Date();
const endDate = new Date(startDate.getFullYear()+1, startDate.getMonth(), startDate.getDate());
lineItem = {
    "label": "Subscription",
    "amount": "20.00",
    "type": "final",
    "paymentTiming": "recurring",
    "recurringPaymentStartDate": startDate,
    "recurringPaymentIntervalUnit": "month",
    "recurringPaymentIntervalCount": 1,
    "recurringPaymentEndDate": endDate,
}

ShippingMethod Object

Name

Type

Description

label

String

Label for this Shipping Method

amount

String

Price for this shipping option

detail

String

Description for this Shipping Method

identifier

String

Identifier for this Shipping Method

ShippingMethod example

{    
    "label": "Free Shipping",
    "amount": "0.00",
    "detail": "Arrives in 7 to 10 business days",    
    "identifier": "free"
}

PaymentMethod Object

Name

Type

Description

displayName

String

A string, suitable for display, that describes the card

network

String

Name of the payment network backing the card

type

PaymentMethodType

The card's type of payment

billingContact

PaymentContact

The billing contact associated with the card


PaymentMethodType

A payment card’s type of payment.

The payment method type value is one of:

  • debit

  • credit

  • prepaid

  • store

Error Object

Note: Supported starting iOS 11. Available when address_validation is part of requiredFeatures list.

Name

Type

Description

code

One of Apple Pay Error Codes

contactField

One of Apple Pay Error Contact fields

message

String

Error message displayed to the customer

Last updated