Overview

Reference

Using Chargify.js

Chargify.js is a powerful tool that can be used to streamline your existing API-based workflows in Chargify. Chargify.js can be used to easily contruct signup and payment profile updates on your existing sites.

Creating New Subscriptions

Use Chargify.js to allow new subscribers to securely enter their payment information from your site. Instead of sending a credit_card_attribute with your POST to the /subscriptions endpoint, your workflow will closely follow this outline:

  • A potential subscriber will complete a payment-based form on your site
  • Chargify returns a one-time token for you to use to complete the subscription request to the /subscriptions endpoint

Updating Existing Payment Methods

In addition to creating new subscribers, use Chargify.js to create new payment methods. This workflow allows your existing subscribers to enter new card information on your site. From here, you’ll use the token to send a POST to the /payment_profiles to create a new payment method.

  • An existing subscriber completes a payment-based form on your site, for the purpose of adding a new credit card to their account
  • Chargify returns a one-time token to use for adding a new payment method to an existing subscription
Chargify.js is not compatible with updating existing credit cards in Chargify. You may only add new cards to existing subscriptions, or create new subscriptions with recently tokenized card.

How it Works

Chargify provides transparent iframes that allow you to customize a customer’s payment form. This approach ensures the you meet the latest PCI compliance requirements.

When a customer submits your payment form, Chargify.js sends the customer payment information to be securely stored in your payment gateway. In return, a one-time token is generated for you to use to complete the subscription process using our API. The one-time-payment token references the payment information that is securely stored in your gateway.

With this token you can create a subscription or payment profile assigned to the customer. Your PCI is significantly reduced, because of you don’t pass any sensitive payment information. An example API call to the subscriptions endpoint would take the following form:

{
  "subscription": {
    "product_handle": "pro-plan",
    "customer_attributes": {
      "first_name": "Joe",
      "last_name": "Smith",
      "email": "j.smith@example.com"
    },
    "credit_card_attributes": {
      "chargify_token": "tok_cwhvpfcnbtgkd8nfkzf9dnjn"
    }
  }
}

Getting Started

To begin using Chargify.js, include the chargify.js script on your page. This exposes a single global object, chargify.

__

<script src="https://js.chargify.com/latest/chargify.js"></script>

It is strongly recommended to use the latest Chargify-hosted version of Chargify.js. This version is regularly updated to be compatible with the rest of the system. Using a locally hosted version of Chargify.js may introduce a risk become incompatible with our servers. We strongly recommend against this practice.

Single Page Applications

As of 2019-02-05 Chargify.js works with reactive frameworks like React or Angular.

We published 2 repositories with sample apps that demonstrate how to use Chargify.js with those frameworks:

Hosting and Technical Considerations

The static files on https://js.chargify.com are hosted via AWS Cloudfront. They use a different set of HTTP & TLS specifications than https://app.chargify.com. As such, their compatibility with various browsers and clients may be different. It also may be affected by different failures than our primary app.

Specific technical considerations to be aware of:

  • TLS is terminated by Cloudfront using the TLSv1.2_2018 config. TLS 1.0 and TLS 1.1 are not supported. The full cipher suite list is available from AWS
  • Utilizes SNI for TLS, which can result in lower compatibility with browsers than the Chargify application. Akamai has published a study describing the evolution of browser support for SNI and it is very high, but not perfect.
  • Supports HTTP/2, HTTP/1.1, HTTP/1.0
  • Through the use of AWS Cloudfront, https://js.chargify.com is designed for maximum reliability and speed, but is not covered by our SLA, uptime, or performance guarantees.
When you use Chargify.js, your workflow is classified as SAQ-A. For more information, please see our documentation on PCI compliance.

Configuration

Common configuration options

Call chargify.load anywhere on your page. It’s that simple!

chargify.load({
    // selector, where the iframe will be included on your page
    // optional, if you have a `selector` for every field ('fields' option)
    selector: '#chargify-form',

    // (i.e. '1a2cdsdn3lkn54lnlkn')
    publicKey: 'your-public-api-key',

    // form type (possible values: 'card', 'bank' or 'gocardless')
    type: 'card',

    // points to your Chargify site
    serverHost: 'https://acme.chargify.com'
});

You can find your public API key in the Config –> Integrations section on your site’s page in Chargify.

chargify.load accepts also optional parameters. Here is the complete example:

chargify.load({
    // selector, where the iframe will be included on your page
    // optional, if you have a `selector` for every field ('fields' option)
    selector: '#chargify-form',

    // (i.e. '1a2cdsdn3lkn54lnlkn')
    publicKey: 'your-public-api-key',

    // form type (possible values: 'card', 'bank' or 'gocardless')
    type: 'card',

    // points to your Chargify site
    serverHost: 'https://acme.chargify.com',

    // flag to show/hide the credit card image
    // true: hides the credit card image
    // visible otherwise
    hideCardImage: false,

    // optional label/translation (i.e. '(optional field)') for optional fields
    // Especially useful if you use 'fields' option
    optionalLabel: '(optional field)',

    // required label/translation (i.e. '*') for required fields
    // Especially useful if you use 'fields' option
    requiredLabel: '*',

    // optional global styles that include iframe styles,
    // styles for fields, inputs, labels and messages
    style: {
        // to style an iframe, use the iframe's container selector
        '#chargify-form': { border: '1px dashed #ffc0cb57' },

        // `field` is the container for each field
        field: {
            backgroundColor: 'orange',
            paddingTop: '10px',
            paddingBottom: '10px',
            borderRadius: '5px'
        },

        // `input` is the input HTML element
        input: {
            backgroundColor: '#e6e6e6',
            paddingTop: '2px',
            paddingBottom: '1px',
            placeholder: { color: '#eee' }
        },

        // `label` is the label container
        label: {
            backgroundColor: 'lightblue',
            paddingTop: '2px',
            paddingBottom: '1px'
        },

        // `message` is the invalid message container
        message: {
            backgroundColor: 'red',
            color: 'white',
            paddingTop: '2px',
            paddingBottom: '1px'
        }
    },

    // use this option if you want to include each field
    // in the separate iframe
    fields: {}
});

Specific configuration options for GoCardless

chargify.load({
    // selector, where the iframe will be included on your page
    // optional if you have a `selector` on each and every field
    selector: '#chargify-form',

    // (i.e. '1a2cdsdn3lkn54lnlkn')
    publicKey: 'your-public-api-key',

    // form type (possible values: 'card', 'bank' or 'gocardless')
    type: 'gocardless',

    // selector for GoCardless header
    // that should make the page identifiable to customers
    selectorForGoCardlessHeader: '#gocardless-header',

    // selector for GoCardless footer that should make customers aware
    // that payments are powered by GoCardless
    selectorForGoCardlessFooter: '#gocardless-footer',

    // selector for adding link to switch between IBAN and local bank details
    // (this link will be automatically added after account number
    // if selector is not present)
    //selectorForToggleIbanOrLocalDetails: '#gocardless-toggle-iban',

    // if you want to add your custom styles for GoCardless modal,
    // set this to true to skip automatic injection of CSS styles
    //customGoCardlessModalStyles: true,

    // points to your Chargify site
    serverHost: 'https://acme.chargify.com',
});

Available Fields

Credit Card

Field name Example Required Description
firstName Joe Optional Cardholder first name
lastName Doe Optional Cardholder last name
number 4242 4242 4242 4242 Required Credit card number
month 08 Required Card expiration month
year 2022 Required Card expiration year
cvv 123 Optional (may be required by your gateway settings) The 3- or 4-digit Card Verification Value. This value is merely passed through to the payment gateway
address 123 Main St. Optional (may be required by your gateway settings) The credit card or bank account billing street address. This value is merely passed through to the payment gateway
address2 i.e. Apt. 100 Optional Second line of the customer’s billing address
city Boston Optional (may be required by your gateway settings) The credit card billing address city. This value is merely passed through to the payment gateway
state MA Optional (may be required by your gateway settings) The credit card billing address state, preferably in 2-letter format. This value is merely passed through to the payment gateway
zip 12345 Optional (may be required by your gateway settings) The credit card billing address zip code. This value is merely passed through to the payment gateway
country US Optional (may be required by your gateway settings) The credit card billing address country, preferably in ISO 3166-1 alpha-2 format. This value is merely passed through to the payment gateway. Some gateways require country codes in a specific format. Please check your gateway’s documentation

ACH

Field name Example Required Description
firstName Joe Optional First name on bank account
lastName Doe Optional Last name on card or bank account
bankName Test Bank Required The name of the bank where the customer’s account resides
routingNumber 110000000 Required The routing number of the bank
accountNumber 000123456789 Required The customer’s bank account number
accountType checking ——– this defaults to checking and cannot be changed
accountHolderType personal Required may be personal (default) or business
address 123 Main St. Optional may be required by your product configuration or gateway settings The bank account billing street address (i.e. 123 Main St.). This value is merely passed through to the payment gateway
address2 Apt. 100 Optional Second line of the customer’s billing address
city Boston Optional (may be required by your product configuration or gateway settings) The bank account billing address city. This value is merely passed through to the payment gateway
state MA Optional (may be required by your gateway settings) The bank account billing address state, preferably in 2-letter format. This value is merely passed through to the payment gateway
zip 12345 Optional (may be required by your gateway settings) The bank account billing address zip code. This value is merely passed through to the payment gateway
country US Optional (may be required by your gateway settings) The bank account billing address country, preferably in ISO 3166-1 alpha-2 format. This value is merely passed through to the payment gateway. Some gateways require country codes in a specific format. Please check your gateway’s documentation

GoCardless

Field name Example Required Description
firstName Joe Required First name on bank account
lastName Doe Required Last name on bank account
email joe@chargify.test Required for Becs NZ scheme only The customer’s email
phone +640800000000 Required for Becs NZ scheme only The customer’s phone number
bankName Test Bank Required The name of the bank where the customer’s account resides
bankIban FR1420041010050500013M02606 Required The customer’s International Bank Account Number (IBAN). It needs to be passed if local bank details are empty
routingNumber 19043 Required Bank code. Alternatively you can provide an iban.
branchCode 200000 Required Branch code. Alternatively you can provide an iban.
accountNumber 55779911 Required The customer’s bank account number. Alternatively you can provide an IBAN.
accountHolderType personal Required may be personal (default) or business
address 123 Main St. Required The bank account billing street address (i.e. 123 Main St.). This value is merely passed through to the payment gateway
address2 Apt. 100 Optional Second line of the customer’s billing address
city London Required The bank account billing address city.
state LND Required The bank account billing address state, in 2 or 3-letter format.
zip E1W 3SS Required The bank account billing address zip code.
country GB Required The bank account billing address country, in ISO 3166-1 alpha-2 format.
swedishIdentityNumber 198112289874 Required for Autogiro scheme only The Swedish civic/identity number
danishIdentityNumber 0101701234 Required for Betalingsservice scheme only The Danish civic/identity number

Working with Fields

If you want to display each field in a separate iframe, all you have to do is to skip a selector option and define a fields option instead. Minimum requirement is to specify all required fields via the fields option.

  // ...

  fields: {
      // ...

      firstName: {
          // selector where the iframe with this field will be included on your page
          selector: '#chargify4',

          // ot overrides default label
          label: 'FIRST NAME',

          // it overrides default placeholder
          placeholder: 'John',

          // if a given field is optional by default, you can make it required
          required: true,

          // it overrides default error message
          message: 'First name is not valid. Please update it.',

          // it overrides or defines max length
          maxlength: '30',

          // it overrides global styles for this field only
          style: {
              field: {
                  backgroundColor: '#f0dfdf',
                  padding: '3px',
                  borderRadius: '5px'
              },
              input: {
                  backgroundColor: '#f0fde1',
                  paddingTop: '2px',
                  paddingBottom: '1px',
                  placeholder: { color: '#eee' }
              },
              label: { paddingTop: '2px', paddingBottom: '1px', fontSize: '11px' },
              message: { paddingTop: '2px', paddingBottom: '1px' }
          }
      }
  }

Getting a Chargify Token

First, include Chargify iframe(s) inside a form:

<!DOCTYPE html>
<html>
    <head>
        <script src="https://your-page.com/chargify.js"></script>
    </head>

    <body>
        <form id='chargify-form'>
            <div id="chargify1"></div>

            <input id="chargify-token" type="hidden" />

            <button type="submit">Submit Form</button>
        </form>
    </body>

    <script>
        var chargify = new Chargify();

        chargify.load({
            // selector, where the iframe will be included on your page
            // optional, if you have a `selector` for every field ('fields' option)
            selector: '#chargify1',

            // (i.e. '1a2cdsdn3lkn54lnlkn')
            publicKey: 'your-public-api-key',

            // form type (possible values: 'card' or 'bank')
            type: 'card',

            // points to your Chargify site
            serverHost: 'https://acme.chargify.com'
        });
    </script>
</html>

Then you have to interrupt the submission of the form to send billing info to Chargify and get a one time token in exchange. Once you have the token, submit the form to your server.

document.querySelector('#chargify-form').addEventListener('submit', function(event) {
    var form = this;

    event.preventDefault();

    chargify.token(
        form,
        function success(token) {
            // optionally, you can assign a chargify token to a hidden field
            // or pass it to your backend in other way
            document.querySelector('#chargify-token').value = token;

            // and then submit the form
            form.submit();
        },
        function error(err) {
            // be aware that an error can occur for different reasons
            // while saving billing info in the gateway or directly
            // on the Chargify backend. It is rare but still possible.
            // Remember to make the user aware the presence of an error
            console.log('token ERROR - err: ', err);
        }
    );
});

After you get the token, you will submit it to your server and use it while creating a subscription or payment profile using our API.

Tokens expire after 20 minutes.

Handling Errors

When an error occures on the back-end side, the error callback is invoked with the object having 2 properties:

{
    status: 400, // HTTP status
    errors: "Your card was declined." // it can be an array of errors as well
}