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

14 Comments

  1. effexor without a prescription said:

    My husband and i ended up being cheerful Albert could carry out his analysis because of the ideas he acquired from your blog. It’s not at all simplistic just to always be freely giving concepts a number of people could have been making money from. And now we acknowledge we’ve got the blog owner to appreciate because of that. All of the explanations you’ve made, the easy blog menu, the friendships you aid to create – it’s all amazing, and it’s aiding our son and our family believe that that article is amusing, and that’s especially essential. Many thanks for all! https://effexorvenlafaxines.com/

    January 8, 2021
    Reply
  2. amitriptyline online said:

    Thanks for your own labor on this web site. My mother take interest in participating in research and it is simple to grasp why. My spouse and i notice all regarding the powerful way you produce valuable thoughts via your website and in addition recommend response from the others on this subject then our own princess is undoubtedly studying a whole lot. Take pleasure in the rest of the year. You have been performing a terrific job. https://endepamitriptyline.com/

    January 8, 2021
    Reply
  3. risnia generic said:

    I enjoy you because of all of your effort on this blog. Ellie enjoys conducting internet research and it’s easy to see why. All of us hear all about the compelling manner you create efficient ideas by means of the blog and as well cause contribution from other ones about this article and my child is being taught a great deal. Enjoy the remaining portion of the new year. You’re the one carrying out a fantastic job. https://risniarisperidone.com/

    January 9, 2021
    Reply
  4. risperidone said:

    Thanks for your entire labor on this web site. My mother take interest in participating in research and it is simple to grasp why. My spouse and i notice all regarding the powerful tactic you produce useful thoughts via your website and in addition recommend response from the others on this subject then our own princess is truly studying a whole lot. Take pleasure in the rest of the year. You have been performing a superb job. https://risniarisperidone.com/

    January 9, 2021
    Reply
  5. https://www.vfv79.com/ said:

    Plus, if someone wants to follow a conversation, they can subscribe to the comments of a blog post with or without commenting. Visitors can also share a particular discussion or the post on Twitter and Facebook, as well as flag comments they feel are inappropriate to help moderators find and remove them.
    Business bloggers will love the advanced capabilities Disqus has to offer. Enable Disqus to publish comments, hold them all for moderation or allow only those with verified emails to be published. Set up additional moderators to login and moderate comments. Also, get analytics for all of your comments, information about specific commenters and much more.
    카지노사이트

    January 19, 2021
    Reply
  6. https://txt2080.com/woori/ said:

    Another great feature is the optional recommended stories box at the end of your Disqus comments. Use this to keep visitors on your website by directing them to other great posts or monetize this space by sharing posts from publishers advertising on Disqus.
    Visitors are able to follow conversations with or without commenting, as well as share particular comments along with a link to the post on Twitter and Facebook. Plus, they can flag comments they find inappropriate.
    우리카지노

    January 19, 2021
    Reply
  7. https://liveone9.com/baccaratsite/ said:

    Livefyre offers powerful administration features for blog owners, including spam protection, multiple moderators, whitelists, blacklists, individual activity reports and more.
    Install Livefyre on WordPress and Tumblr blogs once you have created a free account or signed in with the account you use on Livefyre.
    바카라사이트추천

    January 19, 2021
    Reply
  8. Roscoe said:

    Hey there this is kinda of off topic but I was wanting to
    know if blogs use WYSIWYG editors or if you have
    to manually code with HTML. I’m starting a blog soon but have no coding experience so I wanted to get
    guidance from someone with experience. Any help would be enormously appreciated!

    Also visit my web site; cheap flights

    January 31, 2021
    Reply
  9. Viola said:

    Good way of describing, and good article to take information regarding my presentation subject matter, which i am going to deliver in university.

    Here is my web site :: cheap flights

    February 1, 2021
    Reply
  10. Sherlene said:

    Thank you for the good writeup. It if truth be told used to be a enjoyment account it.
    Glance complicated to far introduced agreeable from you!
    By the way, how could we communicate?

    Here is my web site; cheap flights

    February 1, 2021
    Reply
  11. Veronica said:

    hey there and thank you for your information – I’ve certainly picked up anything new from right here.
    I did however expertise some technical points using this
    web site, as I experienced to reload the website many times previous to I
    could get it to load correctly. I had been wondering if your web host is OK?
    Not that I’m complaining, but sluggish loading instances times will sometimes affect your placement in google and could damage your quality score if advertising and marketing with Adwords.
    Well I’m adding this RSS to my e-mail and can look out for a lot more of your
    respective exciting content. Make sure you update this again soon.

    my blog post – cheap flights (tinyurl.com)

    February 2, 2021
    Reply
  12. Rosaline said:

    I got this site from my pal who shared with me on the topic of this site and at the moment this time I am visiting this
    web site and reading very informative articles or reviews here.

    Also visit my web site … cheap flights

    February 2, 2021
    Reply
  13. Marvin said:

    magnificent issues altogether, you just gained a emblem new reader.
    What may you suggest about your submit that you just made
    some days ago? Any sure?

    Here is my web-site … cheap flights (tinyurl.com)

    February 3, 2021
    Reply
  14. Benjamin said:

    I do trust all of the concepts you’ve presented on your post.
    They are very convincing and can definitely work.
    Still, the posts are very short for beginners. May you
    please extend them a little from subsequent time?
    Thanks for the post.

    Feel free to visit my web page cheap flights –
    http://tinyurl.com/y48wehwp

    February 12, 2021
    Reply

Leave a Reply

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