Stripe Checkout Integration with React

stripe + react
This post will show you: How to create a product in your Stripe dashboard. Integrate that product in our React js checkout component Successfully communicate with our server and redirect to the Stripe Checkout page.

Table of Contents

In this article, we will learn how to integrate “Stripe Checkout” with React with Hooks and Node js. However, if you would rather prefer to use Angular, here’s a guide we created for that.

You may also be interested in: “Angular 12: Features, Deprecations & Migration”

What is Stripe Checkout?

Stripe Checkout is a fully responsive and secure payment page hosted by Stripe. It lets you quickly receive payments and remove the friction of developing a compliant checkout page.

Goal

Today, we will learn how to:

1. How to create a product in your Stripe dashboard.

2. Integrate that product in our React js checkout component

3. Successfully communicate with our server and redirect to the Stripe Checkout page.

Prerequisites

  • Basic Knowledge of React js and React Hooks.
  • Nodejs version 10 or later
  • React 16.8 or later

Create a Product

However, before we start coding, let’s create a sample product which we will display on our checkout page. 

1. Create a Stripe account

Note: All product-related data and keys will be created in developers’ “test mode”. Sensitive data for production should be saved securely in your .env files.

  • Head over to Stripe’s website and create an account. 
  • Upon creating your account, you will be directed to your dashboard page. 

2. Create a Product

To do this, click on the Products link by the side and click the “Add Product” button. You can fill in the product details as shown below.  

 width=
 width=

Also, make sure you save the Product and also copy the price API ID for later use

Stripe Checkout Integration

Integrating our Stripe product requires two steps: Setting up our node server and calling our stripe product API in our React app.

1. Create-react-app

Let’s create our project using create-react-app using the command below:

npx create-react-app stripe-react-app

2. Setup a Node Express server

Next, we have to setup up our node server. To do this, we will install express and concurrently. Concurrently will allow us to run our node server and React app at the same time. npm i concurrently;  npm i express

3. Install Stripe

To use Stripe in our app, we will be installing three packages: stripe, react-stripe, and stripe-js packages.
Here’s the final version of our package.json file.

{
  "name": "stripe-react-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@stripe/react-stripe-js": "^1.4.1",
    "@stripe/stripe-js": "^1.17.0",
    "@testing-library/jest-dom": "^5.11.4",
    "@testing-library/react": "^11.1.0",
    "@testing-library/user-event": "^12.1.10",
    "concurrently": "^6.2.1",
    "express": "^4.17.1",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "4.0.3",
    "stripe": "^8.169.0",
    "web-vitals": "^1.0.1"
  },
  "homepage":"http://localhost:3000/",
  "proxy": "http://localhost:5000",
  "scripts": {
    "start-client": "react-scripts start",
    "start-server": "node server.js",
    "start": "concurrently "yarn start-client" "yarn start-server",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

You will notice how we set values for proxy and homepage. Similarly, we also used concurrently to start our node server and react app at the same time. 

7. Server.js

Create a server.js file in our home directory. Inside our server.js file, we will

  • Instantiate required packages
  • Create an API route: create-checkout-session. In this route, we will define 

payment_method_types, price, quantity, and the success_url and cancel_url 
The final version of the server.js file will be

const stripe = require('stripe')('sk_test_***************************************');
const express = require('express');
const app = express();
app.use(express.static('.'));
 
const YOUR_DOMAIN = 'http://localhost:3000/checkout';
 
app.post('/create-checkout-session', async (req, res) => {
 const session = await stripe.checkout.sessions.create({
   payment_method_types: [
     'card'
   ],
   line_items: [
     {
       // TODO: replace this with the `price` of the product you want to sell
       // price: '{{PRICE_ID}}',
       price: 'price_*************',
       quantity: 1,
     },
   ],
   mode: 'payment',
   success_url: `${YOUR_DOMAIN}?success=true`,
   cancel_url: `${YOUR_DOMAIN}?canceled=true`,
 });
 
 res.redirect(303, session.url)
});
 
app.listen(5000, () => console.log('Running on port 5000'));

You can find your secret API key in your dashboard. It starts with:  sk_test. You also get to use your product’s price ID in this file.

Frontend:  React App

In this section, we will be building our frontend components. Our frontend will comprise of our main page which will house the product card and a result page that will show if the checkout was successful or not. 

8. Product Card

  • First, we will create a components folder inside the src folder that will house our frontend files.
  • Next, create ProductDisplay.js and Message.js files. The ProductDisplay.js will display the product card and the Message.js will display the message gotten from our Stripe Checkout.
export const ProductDisplay = () => (
   <div className="wrapper">
     <div className="product-img">
       <img
         src="https://cdn.pixabay.com/photo/2017/12/20/09/36/orchid-3029574_1280.jpg"
         alt="Orchid Flower"
         height="420"
         width="327"
       />
     </div>
     <div className="product-info">
       <div className="product-text">
         <h1>Orchid Flower</h1>
         <h2>POPULAR HOUSE PLANT</h2>
         <p>
           The Orchidaceae are a diverse and
           <br />
           widespread family of flowering plants,
           <br />
           with blooms that are often
           <br />
           colourful and fragrant.{" "}
         </p>
       </div>
       <form action="/create-checkout-session" method="POST">
         <div className="product-price-btn">
           <p>
             <span>$20</span>
           </p>
           <button type="submit">buy now</button>
         </div>
       </form>
     </div>
   </div>
);

ProductDisplay.js
export const Message = ({ message }) => (
   <section>
     <p>{message}</p>
     <a className="product-price-btn" href="/">
       <button type="button">Continue</button>
     </a>
   </section>
);
 
 
				           Message.js   

And here’s our App.js file where both components are called.

import React, { useState, useEffect } from "react";
import "./App.css";
import { ProductDisplay } from "./components/ProductDisplay";
import { Message } from "./components/Message";
 
 
export default function App() {
 const [message, setMessage] = useState(");
 
 useEffect(() => {
   // Check to see if this is a redirect back from Checkout
   const query = new URLSearchParams(window.location.search);
 
   if (query.get("success")) {
     setMessage(" Yay! Order placed!   You will receive an email confirmation confirming your order.");
   }
 
   if (query.get("canceled")) {
     setMessage(
       "Order canceled -- please try again."
     );
   }
 }, []);
 
 return message ? <Message message={message} /> : <ProductDisplay />;
}

Project Structure

Here’s the final structure of the project:

 width=

Run npm start to start the project.

You can find a couple of test card numbers provided by Stripe here which you can use to test the Stripe checkout page.

Demo

Summary

There you have it. With Stripe Checkout and React, you can create a seamless eCommerce experience for your customers.

I hope that you have enjoyed reading this article. Feel free to share and add your valuable comments.

We are always eager to hear the opinions from fellow developers.

Unimedia Technology

Here at Unimedia Technology we have a team of React Developers that can help you develop your most complex stripe integrations.

Remember that at Unimedia, we are experts in emerging technologies, so feel free to contact us if you need advice or services. We’ll be happy to assist you.

Unimedia Technology

Your software development partner

We are a cutting-edge technology consultancy specialising in custom software architecture and development.

Our Services

Sign up for our updates

Stay updated, stay informed, and let’s shape the future of tech together!

Related Reads

Dive Deeper with These Articles

Explore more of Unimedia’s expert insights and in-depth analyses in the realm of software development and technology.

Let’s make your vision a reality!

Simply fill out this form to begin your journey towards innovation and efficiency.