A tutorial on deploying an in-app checkout page using Stripe.js Stripe.js tokenization feature 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.
Hosted Pages
The simplest way to setup your checkout process with Chargebee is by using the hosted payment pages or the Hosted Pages + API integration method. Chargebee's hosted pages are built using the Bootstrap themes.
Stripe's Embedded checkout form
The other option is to use the embedded checkout form provided by stripe. See this tutorial for explanation on how to use it.
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 .
Here's a detailed set of steps on how the entire checkout flow works:
And, Voila, a subscription is created! Your users never left your website and neither did your servers handle any sensitive information.
With Stripe.js, your server does not handle any sensitive credit card data, which reduces the PCI compliance burden. But we strongly recommend you to use Chargebee's hosted payment pages .
'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.
Before trying out this tutorial, you would need to setup the following:
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.
<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>
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.
<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]" maxlength=50 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>
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.
<script type="text/javascript" src="https://js.stripe.com/v2/"> </script>
After the JavaScript library has been embedded, we set the Stripe publishable key . This is for Stripe to identify our account.
<!-- Setting the stripe publishable key.--> <script>Stripe.setPublishableKey("pk_test_acfVSJh9Oo9QIGTAQpUvG5Ig"); </script>
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.
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)
$("#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 });
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:
// 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 = { // post-submit callback when error returns error: subscribeErrorHandler, // post-submit callback when success returns success: subscribeResponseHandler, 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
You have to download and import the client library of our choice. Then, configure the client library with your test site and its api key.
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.
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.
Here's how we validate user inputs and handle API call errors in this demo:
Client Side Validation: Chargebee uses jQuery form validation plugin to check whether the user's field inputs(email, zip code and phone number) are valid or not.
Stripe Tokenization Errors: Stripe returns error JSON for tokenization errors. We used the stripeErrorDisplayHandler to identify and display the error that occurred.
Server Side Validation: As this is a demo application we have skipped the server side validation of all input parameters. But we recommend you to perform the validation at your end.
Payment Errors: If a payment fails due to card verification or processing errors, Chargebee returns an error response which is thrown as a payment exception by the client library. We handle the exceptions in the demo application with appropriate error messages.
General API Errors: Chargebee might return error responses due to various reasons such as invalid configuration, bad request etc. To identify specific reasons for all error responses you can check the API documentation . Also take a look at the error handler file to check how these errors can be handled.
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.
For more test cards for testing different scenarios click here .