A simple credit card payment form for Stripe

A simple credit card payment form for Stripe

  • 2018-10-11 04:47 AM
  • 125

A simple credit card payment form for Stripe Today we will build a simple credit card payment form that does the following

Today we will build a simple credit card payment form that does the following

  • does formatting and validation of necessary fields inherently
  • integrates well with Stripe.js
  • looks good on the eye with less code

What you see below will be the final version of the form and uses the following libraries to accomplish the same:

  • Twitter Bootstrap (for grid layout and basic styling)
  • Card.js (for validation and credit card preview)
  • Stripe.js (for Stripe integration)

I will walk you through the code with just the relevant elements to convey the crux of the implementation.

<div class="card"></div>

<form action="#">
  
    <label>Credit Card Number </label>
    <input type="text" name="number" />

    <label>Expiration</label>
    <input type="text" placeholder="MM/YY" name="expiry"/>

    <label>Name</label>
    <input type="text" name="name" />

    <label>CVV </label>
    <input type="text" name="cvv" />
  
  <button type="button" class="btn btn-success">Submit</button>
  <button type="button" class="btn btn-info">Clear</button>

</form>

Card.js is an awesome library which takes care of most of the UI nitty-gritty details and is highly recommended. I have used Card.js without jQuery as seen below.

new Card({
  form: 'form',
  container: '.card',
  formSelectors: {
    numberInput: 'input[name=number]',
    expiryInput: 'input[name=expiry]',
    cvcInput: 'input[name=cvv]',
    nameInput: 'input[name=name]'
  },
  width: 390, // optional — default 350px
  formatting: true
})

You need to pass the selectors to the form elements and credit card preview container. You can use the default form selectors as specified in the documentation or define them explicitly.

Till this point, we have created a fully functional credit card form that enables the user to enter the details and preview the same for visual feedback. The complete code is available in this CodePen for your reference.

Now, we will handle the Stripe integration. There are three steps to follow before persisting the payment details of the user to our application backend:

  1. Collecting credit card information with Stripe.js
  2. Converting those payment details to a single-use token
  3. Submitting that token to our server

Now that we have taken care of (1) by creating a usable form that captures all the details as parameters that can be passed on to Stripe, let’s proceed with Stripe integration.

<script type="text/javascript" src="https://js.stripe.com/v2/"></script>

This will help us access Stripe’s Javascript SDK and must ideally be added to tag or as the final line in the__ at the end of your code.

In a separate