Build an in-app popup checkout form using Stripe.js

Watch Video

A tutorial on deploying an in-app checkout page using Stripe's embedded checkout form to create subscriptions in Chargebee. Stripe's embedded form ensures that sensitive credit card information is not passed to your server thereby reducing your PCI compliance requirements.

Alternative options

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 Js
The other option is to use the Stripe JS . Stripe.js makes it easy to use any form page as a checkout page and also reduces your PCI DSS scope. See this tutorial for explanation on how to use it.

Overview 

What is Stripe embedded checkout form?

Stripe embedded checkout form provides a self contained popup that takes care of building the payment form, validating input and also storing the card information. See Stripe's documentation  for more details

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 personal details.
  2. On clicking "Proceed to Payment" we popup the Stripe's checkout form.
  3. User enters his card details in the secure Stripe's checkout form.
  4. On checkout form submit , Stripe validates the card and also takes storing it. At the end of successful submit, Stripe invokes our call back code with a temporary token.
  5. Using the create subscription API call , the subscription information along with the temporary token is passed to Chargebee.

Is this secure?

With Stripe embedded form, 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 - 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. We get the general information such as account and shipping directly in our signup form itself.

Include Stripe checkout's js

Inorder to use Stripe checkout we need to add the Stripe's checkout js to checkout page's header tag using script tag.

  • php
  • Ruby
  • Java
  stripe-popup-js/signup.html  -   View full code
<script src="https://checkout.stripe.com/checkout.js">           
</script>

Configure Stripe checkout form

The stripe checkout form can be configured. At the minimum we need to provide the publishable key and the handler for token.

  • php
  • Ruby
  • Java
  stripe-popup-js/signup.html  -   View full code
// Creating Stripe Checkout handler object and also 
// configuring Stripe publishable key and setting the options in Stripe Js.
var handler = StripeCheckout.configure({
    //Replace it with your stripe publishable key
    key: 'pk_test_acfVSJh9Oo9QIGTAQpUvG5Ig',
    image: '/assets/images/favicon.png',
    allowRememberMe: false,
    token: handleStripeToken
});

Calling the Stripe checkout form

We register for the 'on click' event of the "Proceed to Payment" button and invoke the configured handler.

  • php
  • Ruby
  • Java
  stripe-popup-js/signup.html  -   View full code
// Calling Stripe Js to display pop up on button click event
$("#submit-btn").on('click', function(e) {
    var form = $("#subscribe-form");
    if(!$(form).valid()) {
        return false;
    }
    handler.open({
           name: 'Honey Comics',
           description: $('#plan-desc').val() ,
           amount: $('#plan-price').val() ,
           email: $('#email').val() ,
    });
    return false;
});

Handling the returned token

On success, Stripe calls the function passed to the token parameter during configuration . In this case it is handleStripeToken. In that function we add the token to a hidden parameter and submit the form.

  • php
  • Ruby
  • Java
  stripe-popup-js/signup.html  -   View full code
function handleStripeToken(token, args) {
            form = $("#subscribe-form");
            $("input[name='stripeToken']").val(token.id );
            var options = {
                beforeSend: showProcessing,
                // post-submit callback when error returns
                error: subscribeErrorHandler, 
                // post-submit callback when success returns
                success: subscribeResponseHandler, 
                complete: hideProcessing,
                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.

Validation and Error Handling

Here's how we validate user inputs and handle API call errors in this demo:

  • Client Side Validation: We use the jQuery form validation  plugin to check whether the user's input in fields(email, zip code and phone number) is valid or not.

  • Server Side Validation: As this is a demo app 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 exception in this demo with appropriate error messages.

  • General API Errors: Chargebee might return error responses due to various reasons such as invalid configuration. To identify specific reasons for all error responses you can check the API documentation  and also take a look at the error handler file to check how these errors can be handled.

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 .