React – Stripe Payment Gateway Integration

Stripe allow us to easily accept and manage payments online. Stripe payment gateway integration with react is very easy. Today we will discuss about the stripe payment gateway in react

Before start learning React - Stripe Payment Gateway integration . We need a React Project. If you don’t know how to create a new project. Follow this tutorial.

Stripe offer two way to interact with Stripe server using JS.

  • Default Stripe form.
  • Custom Stripe Form.

Default Stripe Form gives us the easiest and safest way to create a token.

So, let’s start with Default Stripe Form

First of all, we need to add a stripe checkout script which will highlight the global variable stripecheckout.

Include the Stripe Library

We have two ways to load this JS.

In the first method we need to add the script tag to the index.html file.

<script src="https://checkout.stripe.com/checkout.js"></script>

The second way to include it via component.

I will prefer second method because in this method the stripe will load when we really need it.

Open the app.component.ts file and add the below method on it

loadStripe = () => {
    
    if(!window.document.getElementById('stripe-script')) {
      var s = window.document.createElement("script");
      s.id = "stripe-script";
      s.type = "text/javascript";
      s.src = "https://checkout.stripe.com/checkout.js";      
      window.document.body.appendChild(s);
    }
  }

Next, Call the above method from componentDidMount method like below

componentDidMount() {
    this.loadStripe();    
}

The loadStripe method will add the script dynamically when component will load.

Next, Create a new method called pay which will open the stripe payment form.

pay = (amount) => {
    var handler = window.StripeCheckout.configure({
      key: 'your_public_key',
      locale: 'auto',
      token: function (token: any) {
        // You can access the token ID with `token.id`.
        // Get the token ID to your server-side code for use.
        console.log(token)
        alert('Token Created!!');
      }
    });

    handler.open({
      name: 'Demo Site',
      description: '2 widgets',
      amount: amount * 100
    });
  }

Here key is your stripe public key, You can get this key from the stripe dashboard. Login or register on stripe then go to the Developer then Api Keys . Here you can see the Publishable key copy this key and replace with the above your_public_key

Next, We need to add the button to our component’s template. Open the StripeTutorial.js file and add the below method.

render() {
    return (
      <div className="mt-5">
        <h2>Stripe Checkout</h2>
        <div className="row mt-5">
          <div className="col-md-4 mt-2">
            <button onClick={() => this.pay(20)} className="btn btn-primary btn-block">Pay $20</button>
          </div>
          <div className="col-md-4 mt-2">
            <button onClick={() => this.pay(30)} className="btn btn-success btn-block">Pay $30</button>
          </div>
          <div className="col-md-4 mt-2">
            <button onClick={() => this.pay(50)} className="btn btn-info btn-block">Pay $50</button>
          </div>    
        </div>
        <p className="mt-5">
            Try it out using the test card number <b>4242 4242 4242 4242</b>, a random three-digit CVC number, any expiration date in the future, and a random five-digit U.S. ZIP code.
        </p>
      </div>


    );
  }

After the above changes our StripeTutorial.js file will looks like this

import React, { Component } from 'react';

class StripeTutorial extends Component {
  pay = (amount) => {
    var handler = window.StripeCheckout.configure({
      key: 'pk_test_aeUUjYYcx4XNfKVW60pmHTtI',
      locale: 'auto',
      token: function (token: any) {
        // You can access the token ID with `token.id`.
        // Get the token ID to your server-side code for use.
        console.log(token)
        alert('Token Created!!');
      }
    });

    handler.open({
      name: 'Demo Site',
      description: '2 widgets',
      amount: amount * 100
    });
  }

  componentDidMount() {
    this.loadStripe();    
  }

  loadStripe = () => {
    
    if(!window.document.getElementById('stripe-script')) {
      var s = window.document.createElement("script");
      s.id = "stripe-script";
      s.type = "text/javascript";
      s.src = "https://checkout.stripe.com/checkout.js";      
      window.document.body.appendChild(s);
    }
  }

  render() {
    return (
      <div className="mt-5">
        <h2>Stripe Checkout</h2>
        <div className="row mt-5">
          <div className="col-md-4 mt-2">
            <button onClick={() => this.pay(20)} className="btn btn-primary btn-block">Pay $20</button>
          </div>
          <div className="col-md-4 mt-2">
            <button onClick={() => this.pay(30)} className="btn btn-success btn-block">Pay $30</button>
          </div>
          <div className="col-md-4 mt-2">
            <button onClick={() => this.pay(50)} className="btn btn-info btn-block">Pay $50</button>
          </div>    
        </div>
        <p className="mt-5">
            Try it out using the test card number <b>4242 4242 4242 4242</b>, a random three-digit CVC number, any expiration date in the future, and a random five-digit U.S. ZIP code.
        </p>
      </div>


    );
  }
}

export default StripeTutorial;

You have successfully integrated the Strip with React. With the above integration you will be able to generate tokens. Now you need to code some server side code to catch this payment.

For server side payment capture, visit https://stripe.com/docs/api/charges/create

Running application:

Run the application using npm run start and you should see three payment button, click on any one will appear stripe payment popup. Congrats!! See, it was easy.

Sometime we need more handling we can achieve it via (Custom Stripe Form). We will learn about this in next tutorial

Our Application will look like this

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *