Stripe integration with React using custom form

Stripe is the best platform to collection payment online. In this tutorial, we’ll learn Stripe integration with React with the example. We will create custom form to collect the credit or debit card information and create token from the information. Let’s see Stripe integration with React with the example

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

Stripe.js makes it easy to collect credit card—and other similarly sensitive—details without having the information touch your server.

Set up Stripe Elements

First of all, we need to add a stripe script.

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 type="text/javascript" src="https://js.stripe.com/v2/"></script>

The second way to include it via component.

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

Open the App.js 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://js.stripe.com/v2/";
      s.onload = () => {
        window['Stripe'].setPublishableKey('your_public_key');
      }
      window.document.body.appendChild(s);
    }
}

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

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

Next, Call the above method on componentDidMount method like below

componentDidMount() {
    this.loadStripe();    
}

Create your payment form

Next, We need to create beautiful html form. We am using bootstrap in our project.

open theApp.js file and put the below html

render() {
  return (
    <div className="container">    
      <div className="row">
          <div className="col-xs-12 col-md-8 mr-auto ml-auto">            
              <div className="panel panel-default">
                  <form onSubmit={this.pay}>
                    <div className="panel-body mt-5">
                        <h4>Stripe - Custom form demo</h4>    
                        <p><b>{this.state.message}</b></p>
                        <div className="row">
                            <div className="col-xs-12 col-md-12">
                                <div className="form-group">
                                    <label>CARD NUMBER</label>
                                    <div className="input-group">
                                        <input type="text" className="form-control" placeholder="Valid Card Number" name="cardNumber" maxLength="18" onChange={this.handleChange} />
                                        <span className="input-group-addon"><span className="fa fa-credit-card"></span></span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div className="row">
                            <div className="col-xs-7 col-md-7">
                                <div className="form-group">
                                    <label><span className="hidden-xs">EXPIRATION</span> Date</label>
                                    <div className="row">
                                        <div className="col-md-6">
                                            <div className="form-group">
                                                <select name="expMonth" className="form-control"  onChange={this.handleChange}>
                                                    <option value="">Select Month</option>
                                                    <option value="1">01</option>
                                                    <option value="2">02</option>
                                                    <option value="3">03</option>
                                                    <option value="4">04</option>
                                                    <option value="5">05</option>
                                                    <option value="6">06</option>
                                                    <option value="7">07</option>
                                                    <option value="8">08</option>
                                                    <option value="9">09</option>
                                                    <option value="10">10</option>
                                                    <option value="11">11</option>
                                                    <option value="12">12</option>
                                                </select>
                                            </div>
                                        </div>
                                        <div className="col-md-6 pull-right">
                                            <div className="form-group">
                                                <select name="expYear" className="form-control" onChange={this.handleChange}>
                                                    <option value="">Select Year</option>
                                                    <option value="20">2020</option>
                                                    <option value="21">2021</option>
                                                    <option value="22">2022</option>
                                                    <option value="23">2023</option>
                                                    <option value="24">2024</option>
                                                    <option value="25">2025</option>
                                                    <option value="26">2026</option>
                                                    <option value="27">2027</option>
                                                    <option value="28">2028</option>
                                                    <option value="29">2029</option>
                                                    <option value="30">2030</option>                                                
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                </div>                            
                            </div>
                            <div className="col-xs-5 col-md-5 pull-right">
                                <div className="form-group">
                                    <label>CVV CODE</label>
                                    <input type="text" name="cvv" className="form-control" placeholder="CVC" maxLength="4" onChange={this.handleChange} />
                                </div>
                            </div>
                        </div>
                    </div>
                    <div className="panel-footer">
                        <div className="row">
                            <div className="col-xs-12 col-md-12">
                                { (this.state.formProcess)? (
                                    <span className="btn btn-warning btn-lg btn-block">Please wait...</span>
                                  ) : (
                                    <button className="btn btn-warning btn-lg btn-block">Process payment</button>
                                  )}
                            </div>
                        </div>
                    </div>
                </form>
                <p className="mt-2">Try it out using the test card number 4242 4242 4242 4242, a random three-digit CVC number and any expiration date in the future.</p>
              </div>
          </div>
      </div>
    </div>
  );
}

Next, We will create a new method which will validate the form and get the form data and sent it to the stripe server to generate the token

Add the below method on App.js file

pay = (e) => {

    e.preventDefault();

    this.setState({
      formProcess: true
    });

    window.Stripe.card.createToken({
      number: this.state.cardNumber,
      exp_month: this.state.expMonth,
      exp_year: this.state.expYear,
      cvc: this.state.cvc
    }, (status, response) => {
            
      if (status === 200) {
        this.setState({
          message: `Success! Card token ${response.card.id}.`,
          formProcess: false
        });

      } else {
        this.setState({
          message: response.error.message,
          formProcess: false
        });
      }
    });
  } 

After the above changes our component will look like below

import React, { Component } from 'react';

class App extends Component {
  state =  {
    cvc: '',
    message: '',
    expYear: '',
    expMonth: '',
    cardNumber: '',
    formProcess: false
  };

  componentDidMount() {
    this.loadStripe();    
  }

  handleChange = (evt) => {
    this.setState({
      [evt.target.name] : evt.target.value
    });
  }

  pay = (e) => {

    e.preventDefault();

    this.setState({
      formProcess: true
    });

    window.Stripe.card.createToken({
      number: this.state.cardNumber,
      exp_month: this.state.expMonth,
      exp_year: this.state.expYear,
      cvc: this.state.cvc
    }, (status, response) => {
      
      
      if (status === 200) {
        this.setState({
          message: `Success! Card token ${response.card.id}.`,
          formProcess: false
        });

      } else {
        this.setState({
          message: response.error.message,
          formProcess: false
        });
      }
    });
  }


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

  render() {
    return (
      <div className="container">    
        <div className="row">
            <div className="col-xs-12 col-md-8 mr-auto ml-auto">            
                <div className="panel panel-default">
                    <form onSubmit={this.pay}>
                      <div className="panel-body mt-5">
                          <h4>Stripe - Custom form demo</h4>    
                          <p><b>{this.state.message}</b></p>
                          <div className="row">
                              <div className="col-xs-12 col-md-12">
                                  <div className="form-group">
                                      <label>CARD NUMBER</label>
                                      <div className="input-group">
                                          <input type="text" className="form-control" placeholder="Valid Card Number" name="cardNumber" maxLength="18" onChange={this.handleChange} />
                                          <span className="input-group-addon"><span className="fa fa-credit-card"></span></span>
                                      </div>
                                  </div>
                              </div>
                          </div>
                          <div className="row">
                              <div className="col-xs-7 col-md-7">
                                  <div className="form-group">
                                      <label><span className="hidden-xs">EXPIRATION</span> Date</label>
                                      <div className="row">
                                          <div className="col-md-6">
                                              <div className="form-group">
                                                  <select name="expMonth" className="form-control"  onChange={this.handleChange}>
                                                      <option value="">Select Month</option>
                                                      <option value="1">01</option>
                                                      <option value="2">02</option>
                                                      <option value="3">03</option>
                                                      <option value="4">04</option>
                                                      <option value="5">05</option>
                                                      <option value="6">06</option>
                                                      <option value="7">07</option>
                                                      <option value="8">08</option>
                                                      <option value="9">09</option>
                                                      <option value="10">10</option>
                                                      <option value="11">11</option>
                                                      <option value="12">12</option>
                                                  </select>
                                              </div>
                                          </div>
                                          <div className="col-md-6 pull-right">
                                              <div className="form-group">
                                                  <select name="expYear" className="form-control" onChange={this.handleChange}>
                                                      <option value="">Select Year</option>
                                                      <option value="20">2020</option>
                                                      <option value="21">2021</option>
                                                      <option value="22">2022</option>
                                                      <option value="23">2023</option>
                                                      <option value="24">2024</option>
                                                      <option value="25">2025</option>
                                                      <option value="26">2026</option>
                                                      <option value="27">2027</option>
                                                      <option value="28">2028</option>
                                                      <option value="29">2029</option>
                                                      <option value="30">2030</option>                                                
                                                  </select>
                                              </div>
                                          </div>
                                      </div>
                                  </div>                            
                              </div>
                              <div className="col-xs-5 col-md-5 pull-right">
                                  <div className="form-group">
                                      <label>CVV CODE</label>
                                      <input type="text" name="cvv" className="form-control" placeholder="CVC" maxLength="4" onChange={this.handleChange} />
                                  </div>
                              </div>
                          </div>
                      </div>
                      <div className="panel-footer">
                          <div className="row">
                              <div className="col-xs-12 col-md-12">
                                  { (this.state.formProcess)? (
                                      <span className="btn btn-warning btn-lg btn-block">Please wait...</span>
                                    ) : (
                                      <button className="btn btn-warning btn-lg btn-block">Process payment</button>
                                    )}
                              </div>
                          </div>
                      </div>
                  </form>
                  <p className="mt-2">Try it out using the test card number 4242 4242 4242 4242, a random three-digit CVC number and any expiration date in the future.</p>
                </div>
            </div>
        </div>
      </div>
    );
  }
}

export default App;

You have successfully integrated the stripe 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 this (https://stripe.com/docs/api/charges/create) url

Here is how our application will looks like

Be First to Comment

Leave a Reply

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