In-app checkout with Stripe.js for card tokenization

Stripe JS Card Token with Subscriptions

Integrating Stripe.js with card token for in-app checkout experience - ChargeBee

Get the best of both worlds using Stripe.js for card tokenization by having an in-app checkout page. And pass token to ChargeBee for Subscription management. Stripe's JavaScript ensures that sensitive credit card information is not passed to your server thereby reducing your PCI compliance requirements.
Note:You should be using Stripe as your payment gateway to use this flow.

stripe_js

A tutorial on deploying an in-app checkout page using Stripe.js to create subscriptions in ChargeBee and store and process payments on Stripe. Stripe.js makes it easy to use any form page as a checkout page and also reduces your PCI DSS scope. It does this by taking care of all the sensitive card information for you.

Alternative(s)

The simplest way to setup your checkout process with ChargeBee is by using the hosted payment pages . With hosted pages, you get a fully PCI DSS compliant checkout process, and hosted pages that are built using Bootstrap themes. A minor drawback with using the hosted checkout pages at the moment is the lack of flexibility in terms of controlling the fields within the form. Although you can customize it to match your website's appearance, you do not have control over the fields.

Overview

What is Stripe JS?

Well, Stripe.js is a JavaScript library which you can wire into your checkout form to handle the credit card information. When a user signs up using the checkout form, it sends the credit card information directly from the user's browser to Stripe's servers. Meaning, credit card information never hits your server and thus reducing your PCI compliance scope.
For further details, have a look at Stripe's documentation .

How exactly does this work?

Here's a detailed set of steps on how the entire checkout flow works:

  1. Using your signup form user enters their card and personal details.
  2. On form submit, Stripe.js passes just the card information to the Stripe server.
  3. Stripe verifies the card, stores it if successful and returns a temporary token.
  4. The temporary token and the form details are submitted to your server.
  5. And using the create subscription API call , the subscription information along with the temporary token is passed to ChargeBee.

And, Voila, a subscription is created! Your users never left your website and neither did your servers handle any sensitive information.

Is this secure?

With Stripe.js, your server does not handle any sensitive credit card data, which reduces the PCI compliance burden. However, serving the form over an SSL connection is strongly recommended, is more secure and makes your users feel more comfortable when sharing their payment information.

Honey Comics - Demo Application

'Honey Comics', our demo application, is a fictitious online comic book store providing a subscription service for comics. We send comic books every week to subscribers. Users can sign up for a subscription from the website by providing the account,payment and shipping address information.

Prerequisites

Before trying out this tutorial, you would need to setup the following:

  • A ChargeBee account. Signup for a free trial if you don't have one.
  • A plan in ChargeBee for your customers to subscribe to.You can setup the plan for the demo using the “Setup Configuration” option in the index page if you have downloaded code and started the tutorials locally.
  • A Stripe account (test mode for now, live mode when you go into production).
  • Your Stripe account integrated into your ChargeBee account. Here is how you do it .
  • Your Stripe test publishable key (don't forget to replace it with the live publishable key when in production).
  • Your ChargeBee API key for your test site.

Build the checkout form

We will start with the client side implementation. Let's start by building a form, for our users to sign up with. Now, only the card related information is passed to Stripe while remaining information such as account and shipping are passed to our server and then onto ChargeBee.
Our demo app's checkout page is an example of a simple form collecting basic account information (such as name, email, phone) and card information such as card number, expiry date, cvv. We also collect the shipping address.

Below form snippet shows the card number field alone.

checkout.html View full code
<div class="form-group">
    <label for="card_no">Credit Card Number</label>
    <div class="row">
        <div class="col-sm-6">
            <input type="text" class="card-number form-control" id="card_no" 
                   required data-msg-required="cannot be blank"> 
        </div>
        <div class="col-sm-6">                          
            <span class="cb-cards hidden-xs">                                        
                <span class="visa">  </span>                                        
                <span class="mastercard">  </span>
                <span class="american_express">  </span>
                <span class="discover">  </span>
            </span> 
        </div>
    </div>
    <small for="card_no" class="text-danger"></small>
</div>

Warning

We should not include a 'name' attribute to the card data fields in the form. This will ensure that the sensitive card data is not passed to our server when submitted.

The below form snippet shows an account field. In this case the name attribute is set as it needs to be passed on to our demo app server.

checkout.html View full code

<div class="col-sm-6">
    <div class="form-group">
        <label for="customer[email]">Email</label>
        <input id="email" type="text" class="form-control" name="customer[email]" 
                   data-rule-required="true" data-rule-email="true" 
                   data-msg-required="Please enter your email address" 
                   data-msg-email="Please enter a valid email address">
        <small for="customer[email]" class="text-danger"></small>
    </div>
</div> 

Wire up Stripe.js

Now that the form is built, let's wire up Stripe.js into our form. For Stripe.js to come into action, we add it to checkout page's header tag using script tag.

checkout.html View full code
<script type="text/javascript" src="https://js.stripe.com/v2/">
</script>

Set the Stripe Publishable Key

After the JavaScript library has been embedded, we set the Stripe publishable key . This is for Stripe to identify our account.

checkout.html View full code
<!-- Setting the stripe publishable key.-->
<script>Stripe.setPublishableKey("pk_test_acfVSJh9Oo9QIGTAQpUvG5Ig");
</script>

Note:

Replace the sample key given above with your test publishable key. Also, don't forget to replace the test keys with live keys when going into production.

Send the card details to Stripe

So now that Stripe.js is all set in our web page, now let's write up some javascript for our form. The javascript should trigger up once a user submits the form and pass the card details to Stripe and also handle the response from Stripe.
In our code, we used a Stripe's Stripe.createToken(params, stripeResponseHandler) to pass the card details to Stripe. The parameter params should be a JSON object containing the card information and stripeResponseHandler is a callback function to be executed once the call is complete. The Stripe call is asynchronous and stripe will call the callback function with a json object once it has stored the card details in its server(s)

checkout.html View full code
$("#subscribe-form").on('submit', function(e) {
    // form validation
    formValidationCheck(this);
    if(!$(this).valid()){
        return false;
    }
    // Disable the submit button to prevent repeated clicks and form submit
    $('.submit-button').attr("disabled", "disabled");
    // createToken returns immediately - the supplied callback 
    // submits the form if there are no errors
    Stripe.createToken({
        number: $('.card-number').val(),
        cvc: $('.card-cvc').val(),
        exp_month: $('.card-expiry-month').val(),
        exp_year: $('.card-expiry-year').val()
    }, stripeResponseHandler);
    return false; // submit from callback
});

Handle Stripe's response

The json object passed to the callback function will contain a temporary token and additional information. Incase the card validation fails then the json object will contain the error information.The sample responses are given below

In our demo app's callback function (viz,stripeResponseHandler) we do the following:

  • We identify whether the response from Stripe is an success json or error json.
  • If it's an error, we re-enable the submit button and call the error handler function.
  • If it is success, we extract the response, append it to the form and submit it to our demo app server.
checkout.html View full code
// Call back function for stripe response.
function stripeResponseHandler(status, response) {
    if (response.error) {
        // Re-enable the submit button
        $('.submit-button').removeAttr("disabled");
        // Show the errors on the form
        stripeErrorDisplayHandler(response);
        $('.subscribe_process').hide();
    } else {
        var form = $("#subscribe-form");
        // Getting token from the response json.
        var token = response['id'];
        // insert the token into the form so it gets submitted to the server
        if ($("input[name='stripeToken']").length == 1) {
            $("input[name='stripeToken']").val(token);
        } else {
            form.append("<input type='hidden' name='stripeToken' value='" + token + "' />");
        }
        var options = {
            error: subscribeErrorHandler, // post-submit callback when error returns
            success: subscribeResponseHandler, // post-submit callback when success returns
            complete: function() {
                $('.subscribe_process').hide()
            },
            contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
            dataType: 'json'
        };
        // Doing AJAX form submit to your server.
        form.ajaxSubmit(options);
        return false;
    }
}


Now lets switch to the server side implementation

Setup the client library

We first have to download and import the client library of our choice. Then we need to configure the client library with our test site and our test api key.

For the tutorials we have configured the site and the credentials in a properties file from which the client library is configured at the webapp is initialized.

For the tutorials we have configured the site credentials in config/environments/development.rb

We setup the client library in config/initializers/chargebee.rb

For the tutorials we have configured the site credentials in Config.php which is included in other php files.

Create the subscription

We fetch the Stripe token and other information from the POST parameters submitted by our form and use the Create Subscription API to create the subscription in ChargeBee.

Since it is a demo app we have skipped validating the parameters in server. But it is recommended to perform these validations on the server side as well for security even though we have validated them in client.

Redirecting to a thank you page

So, what happens when a subscription is created successfully? Well, ChargeBee returns a success response in json format which is wrapped as a 'result' class by the client library. In case of any error , ChargeBee returns a error response which is wrapped and thrown as an exception by the client library .

In case of successful checkout we redirect the user to a simple 'Thank You' page.

Handling Errors

Let's look at some errors and how we have handled them in the demo application.

  • Form Errors: We use the Jquery form validation plugin to check whether the form inputs are valid or not. The plugin will validate the inputs entered into the email, zip and phone number fields.
  • Stripe Tokenization Errors: Stripe returns error JSON for tokenization errors. We used the stripeErrorDisplayHandler to identify and display the error that occurred.
  • API Errors: Sometimes the credit card might fail during verification, or processing errors occur while creating the subscription in ChargeBee. When this happens, ChargeBee returns back an error response which is thrown as a exception by the client library. We handle this using our API exception handler in the demo application.

Test cards

Now that you're all set, why don't you test your integration with some test transactions. Here are some credit card numbers that you can use to test your application.

Visa
4242 4242 4242 4242
Discover
6011 1111 1111 1117
JCB
3530 1113 3330 0000

For more test cards for testing different scenarios click here .