Collect Payment Methods in your App with Chargifyjs

This implementation guide will walk you through the process of building a Chargifyjs payment page that collects new payment methods in your web application. 


Summary

Feature
Chargifyjs
You Need
A web app; developer experience with Javascript and APIs
Code
Yes
Difficulty
◉◉

Implementation Samples Diagram

In this walkthrough, we'll build a functioning Chargifyjs form that allows your logged-in end user to add a credit card.

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

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

  3. Get your Advanced Billing API Key
    In your Advanced Billing Site, go to Config > Integrations > API Keys
2. Build your Chargifyjs 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
        - index.html
        - load.js
        - submit.js
        - styles.css 

  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.
index.html load.js submit.js styles.css
<!doctype html>
<html lang="en">
  <head>
    <!-- meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- include chargifyjs -->
    <script src="https://js.chargify.com/latest/chargify.js"></script>
    
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    
    <!-- Chargifyjs custom CSS (modify as needed) -->
    <link rel="stylesheet" href="styles.css" />
  </head>

  <!-- begin body -->
  <body>
    <div class="form-box">
      <h2 align="left">Chargifyjs for Credit Cards with Billing Address</h2>
      <hr style="margin-top:16px; margin-bottom:32px; border-bottom: 4px solid #e0e1ec;">

      <!-- load spinner -->
      <div id="load_spinner" class="d-flex justify-content-center">
        <div class="spinner-border" role="status">
          <span class="sr-only">Loading...</span>
        </div>
      </div>
   
      <!-- error banner -->
      <div class="alert alert-danger" role="alert" id="chargify-error-message" style="display:none;"></div>

      <form id="chargify-form" action="create.js" method="POST" style="display:none;">
        
        <!-- Card Details Section -->
        <h5 style="margin-bottom:32px;">Card Details</h5>

        <div class="form-row">
          <div class="form-group col-md-6">
            <div id="first_name"></div>
          </div>
          <div class="form-group col-md-6">
            <div id="last_name"></div>
          </div>
          <div class="form-group col-md-6">
            <div id="cc_number"></div>
          </div>
          <div class="form-group col-md-6">
            <span id="cc_month"></span>
            <span id="cc_year"></span>
            <span id="cc_cvv"></span>
          </div>
        </div>

        <hr>
        <h5 style="margin-bottom:32px;">Billing Address</h5>
      
        <!-- billing address -->
        <div class="form-row">
          <div class="form-group col-md-6">
            <div id="billing_address"></div>
         </div>
          <div class="form-group col-md-6">
            <div id="billing_address2"></div>
          </div>
        </div>

        <div class="form-row">
          <div class="form-group col-md-6">
            <div id="billing_city"></div>
          </div>
          <div class="form-group col-md-6">
            <div id="billing_zip"></div>
          </div>
        </div>

        <!-- billing address -->
        <div class="form-row">
          <div class="form-group col-md-6">
            <div id="billing_country"></div>
          </div>
          <div class="form-group col-md-6">
            <div id="billing_state"></div>
          </div>
        </div>
        
        <!-- Form Submit -->
        <button type="submit" class="btn btn-primary">Save Card</button>

        <!-- Display Chargifyjs Token (make this input hidden in production) -->
        <hr>The Chargify Token is: <input id="chargify-token" type="text" /></br>
        Use this token in your backend to perform an action with the Chargify API

      </form>
    </div>
    <!-- end body -->

    <!-- 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();
    }, 2000);
    </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 payment method for the customer Server-side API

Next, create a payment profile and save the card to the existing customer.

// EXAMPLE: Chargifyjs for Create Payment Method for Customer
// ENDPOINT: POST /payment_profiles.json
// DOCS: https://developers.chargify.com/docs/api-docs/b3A6MTQxMDgzNTU-create-payment-profile

// REQUEST BODY
{
  "payment_profile": {
    "customer_id": 12345, //valid customer ID
    "chargify_token": "tok_w68qcpnftyv53jk33jv6wk3w" //the chargifyjs token generated from your form
  }
}


Then, set the newly created payment method as the default.

If you want to set it as the default in real time
You’ll need the subscription id and the payment profile id in your code, then set the payment method as the default for the subscription by performing POST /subscriptions/:id/payment_profiles/:id/change_payment_profile.json. There is no json body for this API call.

If you want to let the user set the default manually
Continue to the next section, and build a UI to let your customer manage multiple payment methods.

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 Advanced Billing Test Gateway, use a card number of 2 or 3 to simulate an error.

  2. Add payment method errors and test
    Test a failed API call to Advanced Billing. 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 '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 - Let your customers manage multiple payment methods
If you want to let your users manage their payment methods with a UI, this will walk you through the general process.

 

  1. Read the customer’s payment methods
    You’ll need the customer id, and then read the payment profiles for the customer by performing GET /payment_profiles.json?customer_id=:id. Since this endpoint reads all payment profiles and returns a max of 20 as a default, be sure you have a value set as the customer_id to ensure you are fetching the intended customer’s data.

  2. Parse the data you want to display
    For example, the payment profile id would be similar to response[0].payment_profile.id. Maybe you want the payment profile first name, which would be response[0].payment_profile.first_name.

  3. Pass the data to your frontend, and display it
    Here is a sample image that shows what an end result might look like in a basic table/list layout:

    image2.png

  4. Let the user set a payment method as the default
    You’ll need the subscription id and the payment profile id, then set the payment method as the default for the subscription by performing POST /subscriptions/:id/payment_profiles/:id/change_payment_profile.json. There is no json body for this API call.

    image5.png

Examples

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