Accept Signups with Chargifyjs

This implementation guide will walk you through the process of building a Chargifyjs payment page. When you’re finished, you will have a working Chargifyjs payment page.

Website Web App


Summary

Chargify Feature
Chargifyjs
You Need
A website or web app; a localhost development environment; developer experience with Javascript and APIs
Code
Yes
Difficulty

Implement Chargifyjs on your Website Try it out Diagram

Chargifyjs on websites is ideal when a user is not logged in. In this walkthrough, we'll build a functioning Chargifyjs signup page for credit cards.

1. Set up Chargify
  1. Know your Subdomain
    In your Chargify Site URL, you'll see: https://SUBDOMAIN.chargify.com

  2. Get your Chargifyjs Public Key
    In your Chargify Site, go to Config > Integrations > Chargify.js

  3. Get your Chargify API Key
    In your Chargify Site, go to Config > Integrations > API Keys
2. Build your signup page  HTML JS CSS
To start, you need a web form. You can either use an existing form, create a form from scratch, or use a prebuilt example from the Examples Section. In this implementation guide, we will be using the HTML+JS prebuilt example.

  1. Set up your file directory
    yourfolder
        - signup.html > your signup page
        - load.js > your chargifyjs configuration
        - submit.js > your form submit
        - styles.css > your additional form styling

  2. Add your code
    When you're done, load on localhost. Keep in mind, the form will not render until you add your real credentials in the next step.
signup.html load.js submit.js styles.css
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- include chargifyjs -->
    <script src="https://js.chargify.com/latest/chargify.js"></script>
    <!-- Chargifyjs custom CSS (modify as needed) -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" />
    <!-- Chargifyjs custom CSS (modify as needed) -->
    <link rel="stylesheet" href="styles.css" />
  </head>
  <body class="bg-light">
    <header>
      <div class="navbar navbar-dark bg-dark shadow-sm">
        <div class="container">
          <a href="#" class="navbar-brand d-flex align-items-center">
            <strong>Chargifyjs Signup - CC with Billing Address</strong>
          </a>
        </div>
      </div>
    </header>
    <div class="container">
      <main>
        <div class="py-5 text-center">
          <h2>PRODUCT NAME</h2>
          <p class="lead">Chargifyjs Signup - CC with Billing Address</p>
        </div>
        <div class="row g-5">
          <div class="col-md-5 col-lg-4 order-md-last">
            <h4 class="d-flex justify-content-between align-items-center mb-3">
              <span>Summary</span>
            </h4>
            <ul class="list-group mb-3">
              <li class="list-group-item d-flex justify-content-between lh-sm">
                <div>
                  <h6 class="my-0">PRODUCT NAME</h6>
                </div>
                <span class="text-muted">$AMOUNT-IN-CENTS/100 /mo</span>
              </li>
              <li class="list-group-item d-flex justify-content-between">
                <span>Today's Total</span>
                <strong>$TOTAL-IN-CENTS/100</strong>
              </li>
            </ul>
          </div>
          <!-- load spinner -->
          <div id="load_spinner" class="d-flex justify-content-center">
            <div class="spinner-border" role="status">
              <span class="sr-only"></span>
            </div>
          </div>
          <!-- error banner -->
          <div class="alert alert-danger" role="alert" id="chargify-error-message" style="display:none;"></div>
          <div class="col-md-7 col-lg-8">
            <h4 class="mb-3">Customer Information</h4>
            <form id="chargify-form" action="/website-chargifyjs-ify/create_subscription" method="POST" style="display:none;">
              <div class="row g-3">
                <div class="col-sm-6">
                  <label for="companyName" class="form-label">Company</label>
                  <input type="text" class="form-control" id="company" name="company" placeholder="" value="" required>
                  <div class="invalid-feedback">
                    Valid first name is required.
                  </div>
                </div>
                <div class="col-sm-6">
                  <label for="companyEmail" class="form-label">Email</label>
                  <input type="email" class="form-control" id="email" name="email" placeholder="" value="" required>
                  <div class="invalid-feedback">
                    Valid last name is required.
                  </div>
                </div>
                <div class="col-sm-6">
                  <label for="firstName" class="form-label">Contact First name</label>
                  <input type="text" class="form-control" id="firstName" name="first_name" placeholder="" value="" required>
                  <div class="invalid-feedback">
                    Valid first name is required.
                  </div>
                </div>
                <div class="col-sm-6">
                  <label for="lastName" class="form-label">Contact Last name</label>
                  <input type="text" class="form-control" id="lastName" name="last_name" placeholder="" value="" required>
                  <div class="invalid-feedback">
                    Valid last name is required.
                  </div>
                </div>
              </div>
              <!-- end -->
              <hr class="my-4">
              <h4 class="mb-3">Payment</h4>
              <div class="row g-3">
                <div class="col-md-6 col-sm-12">
                  <div id="cc_first_name"></div>
                </div>
                <div class="col-md-6 col-sm-12">
                  <div id="cc_last_name"></div>
                </div>
                <div class="col-md-6 col-sm-12">
                  <div id="cc_number"></div>
                </div>
                <div class="col-md-6 col-sm-12">
                  <span id="cc_month"></span>
                  <span id="cc_year"></span>
                  <span id="cc_cvv"></span>
                </div>
              </div>
              <!--end -->
              <hr class="my-4">
              <h4 class="mb-3">Billing Address</h4>
              <div class="row g-3">
                <div class="col-md-6 col-sm-12">
                  <div id="cc_billing_address"></div>
                </div>
                <div class="col-md-6 col-sm-12">
                  <div id="cc_billing_address2"></div>
                </div>
                <div class="col-md-6 col-sm-12">
                  <div id="cc_billing_city"></div>
                </div>
                <div class="col-md-6 col-sm-12">
                  <div id="cc_billing_zip"></div>
                </div>
                <div class="col-md-6 col-sm-12">
                  <div id="cc_billing_country"></div>
                </div>
                <div class="col-md-6 col-sm-12">
                  <div id="cc_billing_state"></div>
                </div>
              </div>
              <!-- end -->
              <hr class="my-4">
              When you submit the form, Chargifyjs will generate a token, and place it in the input box below. Hide this box in a real form.</br></br>
              <input id="product_handle" name="product_handle" type="text" value="HIDDEN PRODUCT HANDLE HERE" />
              <input id="chargify-token" name="chargify_token" type="text" />
              <button class="w-100 btn btn-primary btn-lg" type="submit">Subscribe</button>
            </form>
          </div>
        </div>
      </main>
    </div>
    <!-- JavaScript (jquery/bootstrap) -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
    <!-- Javascript (Chargifyjs load and submit files) -->
    <script src="load.js"></script>   <!-- This contains your Chargify.js file -->
    <script src="submit.js"></script>  <!-- This pauses form submission to create a token -->
    <!-- Smooth form load -->
    <script>
      setTimeout(function () {
          $("#load_spinner").remove();
          $("#chargify-form").show();
      }, 100);
    </script>
  </body>
</html>
3. Add credentials and start customizing
Next, let's configure your chargifyjs public credentials, payment method type, iframed fields, iframed field stylings, and more.

  1. Add your Chargifyjs credentials in the load.js file
    In load.js, update these:
    a) Update PublicKey with the Chargifyjs Public Key you created in Step 1.1, and 
    b) Update ServerHost with the Subdomain from Step 1.1


  2. Customize chargify.load (as needed)
    View more documented examples

  3. Configure Styling (as needed)
    Within chargify.load, there is a style object, which controls the styling of the iframed fields. In the load.js example file, you will see many values set to null to help guide you. Replace the null values, with real values, as needed, once your form is fully functional.

  4. Add secure iframed fields (as needed)
    The load.js file tells Chargifyjs what iframed fields to display on your web form. This is done by including fields (billing address, billing city, etc) in your chargify.load function, and those fields map to div IDs in your frontend form. Use the image below, alongside the 5 steps, to guide you.

    chargifyjs-divid-example.png

    1. Add a supported field to the load.js file, such as number. You will add these fields in the fields object.
    2. Set the selector to any ID you’d like, such as #cc_number.
    3. In the signup.html file, add a div with the matching selector, such as <div id="cc_number"></div>
    4. When you load your page, assuming no errors in your chargify.load function, the secure field will be iframed into your web form.
    5. Repeat for any field you would like to add. For full examples, see below.

4. Submit the form to your server

If using example from Frontend Implementation section
1. Go into submit.js and uncomment form.submit();
2. Go into signup.html, find the input chargify-token and change 'text' to 'hidden'

If not
If you are not using the example code, just make sure your form can successfully submit and POST to your servers.

5. Create the subscription Server-side API
Use the Create Subscription endpoint and pass the chargifyjs token as the payment method.

Credit Card Bank Account Paypal Other

Credit Card With Product
// EXAMPLE: Chargifyjs for Credit Cards - Create Subscription with Product
// ENDPOINT: POST /subscriptions.json
// DOCS: https://developers.chargify.com/docs/api-docs/b3A6MTQxMDgzODg-create-subscription

// REQUEST BODY
{
  "subscription": {
    "product_handle": "gold-plan", //a valid product handle from your catalog
    "customer_attributes": {
      "first_name": "Christopher",
      "last_name": "Adil",
      "email": "christopher.adil@example.com",
      "organization": "Varity LLC"
    },
    "credit_card_attributes": {
      "chargify_token": "tok_mzvtmcv2hgtxj9sb7qq5kphc", //the chargifyjs token generated from your form
      "payment_type": "credit_card"
    }
  }
}

Credit Card With Components
// EXAMPLE: Chargifyjs for Credit Cards - Create Subscription with Components
// ENDPOINT: POST /subscriptions.json
// DOCS: https://developers.chargify.com/docs/api-docs/b3A6MTQxMDgzODg-create-subscription

// REQUEST BODY
{
  "subscription": {
    "product_handle": "gold-plan", //a valid product handle from your catalog
    "customer_attributes": {
      "first_name": "Christopher",
      "last_name": "Adil",
      "email": "christopher.adil@example.com",
      "organization": "Varity LLC"
    },
    "components": [                              
      {
        "component_id": "handle:24-7-support",  //a valid component handle from your catalog
        "allocated_quantity": 1
      },
      {
        "component_id": "handle:automated-backups", //a valid component handle from your catalog
        "allocated_quantity": 25
      }
    ],
    "credit_card_attributes": {
      "chargify_token": "tok_mzvtmcv2hgtxj9sb7qq5kphc", //the chargifyjs token generated from your form
      "payment_type": "credit_card"
    }
  }
}

Credit Card With Existing Customer
// EXAMPLE: Chargifyjs for Credit Cards - Create Subscription with Existing Customer
// ENDPOINT: POST /subscriptions.json
// DOCS: https://developers.chargify.com/docs/api-docs/b3A6MTQxMDgzODg-create-subscription

// REQUEST BODY
{
  "subscription": {
    "product_handle": "gold-plan", //a valid product handle from your catalog
    "customer_reference": "HhypUAwhew4HLwGtmOBxdGx9", //an existing user ID. if none exists, pass the Chargify customer_id
    "credit_card_attributes": {
      "chargify_token": "tok_mzvtmcv2hgtxj9sb7qq5kphc",  //a unique reference value belonging to an existing customer
      "payment_type": "credit_card"
    }
  }
}
6. Test and add final touches
Finally, it's time to test your full Chargifyjs implementation and add the final touches.

  1. Test the frontend
    The form should load, a token should generate, and you should test token generation errors. If you are connected to the Chargify Test Gateway, use a card number of 2 or 3 to simulate an error.

  2. Add subscription creation errors and test
    Test a failed API call to Chargify. For example, break the API call on purpose, to test how your implementation responds to that error. Pass the error back to your front end. This is how your users will see errors such as 'insufficient funds', 'declined card', etc.

  3. Add a redirect and test success
    On success, a user should be redirected successfully, and the entire flow should make sense start to finish.
Optional - Create a subscription preview Server-side API

Before your signup page loads, make an API call to gather the subscription preview data (product name, cost, any taxes, etc), and pass it to the front end. 

  1. Make a subscription preview API call   See the endpoint
    // Example json to preview a product
    {
      subscription: {
        product_handle: 'pro'
      }
    }
    
  2. Pass and display the data to your front end
    In the sample signup page, you'll see placeholders for PRODUCT NAME, AMOUNT-IN-CENTS, TOTAL-IN-CENTS. Replace these with the parsed values from the subscription preview. Add more fields as you see fit.

Implement Chargifyjs in your Web App Try it out Diagram

Chargifyjs in web apps is ideal when a user is logged in. In this walkthrough, we'll build a functioning Chargifyjs signup page for credit cards.

1. Set up Chargify
  1. Know your Subdomain
    In your Chargify Site URL, you'll see: https://SUBDOMAIN.chargify.com

  2. Get your Chargifyjs Public Key
    In your Chargify Site, go to Config > Integrations > Chargify.js

  3. Get your Chargify API Key
    In your Chargify Site, go to Config > Integrations > API Keys
2. Build your signup page  HTML JS CSS
To start, you need a web form. You can either use an existing form, create a form from scratch, or use a prebuilt example from the Examples Section. In this implementation guide, we will be an HTML+JS prebuilt example, that collects credit card, and assumes your customer is logged in to your app, 

  1. Set up your file directory
    yourfolder
        - signup.html > your signup page
        - load.js > your chargifyjs configuration
        - submit.js > your form submit
        - styles.css > your additional form styling

  2. Add your code
    When you're done, load on localhost. Keep in mind, the form will not render until you add your real credentials in the next step.
signup.html load.js submit.js styles.css
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- include chargifyjs -->
    <script src="https://js.chargify.com/latest/chargify.js"></script>
    <!-- Chargifyjs custom CSS (modify as needed) -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" />
    <!-- Chargifyjs custom CSS (modify as needed) -->
    <link rel="stylesheet" href="styles.css" />
  </head>
  <body class="bg-light">
    <header>
      <div class="navbar navbar-dark bg-dark shadow-sm">
        <div class="container">
          <a href="#" class="navbar-brand d-flex align-items-center">
            <strong>Chargifyjs Signups: Web App with CC</strong>
          </a>
        </div>
      </div>
    </header>
    <div class="container">
      <main>
        <div class="py-5 text-center">
          <h2>PRODUCT NAME</h2>
          <p class="lead">Create subscription with Chargifyjs.</p>
        </div>
        <div class="row g-5">
          <div class="col-md-5 col-lg-4 order-md-last">
            <h4 class="d-flex justify-content-between align-items-center mb-3">
              <span>Summary</span>
            </h4>
            <ul class="list-group mb-3">
              <li class="list-group-item d-flex justify-content-between lh-sm">
                <div>
                  <h6 class="my-0">PRODUCT NAME</h6>
                </div>
                <span class="text-muted">$AMOUNT IN CENTS/100/mo</span>
              </li>
              <li class="list-group-item d-flex justify-content-between">
                <span>Today's Total</span>
                <strong>$TOTAL IN CENTS/100</strong>
              </li>
            </ul>
          </div>
          <!-- load spinner -->
          <div id="load_spinner" class="d-flex justify-content-center">
            <div class="spinner-border" role="status">
              <span class="sr-only"></span>
            </div>
          </div>
          <!-- error banners -->
          <div class="alert alert-danger" role="alert" id="chargify-error-message" style="display:none;"></div>
          <div class="col-md-7 col-lg-8">
            <h4 class="mb-3">Customer Information</h4>
            <form id="chargify-form" action="/chargifyjs-webapp/create_subscription" method="POST" style="display:none;">
              <div class="row g-3">
                <div class="col-sm-6">
                  Logged in as test@example.com
                </div>
              </div>
              <!-- end -->
              <hr class="my-4">
              <h4 class="mb-3">Payment</h4>
              <div class="row g-3">
                <div class="col-md-6 col-sm-12">
                  <div id="cc_first_name"></div>
                </div>
                <div class="col-md-6 col-sm-12">
                  <div id="cc_last_name"></div>
                </div>
                <div class="col-md-6 col-sm-12">
                  <div id="cc_number"></div>
                </div>
                <div class="col-md-6 col-sm-12">
                  <span id="cc_month"></span>
                  <span id="cc_year"></span>
                  <span id="cc_cvv"></span>
                </div>
              </div>
              <!-- end -->
              <hr class="my-4">
              When you submit the form, Chargifyjs will generate a token, and place it in the input box below. Hide this box in a real form.</br></br>
              <input id="product_handle" name="product_handle" type="text" value="HIDDEN PRODUCT HANDLE HERE" />
              <input id="chargify-token" name="chargify_token" type="text" />
              <input id="account_id" name="account_id" type="hidden" value="<%= user.account_id %>" />
              <input id="company" name="company" type="hidden" value="Acme (Autofilled for sample)" />
              <input id="first_name" name="first_name" type="hidden" value="First (Autofilled for sample)" />
              <input id="last_name" name="last_name" type="hidden" value="Last (Autofilled for sample)" />
              <input id="email" name="email" type="hidden" value="<%= user.email %>" />
              <button class="w-100 btn btn-primary btn-lg" type="submit">Subscribe</button>
            </form>
          </div>
        </div>
      </main>
    </div>
    <!-- JavaScript (jquery/bootstrap) -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
    <!-- Javascript (Chargifyjs load and submit files) -->
    <script src="load.js"></script>   <!-- This contains your Chargify.js file -->
    <script src="submit.js"></script>  <!-- This pauses form submission to create a token -->
    <!-- Smooth form load -->
    <script>
      setTimeout(function () {
          $("#load_spinner").remove();
          $("#chargify-form").show();
      }, 100);
    </script>
  </body>
</html>
3. Add credentials and start customizing
Next, let's configure your chargifyjs public credentials, payment method type, iframed fields, iframed field stylings, and more.

  1. Add your Chargifyjs credentials in the load.js file
    In load.js, update these:
    a) Update PublicKey with the Chargifyjs Public Key you created in Step 1.1, and 
    b) Update ServerHost with the Subdomain from Step 1.1


  2. Customize chargify.load (as needed)
    View more documented examples

  3. Configure Styling (as needed)
    Within chargify.load, there is a style object, which controls the styling of the iframed fields. In the load.js example file, you will see many values set to null to help guide you. Replace the null values, with real values, as needed, once your form is fully functional.

  4. Add secure iframed fields (as needed)
    The load.js file tells Chargifyjs what iframed fields to display on your web form. This is done by including fields (billing address, billing city, etc) in your chargify.load function, and those fields map to div IDs in your frontend form. Use the image below, alongside the 5 steps, to guide you.

    chargifyjs-divid-example.png

    1. Add a supported field to the load.js file, such as number. You will add these fields in the fields object.
    2. Set the selector to any ID you’d like, such as #cc_number.
    3. In the signup.html file, add a div with the matching selector, such as <div id="cc_number"></div>
    4. When you load your page, assuming no errors in your chargify.load function, the secure field will be iframed into your web form.
    5. Repeat for any field you would like to add. For full examples, see below.

 

4. Submit the form to your server

If using example from Frontend Implementation section
1. Go into submit.js and uncomment form.submit();
2. Go into signup.html, find the input chargify-token and change 'text' to 'hidden'

If not
If you are not using the example code, just make sure your form can successfully submit and POST to your servers.

5. Create the subscription Server-side API
Use the Create Subscription endpoint and pass the chargifyjs token as the payment method. These examples are similar to the Method 1 Website examples, but the primary difference is that you are passing a customer reference value (your user's accountID).

Credit Card Bank Account Paypal Other

Credit Card With Product
// EXAMPLE: Chargifyjs for Credit Cards - Create Subscription with Product
// ENDPOINT: POST /subscriptions.json
// DOCS: https://developers.chargify.com/docs/api-docs/b3A6MTQxMDgzODg-create-subscription

// REQUEST BODY
{
  "subscription": {
    "product_handle": "gold-plan", //a valid product handle from your catalog
    "customer_attributes": {
      "first_name": "Christopher",
      "last_name": "Adil",
      "email": "christopher.adil@example.com",
      "reference": "ref_2", //your user's account ID or user ID
      "organization": "Varity LLC"
    },
    "credit_card_attributes": {
      "chargify_token": "tok_mzvtmcv2hgtxj9sb7qq5kphc", //the chargifyjs token generated from your form
      "payment_type": "credit_card"
    }
  }
}

Credit Card With Components
// EXAMPLE: Chargifyjs for Credit Cards - Create Subscription with Components
// ENDPOINT: POST /subscriptions.json
// DOCS: https://developers.chargify.com/docs/api-docs/b3A6MTQxMDgzODg-create-subscription

// REQUEST BODY
{
  "subscription": {
    "product_handle": "gold-plan", //a valid product handle from your catalog
    "customer_attributes": {
      "first_name": "Christopher",
      "last_name": "Adil",
      "email": "christopher.adil@example.com",
      "reference": "ref_2", //your user's account ID or user ID
      "organization": "Varity LLC"
    },
    "components": [                              
      {
        "component_id": "handle:24-7-support",  //a valid component handle from your catalog
        "allocated_quantity": 1
      },
      {
        "component_id": "handle:automated-backups", //a valid component handle from your catalog
        "allocated_quantity": 25
      }
    ],
    "credit_card_attributes": {
      "chargify_token": "tok_mzvtmcv2hgtxj9sb7qq5kphc", //the chargifyjs token generated from your form
      "payment_type": "credit_card"
    }
  }
}

Credit Card With Existing Customer
// EXAMPLE: Chargifyjs for Credit Cards - Create Subscription with Existing Customer
// ENDPOINT: POST /subscriptions.json
// DOCS: https://developers.chargify.com/docs/api-docs/b3A6MTQxMDgzODg-create-subscription

// REQUEST BODY
{
  "subscription": {
    "product_handle": "gold-plan", //a valid product handle from your catalog
    "customer_reference": "ref_2", //your user's account ID or user ID
    "credit_card_attributes": {
      "chargify_token": "tok_mzvtmcv2hgtxj9sb7qq5kphc",  //a unique reference value belonging to an existing customer
      "payment_type": "credit_card"
    }
  }
}
6. Add user access
In your backend, you likely already have user access for your app. Apply those same user requirements to the Chargifyjs form.
7. Prefill data in your signup page
Since you already know some information about your user, such as name, email, etc, prefill that information and hide the fields. If any of the data needs to be included when generating the Chargifyjs token (such as a prefilled billing address), use these examples for guidance.
8. Test and add final touches
Finally, it's time to test your full Chargifyjs implementation and add the final touches.

  1. Test the frontend
    The form should load, a token should generate, and you should test token generation errors. If you are connected to the Chargify Test Gateway, use a card number of 2 or 3 to simulate an error.

  2. Add subscription creation errors and test
    Test a failed API call to Chargify. For example, break the API call on purpose, to test how your implementation responds to that error. Pass the error back to your front end. This is how your users will see errors such as 'insufficient funds', 'declined card', etc.

  3. Add a redirect and test success
    On success, a user should be redirected successfully, and the entire flow should make sense start to finish.

  4. Test your app's interaction with the chargifyjs form
    Tips:
    - Test a logged in user view
    - Test a non logged in user view
    - Test what happens after the user signs up, can they view the form? Should they be able to?
    - Anything else you can think of

Optional - Create a subscription preview Server-side API

Before your signup page loads, make an API call to gather the subscription preview data (product name, cost, any taxes, etc), and pass it to the front end. 

  1. Make a subscription preview API call   See the endpoint
    // Example json to preview a product
    {
      subscription: {
        product_handle: 'pro'
      }
    }
    
  2. Pass and display the data to your front end
    In the sample signup page, you'll see placeholders for PRODUCT NAME, AMOUNT-IN-CENTS, TOTAL-IN-CENTS. Replace these with the parsed values from the subscription preview. Add more fields as you see fit.

Examples

Was this article helpful?
1 out of 1 found this helpful