Javascript Setup

All the Charge payment forms require javascript for payment card tokenisation.

The exact setup is flexible, and can be adjusted for your required usage and how you're building your front-end assets and templates

Using Stripe Checkout? You can skip the JS! When using Charge with Stripe Checkout you don't need to and any javascript to your pages. Charge will handle everything under the hood including all the public key setup and event binding. Just use the {{ craft.charge.setCheckoutOptions(..) }} tag and we'll do the rest.

Add the JS assets #

You need to add 4 javascript parts to your page. They are:

  1. jQuery.
  2. The Stripe v2 library
  3. The Charge library
  4. Your on-page js init.

It'd look like this:

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
{% includeJsResource('charge/js/stripe_v2.min.js') %}
{% includeJsResource('charge/js/jquery.charge.js') %}
{% includejs %}
    $(this).charge();
{% endincludejs %}

 Define your Public Key #

You can define the Stripe Public Key on the page in two ways.

  • Define it as a data attribute called data-publicKey on your payment form.
  • Assign it directly to the Stripe object in you init js.

We recommend assigning it via the data attribute to keep your on page js as clean as possible. This approach also allows you to fully enclose the js into any other packaged and minified site js libraries you might have.

Defined via data-publicKey

This is the simplest way. With this approach your payment form opening tag would look like this:

<form id="charge-form" method="post" data-publicKey ="{{ craft.charge.publicKey }}">
    ...

Defined in your init JS

Alternatively you can define it on page after you've loaded the Stripe library. That looks like this:

{% includejs %}
    Stripe.setPublishableKey('{{ craft.charge.getPublicKey() }}');
    $(this).charge();
{% endincludejs %}

Charge Config Options #

By default the charge javascript library will look for the following default containers on the payment page:

  • The payment form with an id of charge-form.
  • An error container with an id of payment-errors.
  • A progress indicator with a class of charge_indicator.
  • The Stripe public key on the form via a data attribute called data-publicKey.

You can override these defaults by passing a config array to the $(this).charge(); method. Like so:

$(this).charge({ 
   form : $('#some-other-form'), 
   error_container: $('#custom-errors'), 
   progress: $('.custom-progress')
   publicKey: 'pk_xxxxxxxxxx'
});

Upgrading from 1.x? We've improved how our js library accepts it's options. The legacy approach of $(this).charge('#custom-form', '#customer-errors', '.custom-progress'); still works though!