SDK Integration

Getting started with ChargeAfter SDK

ChargeAfter SDK is non-obtrusive by design, light-weight (30KB), and loads asynchronously in order to prevent the possibility of slowing down the containing website.

NPM Integration

The preferred method of integrating the ChargeAfter SDK is via NPM.

Our NPM package is always up-to-date and is strongly typed (Typescript) for an optimized modern framework.

Installing

// using NPM
npm install @chargeafter/payment-sdk

// using yarn
yarn add install @chargeafter/payment-sdk

Methods of Usage

Our NPM package is usable in one of two ways:

  • Method 1: Import the initialize method and use it to create an SDK instance (Preferred)
  • Method 2: Import checkout and prequalify which accept initialization parameters, and use directly.
import { EnvironmentType, initialize } from "@chargeafter/payment-sdk";
import * as React from "react";
import * as ReactDOM from "react-dom";

const CheckoutButton = () => {
  const cfg = {
    //optional - use in case of more than a single store
    storeId: "<storeId>",
    apiKey: "<your api key>",
    // Optional:
    delegatedMerchantId: "<merchant id to act on behalf of>",
    // Optional:
    preferences: {
      // Optional: default en
      language: "en",

      // Optional: true/false to opt in to marketing or optout
      marketingOptIn: true,

      // Optional:
      currency: "<merchant currency, e.g USD>",

      // Optional:
      // used to determine language and currency
      // if they are not provided
      country: "<merchant country>"
    }
  };
  const onClick = async () => {
    try {
      // initialize is called with config as first parameter, and environment name as second.
      // if not passed, production is assumed.
      const caObject = await initialize(cfg, "sandbox");
      
      // caObject.payments.present("apply");
      // caObject.payments.present("checkout", {
      //   callback: () => {},
      //   cartDetails: {
      //     items: [],
      //     taxAmount: 5,
      //     shippingAmount: 6,
      //     totalAmount: 7
      //   }
      // });
      
    } catch (ex) {
      console.log(ex.message);
    }
  };
  return (
    <button onClick={onClick}>
      Click to checkout
    </button>
  );
};
import { checkout, ICheckoutProps } from "@chargeafter/payment-sdk";

const checkoutButton = () => {
  const cfg: ICheckoutProps = {
    config: {
      //optional - use in case of more than a single store
      storeId: "<storeId>",
      env: {
        name: "qa",
        apiKey: "<your api key>"
      }
    },
    callback: () => {},
    cartDetails: {
      items: [],
      taxAmount: 5,
      shippingAmount: 6,
      totalAmount: 7
    }
  };
  const onClick = async () => {
    try {
      const { consumerId } = await checkout(cfg);
      console.log(consumerId);
    } catch (ex) {
      console.log(ex.message);
    }
  };
  return <button dataButtonType="small-generic" onClick={onClick}>Click to checkout</button>;
};

All types are exported from the package for your convenience.

See the following sections for the Apply and Checkout functionalities.

HTML Integration

If an NPM integration (preferred by ChargeAfter) is not possible, you can use an HTML integration.

The minimum requirements are a public API key provided by ChargeAfter.

The code snippet below shows how to add the ChargeAfter Payment SDK to your website.

Code samples

<html>
<body>
    <script>
        // the script goes to the end of the body section
        function onLoadChargeAfterSDKScript() {
            var config = {
                // Required: if not provided the SDK will not be initilized
                apiKey: 'public-api-key',

                // Optional
                storeId: 'your-store-id',

                // Optional
                delegatedMerchantId: '<merchant id to act on behalf of>',

                // Optional
                onLoaded: function() {
                    // now we can work with chargeafter sdk
                    // ChargeAfter.payments.present('apply')
                    // ChargeAfter.payments.present('checkout',{...})

                    // not required, automaticly handled by the SDK and widget
                    // ChargeAfter.promotions.present('sku')
                },
                
                // Optional functionality that triggers when user flow finishes 
                // and modal closes
                onComplete: function(payload, context) {
                  // payload includes same data as Apply/Checkout callbacks
                  const {data, status, token} = payload;
                  // 'APPLY' | 'CHECKOUT' 
                  const source = context.source;
                  
                  /**
                    only applicable for applications initiated from widget
                    sku?: string;
                    price?: string | number;
                    category?: string;
                    tag?: string;
                  */
                  const promotion = context.promotion;
                }
            };

            ChargeAfter.init(config);
        }

        var script = document.createElement('script');
        script.src = 'https://cdn.chargeafter.com/web/v2/chargeafter.min.js?t=' + Date.now();
        script.type = 'text/javascript';
        script.async = true;
        script.onload = onLoadChargeAfterSDKScript;
        document.body.appendChild(script);
    </script>
</body>
</html>
<html>
<body>
    <script>
        // the script goes to the end of the body section
        function onLoadChargeAfterSDKScript() {
            var config = {
                // Required: if not provided the SDK will not be initilized
                apiKey: 'sandbox-api-key',
               
                // Optional:
                storeId: 'your-store-id',

                // Optional:
                delegatedMerchantId: '<merchant id to act on behalf of>',

                // Optional: 
                onLoaded: function() {
                    // now we can work with chargeafter sdk
                    // ChargeAfter.payments.present('apply')
                    // ChargeAfter.payments.present('checkout',{...})

                    // not required, automaticly handled by the SDK and widget
                    // ChargeAfter.promotions.present('sku')
                },
              
                // Optional functionality that triggers when user flow finishes 
                // and modal closes
                onComplete: function(payload, context) {
                  // payload includes same data as Apply/Checkout callbacks
                  const {data, status, token} = payload;
                  // 'APPLY' | 'CHECKOUT' 
                  const source = context.source;
                  
                  /**
                    only applicable for applications initiated from widget
                    sku?: string;
                    price?: string | number;
                    category?: string;
                    tag?: string;
                  */
                  const promotion = context.promotion;
                }
            };

            ChargeAfter.init(config);
        }

        var script = document.createElement('script');
        script.src = 'https://cdn-sandbox.ca-dev.co/web/v2/chargeafter.min.js?t=' + Date.now();
        script.type = 'text/javascript';
        script.async = true;
        script.onload = onLoadChargeAfterSDKScript;
        document.body.appendChild(script);
    </script>
</body>
</html>

Properties

ChargeAfter Object

FieldTypeDescription
initfunctionInitializes the ChargeAfter flow and receives config object. See Config object below.
cfgobjectReferences to the config the merchant has provided ChargeAfter
in the init function. See Config object below.
paymentsobjectRepresents the payments flows: Apply and/or Checkout.
Example: ChargeAfter.payments.present('apply')
promotionsobjectHolds the widget and promotions, updating the widgets with new prices or opening the Promotion Modal manually.
Example: ChargeAfter.promotions.update([...items]);
getDirectLendersfunctionReturns a promise which resolves an array of lenders that are defined as direct lenders and can be launched directly.
eligibilityobjectRepresents the ability to present a widget in iframe for checking eligibility with a specific lender.
poweredByLogofunctionGets the URL of the "powered by" logo used by ChargeAfter.
disposefunctionManually removes all resources ChargeAfter is using including the modal iframe.
preferencesobject (Optional)See Preferences object below.

Config Object

FieldTypeDescription
apiKeystring (Required)Public API key provided by ChargeAfter.
storeIdstring (Optional)An id used to identify a specific store in case the merchant has more than one.
delegatedMerchantIdstring (Optional)The merchant id that partners can use to tell ChargeAfter to which merchant the flow is referring.
onLoadedfunction (Optional)Event callback that fires when ChargeAfter finishes the initialization process.
preferencesobject (Optional)See Preferences object below.
onCompletefunction (Optional)Callback that will be executed on modal closure.

Preferences object

FieldTypeDescription
currencystring (Optional)The currency to show to the consumer in the ChargeAfter modal
Default: ‘USD’
countrystring (Optional)The country in which the merchant operates
languagestring (Optional)The language to present to the consumer in the ChargeAfter modal
Default: 'en'
marketingOptInboolean (Optional)Opts in the consumer to marketing.
Default: true

👍

Testing the integration

Change cdn.chargeafter.com to cdn-sandbox.ca-dev.co, and use your testing credentials to access our sandbox environment. Please refer to the sandbox environment instructions for more details.

A sandbox (test environment) URL should be provided to you together with your sandbox credentials.


What’s Next