Skip to main content

Comcarde Web Client SDK

The comcarde-web Client SDK helps you gather payment data from your customers browser, for use in payments on your server.

overview diagram

  1. comcarde-web helps you gather payment data from your customers browser. The SDK will handle any necessary communication with the Comcarde REST API (using your Client API Key).
  2. Your web client passes the payment information to your server.
  3. Your server creates payments via the Comcarde REST API (using your Server API Key).

Client SDKs can help you gather information required for payments, but only a server with a Server API Key can create payment transactions. This ensures that it is not possible to create unauthorized payment transactions using keys visible to client devices.

Prerequisites#

Before you begin, you'll need a JavaScript enabled website or app, and a Client API Key.

Comcarde JavaScript Client#

At a minimum, you will need to create a Comcarde JavaScript Client in your Website or App.

First, load the client code for your target environment:

<script src="https://sandbox-assets.comcarde.com/web/v2/js/client.min.js"></script>

Finally, create an instance of the Comcarde JavaScript Client:

comcarde.client.create({  authorization: client-api-key // your client API Key}, function(clientErr, clientInstance) {  if (clientErr) {    console.error(clientErr);    return;  }
  // this is where you will configure the plugin modules...});

Pluggable Modules#

Additional functionality can be added to your Comcarde JavaScript Client in the form of pluggable modules. This allows you to only pull in what you need, keeping your web client footprint small.

Comcarde Hosted Fields Module#

Fully outsource all your cardholder data functions to Comcarde so that your platform qualifies for the simplest PCI-DSS SAQ level.

This is achieved by collecting the most sensitive card-holder data via inline frames (iframes) hosted by Comcarde domains. Comcarde PCI-DSS SAQ-D compliant systems can then translate the data into a single use token that can be safely handled by your PCI-DSS SAQ-A platform. The token can be used by your back-end services to generate a payment via the Comcarde REST API.

Comcarde Hosted Fields Diagram

Add Comcarde Hosted Fields Module To Your App#

In addition to the Comcarde JavaScript Client, add a hosted-fields module to your website source.

<script src="https://sandbox-assets.comcarde.com/web/v2/js/hosted-fields.min.js"></script>

Insert placeholder elements with special IDs into your website. These can be positioned to fit in with your website/app design. The hosted-fields module will find the elements based on their ID, and replace them with <iframe> elements.

Hosted Field element ID's

  • card-number
  • cvv
  • expiration-date

Example:

<div id="card-number"></div>

You can also provide labels for the hosted fields, the same as if it were a field hosted by the parent website/app.

<label for="expiration-date">Expiration Date</label><div id="expiration-date"></div>

Finally, add hosted fields functionality to your Comcarde JavaScript Client:

comcarde.client.create({  authorization: client-api-key // your client API Key}, function(clientErr, clientInstance) {
  // optionally configure other plugin modules...
  /*   * Create Comcarde Hosted Fields Plugin Module Component   */  comcarde.hostedFields.create({        client: clientInstance,        styles: {            // Style all elements            'input': {                'font-size': '16px',                'color': '#3A3A3A',                'font-family': 'monospace'            },
            // Styling element state            ':focus': {                'color': 'blue'            },            '.valid': {                'color': 'green'            },            '.invalid': {                'color': 'red'            },
            // Media queries            // Note that these apply to the iframe, not the root window.            '@media screen and (max-width: 700px)': {                'input': {                    'font-size': '16px'                }            },        },        fields: {            number: {                selector: '#card-number',                placeholder: 'xxxx xxxx xxxx xxxx'            },            cvv: {                selector: '#cvv',                placeholder: 'xxx'            },            expirationDate: {                selector: '#expiration-date',                placeholder: 'MM/YYYY'            }        }    }, function(hostedFieldsErr, hostedFieldsInstance) {        if (hostedFieldsErr) {            console.error(hostedFieldsErr);            return;        }
        hostedFieldsInstance.on('validityChange', function(event) {            var field = event.fields[event.emittedBy];            if (field.isValid) {                // handle valid case            } else if(field.isPotentiallyValid) {                // handle potentially valid case            } else {                // handle invalid case            }        });
        form.addEventListener('submit', function(event) {            event.preventDefault();
            /*             * Cardholder name, issue number, and start date can optionally also be passed to             * the tokenize operation. This data can safely be collected via normal fields             * without requiring more than PCI DSS SAQ A accreditation.             *             * This can be useful if your Comcarde account is configured to potentially use             * Payment Service Providers that require card holder names for instance.             */            hostedFieldsInstance.tokenize({                'cardholderName': 'X Ample',                'issueNumber': '01',                'startDate': '01/19'            }, function(tokenizeErr, payload) {                if (tokenizeErr) {                    console.error(tokenizeErr);                    return;                }
                // send payload.token to your server to be used as a tokenized payment                // instrument in a payment request.            });        }, false);    });});

3D Secure Module#

3D Secure Module Overview Diagram

This module automates the handling of 3D Secure additional actions, as part of the 3D Secure Payment Flow.

Module usage#

In addition to the Comcarde JavaScript Client, add the three-d-secure module to your website source:

<script src="https://sandbox-assets.comcarde.com/web/v2/js/three-d-secure.min.js"></script>

Finally, add the module to your Comcarde JavaScript Client:

comcarde.client.create({  authorization: client-api-key // your client API Key}, function (clientErr, clientInstance) {
  // optionally configure other plugin modules...
  /*   * Create a 3D Secure Plugin Module Component.   */  comcarde.threeDSecure.create({    client: clientInstance  }, function (err, threeDSecureInstance) {    if (err) {      console.log(err);      return;    }
    var serverResponse = // the full 2001 response received on your server
    threeDSecureInstance.threeDSecureChallenge(serverResponse).then(function (response) {
      var message = response.message; // text explanation of the outcome      var paymentId = response.paymentId; // unique id of the payment
      if (response.code === 1000) {
        // congratulations, your payment has succeeded, no further action required
      } else if (response.code === 2002) {
        var nonce = response.nonce; // can be used to finalise the payment via your server
        // Optional additional information to help you make an informed decision        // whether to proceed with the payment        if (response.threeDSecureInfo) {
          // status description returned by the PSP          var pspStatus = response.threeDSecureInfo.pspStatus;
          // e.g. "2"          var threeDSecureVersion = response.threeDSecureInfo.threeDSecureVersion;
          if (response.threeDSecureInfo.liabilityShifted) {
            /*             * 3D Secure worked and authentication succeeded.             *             * This will also be true if the issuing bank does not support 3D Secure,             * but the payment method does. In both cases, the liability for fraud             * has been shifted to the bank. You can now finalise the payment using             * response.nonce on your server.             */
          } else {
            /*             * 3D Secure authentication failed. It is still possible to finalise the             * payment using the payment.nonce via your server, but you will need to             * set 3D secure required flag to false.             */
            if (response.threeDSecureInfo.liabilityShiftPossible) {              // the payment instrument was eligible for 3D Secure            } else {              // the payment instrument was not eligible for 3D secure.            }
          }
        }
      } else if (response.code === 2004) {        // an error occurred when attempting 3D Secure authentication.        // See response.message      }
    }).catch(function (err) {      console.log('threeDSecureChallenge failed. err: ' + JSON.stringify(err));    });
  });
});

PayPal™ Module#

Enable payments using PayPal Smart Buttons. This works by integrating with PayPal APIs to generate a single use PayPal nonce, which can be used by your server as a payment instrument with the Comcarde REST API.

Note: This module can only be used with Merchant Accounts configured to route all Payments with PayPal Payment Instruments to Adyen Payment Service Provider. We plan to add support for more PSPs soon and deprecate the PayPal Checkout Module.

!PayPal Module Overview

Add PayPal Module To Your App#

In addition to the Comcarde JavaScript Client, you will need to add the following to your website source.

<script src="https://sandbox-assets.comcarde.com/web/v2/js/paypal.min.js"></script>

Next, insert a placeholder element <div id="paypal-button"></div> into your website, which wil be populated with a PayPal button by the PayPal module.

Finally, add PayPal functionality to your Comcarde JavaScript Client:

comcarde.client.create({  authorization: client-api-key // your client API Key}, function(clientErr, clientInstance) {
  // optionally configure other plugin modules...
  /*   * Create a paypal plugin module component   */  comcarde.paypal.create({    client: clientInstance  }, onPaypalMakePayment, onPaypalAuthorizePayment, onPaypalCancel, onPaypalError);
  /*   * Callback promise allowing you to provide checkout data after your user clicks the   * paypal button   */  function onPaypalMakePayment() {    return new Promise((resolve, reject) => {      resolve({        amount: '1234', // amount of the transaction. In the lowest denomination of the currency        currency: 'GBP', // currency code of the amount, such as 'USD'        customerOrderCode: 'abc-1234' // unique customer order code to represent the transaction.      });    });  }
  /*   * Callback method providing you with a nonce that can be used as a PayPal Payment   * Instrument by your server.   */  function onPaypalAuthorizePayment(nonce) {    console.log('Got a PayPal nonce: ' + nonce);  }
  /*   * Callback method for when your user decides to cancel using PayPal   */  function onPaypalCancel(onCancelEvent) {    console.log(onCancelEvent);  }
  /*   * Callback method for when an error is encountered   */  function onPaypalError(onErrorEvent) {    console.error(onErrorEvent);  }});

PayPal™ Checkout Module#

Enable payments using PayPal Checkout. This works by integrating with PayPal APIs to generate a single use PayPal nonce, which can be used as a payment instrument for the Comcarde REST API.

PayPal Checkout Overview

Add PayPal Checkout Module To Your App#

In addition to the Comcarde JavaScript Client, add the paypal-checkout module and associated PayPal Checkout code to your website source:

<script src="https://sandbox-assets.comcarde.com/web/v2/js/paypal-checkout.min.js"></script><script src="https://www.paypalobjects.com/api/checkout.js" data-version-4></script>

Next, insert a placeholder element <div id="paypal-button"></div> into your website, which will be populated with a PayPal button by the PayPal Checkout code.

Finally, add PayPal Checkout functionality to your Comcarde JavaScript Client:

comcarde.client.create({  authorization: client-api-key // your client API Key}, function(clientErr, clientInstance) {
    // optionally configure other plugin modules...
    /*     * Create a PayPal Checkout Plugin Module Component.     */    comcarde.paypalCheckout.create({        client: clientInstance    }, function(paypalCheckoutErr, paypalCheckoutInstance) {
        // Stop if there was a problem creating PayPal Checkout.        // This could happen if there was a network error or if it's incorrectly        // configured.        if (paypalCheckoutErr) {            console.error('Error creating PayPal Checkout:', paypalCheckoutErr);            return;        }
        // Set up PayPal with the checkout.js library        paypal.Button.render({            env: 'sandbox', // Or 'production'            commit: true, // This will add the transaction amount to the PayPal button
            payment: function() {                customerOrderCode = 'Your customers unique order code' // unique code for order
                /**                 * @typedef {object} PayPalCheckout~lineItem                 * @property {string} quantity Number of units of the item purchased. This value                 * must be a whole number and can't be negative or zero.                 * @property {string} unitAmount Per-unit price of the item.                 * * Value of the item specified in the lowest denomination of the given currency.                 * @property {string} name Item name. Maximum 127 characters.                 * @property {string} kind Indicates whether the line item is a debit (sale) or                 * credit (refund) to the customer. Accepted values: `debit` and `credit`.                 * @property {?string} unitTaxAmount Per-unit tax price of the item.                 * * Value of the item tax specified in the lowest denomination of the given                 *   currency.                 * @property {?string} description Item description. Maximum 127 characters.                 * @property {?string} productCode Product or UPC code for the item. Maximum 127                 * characters.                 * @property {?string} url The URL to product information.                 */
                /**                * Creates a PayPal payment ID or billing token using the given options. This is                * meant to be passed to PayPal's checkout.js library.                * When a {@link callback} is defined, the function returns undefined and invokes                * the callback with the id to be used with the checkout.js library. Otherwise, it                * returns a Promise that resolves with the id.                * @public                * @param {object} options All options for the PayPalCheckout component.                * @param {string} [options.flow=checkout]                * @param {string} [options.intent=capture]                * * `authorize` - Submits the transaction for authorization but not settlement.                * * `order` - Validates the transaction without an authorization (i.e. without                *    holding funds). Useful for authorizing and capturing funds up to 90 days                *    after the order has been placed.                * * `capture` - Payment will be immediately submitted for settlement upon creating                *    a transaction.                * @param {string} [options.customerOrderCode] Customer order code represents a                * single paypal transaction.                * @param {boolean} [options.offerCredit=false] Offers PayPal Credit as the default                * funding instrument for the transaction. If the customer isn't pre-approved for                * PayPal Credit, they will be prompted to apply for it.                * @param {string|number} [options.amount] The amount of the transaction.                * * Value of the payment specified in the lowest denomination of the given currency.                * @param {string} [options.currency] The currency code of the amount, such as 'USD'.                * @param {string} [options.displayName] The merchant name displayed inside of the                * PayPal lightbox; defaults to the company name on your Comcarde account.                *  This option may not be supported by all payment service providers.                * @param {string} [options.locale=en_US] Use this option to change the language,                * links, and terminology used in the PayPal flow. This locale will be used unless                * the buyer has set a preferred locale for their account. If an unsupported locale                * is supplied, a fallback locale (determined by buyer preference or browser data)                * will be used and no error will be thrown.                * This option may not be supported by all payment service providers.                *                * Supported locales are:`da_DK`,`de_DE`,`en_AU`, `en_GB`, `en_US`,`es_ES`,`fr_CA`,                * `fr_FR`,`id_ID`, `it_IT`, `ja_JP`, `ko_KR`,`nl_NL`, `no_NO`, `pl_PL`,`pt_BR`,                * `pt_PT`, `ru_RU`, `sv_SE`, `th_TH`, `zh_CN`, `zh_HK`, and `zh_TW`.                *                * @param {boolean} [options.enableShippingAddress=false] Set to true to display shipping                * address selection in the PayPal checkout page/window, set to false to hide shipping address.                * If an address is supplied in shippingAddressOverride it will be displayed regardless of the                * value of this field. This option may not be supported by all payment service providers.                * @param {object} [options.shippingAddressOverride] Allows a shipping address that                * has been previously collected to be passed into the PayPal payment flow. This option                * may not be supported by all payment service providers.                * @param {string} options.shippingAddressOverride.line1 Street address.                * @param {string} [options.shippingAddressOverride.line2] Street address (extended).                * @param {string} options.shippingAddressOverride.city City.                * @param {string} options.shippingAddressOverride.state State.                * @param {string} options.shippingAddressOverride.postalCode Postal code.                * @param {string} options.shippingAddressOverride.countryCode Country.                * @param {string} [options.shippingAddressOverride.phone] Phone number.                * @param {string} [options.shippingAddressOverride.recipientName] Recipient's name.                * @param {boolean} [options.shippingAddressEditable=true] Set to true to enable user selection                * of the shipping address in the PayPal checkout page/window even if an address in                * shippingAddressOverride is supplied. This option may not be supported by all payment service providers.                * @param {string} [options.billingAgreementDescription] Use this option to set the                * description of the preapproved payment agreement visible to customers in their                * PayPal profile during Vault flows. Max 255 characters. This option may not be supported by all                * payment service providers.                * @param {string} [options.landingPageType] Use this option to specify the PayPal                * page to display when a user lands on the PayPal site to complete the payment.                * * `login` - A PayPal account login page is used.                * * `billing` - A non-PayPal account landing page is used.                * This option may not be supported by all payment service providers.                * @property {lineItem[]} [options.lineItems] The line items for this transaction.                * It can include up to 249 line items.  This option may not be supported by all payment service providers.                **/                return paypalCheckoutInstance.createPayment({                    flow: 'checkout', // Required                    amount: 1000, // Required                    currency: 'GBP', // Required                    intent: 'capture',// Required                    customerOrderCode: customerOrderCode, // Required                    offerCredit: false,                    displayName: 'Bridge',                    locale: 'en_GB',                    enableShippingAddress: true,                    shippingAddressOverride: {                        line1: 'Line 1',                        line2: 'Line 2',                        city: 'City',                        state: 'State',                        postalCode: 'PostalCode',                        countryCode: 'GB',                        phone: '0000 0000000',                        recipientName: 'Joe Bloggs'                    },                    shippingAddressEditable: true,                    billingAgreementDescription: 'a billing agreement',                    landingPageType: 'login',                    lineItems: [                        {                            quantity: 2,                            unitAmount: 300,                            name: 'a line item',                            kind: 'debit',                            unitTaxAmount: 200,                            description: 'description of the line item',                            productCode: 'A0001',                            url: 'a@b.com'                        }                    ]                });            },            onAuthorize: function(data, actions) {                data.customerOrderCode = customerOrderCode;
                /**                * Tokenizes the authorize data from PayPal's checkout.js library when completing a                * buyer approval flow. When a {@link callback} is defined, invokes the callback                * with {@link PayPalCheckout~tokenizePayload|tokenizePayload} and returns                * undefined. Otherwise, returns a Promise that resolves with a                * @link PayPalCheckout~tokenizePayload|tokenizePayload}.                * @public                * @param {object} tokenizeOptions Tokens and IDs required to tokenize the payment.                * @param {string} tokenizeOptions.payerId Payer ID returned by PayPal `onApproved`                * callback.                * @param {string} [tokenizeOptions.paymentId] Payment ID returned by PayPal                * `onApproved` callback.                * @param {string} [tokenizeOptions.paymentToken] paymentToken provided by                * Checkout.js v4 is the ECToken                * @param {string} [tokenizeOptions.billingToken] Billing Token returned by PayPal                * `onApproved` callback.                * @param {string} [tokenizeOptions.intent] Intent of the  payment.                * @param {string} [tokenizeOptions.customerOrderCode] Customer order code                * represents a single paypal transaction. This should be the same order code used                * to create the payment.                */                return paypalCheckoutInstance.tokenizePayment(data, function(err, responsePayload) {                    /**                     * When a response is received as a result of the tokenizePayment call,                     * the responsePayload will contain the following:                     * - responsePayload.nonce - the payment nonce to send as part of the                     *   payment request to make to your server. It should be set as the nonce                     *   value of the 'PayPal' payment instrument type in the payment.                     * - responsePayload.payerInfo - information about the payer which can be used                     *   to set certain values in the subsequent server-side payment request.                     *   This includes:                     *   - responsePayload.payerInfo.email - email address of the payer                     *   - responsePayload.payerInfo.payerId - the payerId of the payer                     *   - responsePayload.payerInfo.firstName and responsePayload.payerInfo.lastName                     *   - responsePayload.payerInfo.phone - phone number of the payer                     *   - responsePayload.payerInfo.shippingAddress - the shipping address to use                     *   for the PayPal order. This may have been set by the merchant in the initial                     *   'createPayment' operation, or it may have been selected by the  payer customer                     *   in the PayPal checkout UI.                     *   - responsePayload.payerInfo.billingAddress - the billing address of the payer                     *                     *   Note that although the nonce will definitely be returned, as it is essential for                     *   completing the payment, it is not guaranteed that all of the rest of this                     *   information will be returned as different PSPs may have different                     *   capabilities in how much information they return.                     */                    console.log('Got a paypal nonce: ' + responsePayload.nonce);                });            },
            onCancel: function(data) {                console.log('paypal checkout payment cancelled', JSON.stringify(data, 0, 2));            },
            onError: function(err) {                console.error('checkout.js error', err);            }        }, '#paypal-button').then(function() {            // The PayPal button will be rendered in an HTML element with the ID            // `paypal-button`. This function will be called when the PayPal button            // is set up and ready to be used.            console.log("paypal button ready!");        });    });});

Google Pay™ Module#

Enables payments using the Google Pay™ for Payments - Web API. This works by integrating with Google Pay™ to generate a single use Comcarde Google Pay™ Nonce, which is used as a Payment Instrument for the Comcarde REST API.

Google Pay Module Components

Add the Google Pay™ Module to your App#

In addition to the Comcarde JavaScript Client, add the google-pay module to your website source:

<script src="https://sandbox-assets.comcarde.com/web/v2/js/google-pay.min.js"></script>

Next insert a placeholder element to your page and give it a unique id so the google-pay module can populate it with a Google Pay™ button, for example:

<div id="google-pay-button"></div>

Finally, add Google Pay™ functionality to your Comcarde JavaScript Client:

comcarde.client.create({  authorization: client-api-key // your client API Key}, function(clientErr, clientInstance) {
  // optionally configure other plugin modules...
  // Declare empty mutable object for the comcardeGooglePayInstance  let comcardeGooglePay = {};
  comcarde.googlePay.create({     client: clientInstance,     containerId: 'google-pay-button' // <- unique identifer of your button element  }, function() {   comcardeGooglePay.startPaymentJourney({     /*      * This object describes a transaction that determines a payer's ability to pay. It's used to      * present a payment authorization dialog.      * Please see https://developers.google.com/pay/api/web/reference/request-objects#TransactionInfo      * for a full description      */     "totalPriceStatus": "FINAL",     "totalPrice": "9.99",     "countryCode": "GB",     "currencyCode": "GBP"   }).then(function (payload) {     /*      * send payload.token to your server to be used as a googlePay payment      * instrument in a payment request.      */     console.log("googlePay token: " + payload.token);     /*      * payload.id contains a unique identifier for the response. This will      * be helpful to us if you need assistance or support      */      console.log("googlePay tokenization trace id: " + payload.id)    }).catch(function (startPaymentJourneyError) {      console.error(startPaymentJourneyError);    });  }).then(function(comcardeGooglePayInstance) {    /*     * Assign the Comcarde Google Pay™ instance to the comcardeGooglePay variable for use in the     * payment callback     */    comcardeGooglePay = comcardeGooglePayInstance;  }).catch(function (googlePayModuleError) {    console.error(googlePayModuleError);  });});

Apple Pay™ Module#

Enable payments using Apple Pay on the Web for users using the Safari browser on Apple devices with sufficient security features.

Apple Pay Module Components

Warning: Please check for Apple Pay availability on your customers browser before attempting to load this module. You may encounter errors if used in a non supported device.

Add the Apple Pay™ Module to your App#

In addition to the Comcarde JavaScript Client, add the apple-pay module to your website source:

<script src="https://sandbox-assets.comcarde.com/web/v2/js/apple-pay.min.js"></script>

Next insert a placeholder element to your page and give it a unique id so the apple-pay module can populate it with an Apple Pay™ button, for example:

<div id="apple-pay-button" onclick="processApplePayPayment()"></div>

The onclick event is a JavaScript method that will initiate the payment, as shown below. Apple enforces this to be a user's interaction.

Finally, add Apple Pay™ functionality to your Comcarde JavaScript Client:

comcarde.client.create({   authorization: client-api-key // your client API Key}, function(clientErr, clientInstance) {  /*   * Optional (but recommended): A conditional statement to ensure the users browser supports ApplePay: i.e Safari only   * The SDK will throw a non-breaking validation error within an unsupported browser without this conditional, and   * show a short message in the place where the Apple Pay button would render.   *   * See Checking for Apple Pay Availability -   * https://developer.apple.com/documentation/apple_pay_on_the_web/apple_pay_js_api/checking_for_apple_pay_availability   */  if (window.ApplePaySession) {    comcarde.applePay.create({       client: clientInstance,       button: {         container: 'apple-pay-button', // <- unique identifer of your button element         style: 'black',         type: 'buy'       }    }).then(function (applePayClientModule) {       processApplePayPayment = function() { // <- the onclick method from the apple pay button placeholder         applePayClientModule.startSession({            label: 'A short order description', // cannot be empty            type: 'final', // type should always be final            amount: '10.00' // String of the total amount to be charged, must be greater than 0.00         }, function (comcardeSingleUseToken, ApplePaySession) { // onpaymentauthorized
            /*             * send comcardeSingleUseToken to your server to be used as a applePay payment             * instrument in a payment request.             */            console.log("applePay token: " + comcardeSingleUseToken);
            /*             * Finally, update the ApplePaySession with the outcome of the server side payment request.             * This completes the payment authorization with a result.             */            ApplePaySession.completePayment(serverPaymentSuccess ? ApplePaySession.STATUS_SUCCESS : ApplePaySession.STATUS_FAILED);
         }).then(function (applePayPaymentRequest) {            applePayClientModule.session(applePayPaymentRequest).then(function (applePaySession) {               applePaySession.onerror = function(applePaySessionError) {                  // TODO: Handle the applePaySessionError Event                  console.error(applePaySessionError);               };               applePaySession.oncancel = function(applePaySessionCancelled) {                  // TODO: Handle the applePaySessionCancelled Event                  console.warn(applePaySessionCancelled);               }            }).catch(function (applePayClientModuleSessionError) {               // TODO: Handle the applePayClientModuleSessionError               console.error(applePayClientModuleSessionError);            });         }).catch(function (applePayClientError) {            // TODO: Handle the applePayClientError            console.error(applePayClientError);         });       }    }).catch(function(applePayClientModuleError) {       // TODO: Handle the applePayClientModuleError       console.error(applePayClientModuleError);    });  }});

Comcarde Apple Pay Create Method#

The Comcarde Apple Pay .create() method expects an object as shown below:

...comcarde.applePay.create({   client: clientInstance,   button: {      container: 'apple-pay-button',      style: 'black',      type: 'buy'   }})...

The object has both required and optional parameters, as detailed below:

  • client (required): This is an instance of the comcarde client used in all optional payment modules.
  • button (required): This is an object that will tell the SDK how and where you want to button to render
  • button.container (required): This is the id attribute of the element you wish to have the Apple Pay button render into. This should match the id attribute of the HTML placeholder element you added earlier.
  • button.style (optional): This is the style type of button you wish to support. Accepted options are:
    • black (default)
    • white
    • white-with-line
  • button.type (optional): This is the type of button you wish the use. The accepted options are:
    • plain
    • add-money
    • book
    • buy (default)
    • check-out
    • contribute
    • donate
    • order
    • reload
    • rent
    • set-up
    • subscribe
    • support
    • tip
    • top-up

Comcarde Apple Pay Start Session Method#

The Comcarde Apple Pay .startSession() method will initiate a new ApplePay session:

...applePayClientModule.startSession({  label: 'A Shortened Order Description',  type: 'final',  amount: '10.00'} ...
  • label (required): A quick description of what is being purchased.
    • This is displayed to the end user as part of their checkout experience in Apple Pay
  • type (required): This should be set to final and not changed
  • amount (required): A decimal representation of the total checkout price (e.g., 10.25)
    • This is displayed to the end user as part of their checkout experience in Apple Pay

Errors#

If an error occurs during interaction with comcarde-web and it is caught by your code, the error will consist of a default textual error message describing at a high level what went wrong, and also a code which should not be returned to the user but which can be mapped to a different error message should you wish to override the default error message.

For example, if hosted fields are included in your page and they are submitted without all required values being entered, an error will be thrown by comcarde-web, containing these values:

{  code: 'HOSTED_FIELDS_FIELDS_EMPTY',  message: 'Please enter all the requested card information.'}

The 'message' field specifies the default error message, which should be suitable to be returned to the user, but it is preferable to map the 'code' field to an error message of your own that is bespoke to your site.