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.

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",
    onError: "apRequest.onError",
    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);
  }                    
}

onError callback example

onError: function(error) {
  setTimeout(function () { alert(`An error occured: ${error}`) }, 500);
}

onCancel callback example

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

ButtonOptions Object

Button Options example

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

APButtonLoadedResult Object


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

ShippingContactResponse Object

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.

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

ShippingMethod example

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

PaymentMethod Object


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.

Last updated