How to Integrate Stripe Payments in React App using Express ?
Last Updated :
24 Apr, 2025
Many of the projects you develop might have a requirement to integrate the payment module in your application. Stripe serves as a payment processing platform designed to help applications securely accept and handle online payments. In this article, we will see how we can easily integrate payment systems in our application.
Approach to integrate Stripe Payments in React App:
- List all the requirements for the project and create the folder structure of the project accordingly.
- Choose and install the required dependencies necessary for the project.
- Create an account on Stripe's website and get the API keys.
- Course, PaymentForm and PaymentSuccess are custom components, and are present in the ./src directory.
- In the default functional component named `App`, implement routing to handle and display different pages.
- Refer to Stripe's documentation page for getting help on how to integrate it with ReactJS.
Steps to Integrate Stripe Payments in React App:
Step 1: Create a new React App project by opening a terminal and using the following command:
npx create-react-app stripe-frontend
Step 2: Navigate to your project folder created above, i.e. 'stripe-frontend', using the following command:
cd stripe-frontend
Step 3: Install the necessary packages for this project
npm install --save axios react-router-dom @stripe/react-stripe-js @stripe/stripe-js
Step 4: Install Tailwind CSS & daisyUI plugin
npm install -D tailwindcss daisyui
Step 5: Configure Tailwind CSS
npx tailwindcss init
Now, paste the below snippet in the `tailwind.config.js` file created after the above step.
/** @type {import('tailwindcss').Config} */
module.exports = {
content: ["./src/**/*.{html,js}"],
theme: {
extend: {},
},
plugins: [require("daisyui")],
}
Step 6: Add the Tailwind directives to CSS file, i.e. `index.css` of our React project.
@tailwind base;
@tailwind components;
@tailwind utilities;
Folder Structure:
Frontend Folder Structure
The updated dependencies in package.json file will look like:
"dependencies": {
"@stripe/react-stripe-js": "^2.5.1",
"@stripe/stripe-js": "^3.0.6",
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"axios": "^1.6.7",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.22.2",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"devDependencies": {
"daisyui": "^4.7.2",
"tailwindcss": "^3.4.1"
}
Steps to obtain Stripe's API key
Step 1: Create an account on Stripe
NOTE: Don't forget to select the country as "United States" to be able to test Stripe Payment API in test/developer mode. If you select another country, e.g. "India" then you will have to put your business details and a lot of information.
Create Account on StripeStep 2: Navigate to the following URL: https://dashboard.stripe.com/test/apikeys. This will give you API keys to be used for our project.
Getting the Stripe API Key from the Stripe websiteStep 3: Create an .env file and hide your PUBLISHABLE_KEY there.
REACT_APP_STRIPE_PUBLISHABLE_KEY=<YOUR_STRIPE_PUBLISHABLE_KEY>
Example of Integrating Stripe Payments in React App
Code Example: Create the required files as seenin folder structure and add the following codes.
JavaScript
//App.js
import { BrowserRouter, Route, Routes } from "react-router-dom";
import "./App.css";
import StripePayment from "./StripePayment";
import Course from "./Course";
import PaymentSuccess from "./PaymentSuccess";
const App = () => {
return (
<div className="App">
<BrowserRouter>
<Routes>
<Route path="/" element={<Course />} />
<Route path="payment" element={<StripePayment />} />
<Route path="success" element={<PaymentSuccess />} />
</Routes>
</BrowserRouter>
</div>
);
};
export default App;
JavaScript
//StripePayment.js
import React, { useState, useEffect } from "react";
import { loadStripe } from "@stripe/stripe-js";
import { Elements } from "@stripe/react-stripe-js";
import axios from "axios";
import PaymentForm from "./PaymentForm";
const stripe = loadStripe('Your API KEY');
const StripePayment = () => {
const [clientSecret, setClientSecret] = useState(null);
useEffect(() => {
axios
.post("http://localhost:4000/create-payment-intent", {
items: [{ id: 1, name: "momos", amount: 40.00 }],
})
.then((resp) => setClientSecret(resp.data.clientSecret));
}, []);
const options = {
clientSecret,
theme: "stripe",
};
return (
clientSecret && (
<Elements stripe={stripe} options={options}>
<PaymentForm></PaymentForm>
</Elements>
)
);
};
export default StripePayment;
JavaScript
//Course.js
const Course = () => {
return (
<div className="flex justify-center">
<div className="card w-96 bg-gray-200 shadow-xl">
<figure class="px-10 pt-10">
<img
src="https://media.geeksforgeeks.org/
wp-content/cdn-uploads/20210420155809/gfg-new-logo.png"
alt="GeeksForGeeks Course"
/>
</figure>
<div className="card-body">
<h2 className="card-title">
Full Stack Development with React & Node JS - Live
</h2>
<p>
Looking to become a full-stack developer? This live, online course
with a focus on the popular JS library React for front-end and
Node.js for back-end along with APIs and deployment is a must-have
program for any aspiring developer.
</p>
<p>
<b>Course Price: $40.00</b>
</p>
<div className="card-actions justify-center">
<a
className="btn btn-primary rounded-lg text-white mt-5"
href="/payment"
>
Purchase
</a>
</div>
</div>
</div>
</div>
);
};
export default Course;
JavaScript
//PaymentForm.js
import React, { useState } from "react";
import {
PaymentElement,
useStripe,
useElements,
} from "@stripe/react-stripe-js";
const PAYMENT_SUCESS_URL = "http://localhost:3000/success";
const PaymentForm = () => {
const stripe = useStripe();
const elements = useElements();
const [message, setMessage] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const handleSubmit = async (e) => {
e.preventDefault();
if (!stripe || !elements) return;
setIsLoading(true);
setMessage("Payment in Progress");
const resp = await stripe.confirmPayment({
elements,
confirmParams: {
return_url: PAYMENT_SUCESS_URL,
},
});
if (resp.error) setMessage("Some Error Occurred !!");
setIsLoading(false);
};
return (
<div className="container mx-auto">
<form onSubmit={handleSubmit}>
<div className="card w-100 bg-base-100 bg-gray-200 shadow-2xl rounded-lg">
<div className="card-body p-6">
<h1 className="card-title font-bold text-2xl mb-4 justify-center">
Complete your payment here!
</h1>
<PaymentElement />
<div className="card-actions justify-center">
<button
className="btn btn-primary rounded-xl text-white px-4 py-2 mt-6"
disabled={isLoading || !stripe || !elements}
>
{isLoading ? "Loading..." : "Pay now"}
</button>
</div>
{message && <div>{message}</div>}
</div>
</div>
</form>
</div>
);
};
export default PaymentForm;
JavaScript
//PaymentSuccess.js
const PaymentSuccess = () => {
return (
<h1 className="font-bold text-xl">Your Payment is successful !</h1>
);
}
export default PaymentSuccess;
To start the frontend runt eh following command.
npm start
Steps to Setup Stripe Payments in Backend
Step 1: Create a npm project inside a new folder `stripe-backend` folder as follows:
mkdir stripe-backend
cd stripe-backend
Step 2: Initialize the Node application using the following command.
npm init -y
Step 3: Install necessary packages
npm install --save express cors body-parser stripe dotenv
Folder Structure:
Backend Folder Structure
The updated Dependencies in package.json file of backend will look like:
"dependencies": {
"body-parser": "^1.20.2",
"cors": "^2.8.5",
"express": "^4.18.3",
"stripe": "^14.19.0"
}
Step 4: Create a .env file in your backend root folder and paste the "Secret key" from Stripe inside it to hide the key.
STRIPE_API_SRECRET_KEY=<YOUR_STRIPE_API_SRECRET_KEY>
Step 5: Create a file `server.js` which will run our Express Server and serve the React App with the CLIENT_SECRET.
JavaScript
//server.js
require('dotenv').config()
const express = require("express");
const cors = require("cors");
const bodyParser = require("body-parser");
const stripe = require("stripe")('<API KEY>');
const app = express();
const PORT = process.env.PORT || 4000;
app.use(cors());
app.use(bodyParser.json());
const calculateTotalOrderAmount = (items) => {
return items[0].amount * 100;
};
app.post("/create-payment-intent", async (req, res) => {
const { items } = req.body;
const paymentIntent = await stripe.paymentIntents.create({
amount: calculateTotalOrderAmount(items),
currency: "usd",
description: "This is for GFG Stripe API Demo",
automatic_payment_methods: {
enabled: true,
},
});
res.send({
clientSecret: paymentIntent.client_secret,
});
});
app.listen(PORT, () => {
console.log(`Server started on PORT ${PORT}`);
});
To start the backend server run the following command.
node server.js
Output:
.gif)
Similar Reads
How to Integrate Stripe Payment Gateway in Node.js ?
Integrating Stripe in Node allows one to make and manage online payments. Stripe provides developer-friendly API to set up the payment gateway to handle secure transactions.Payment gateways help the user to make their payments. There are many payment gateways available in the market like Razorpay, G
3 min read
How to Add Express to React App using Gulp ?
When building a web application with ReactJS, you may need to include a backend server for handling server-side logic and API requests. Express is a popular choice for creating backend servers in Node.js. In this tutorial, we'll explore how to integrate Express with a React app using Gulp as the bui
3 min read
How to Install Express in a Node Project?
ExpressJS is a popular, lightweight web framework for NodeJS that simplifies the process of building web applications and APIs. It provides a robust set of features for creating server-side applications, including routing, middleware support, and easy integration with databases and other services.Be
2 min read
How to use express in typescript ?
In this article, we will see how to use Express in TypeScript. The TypeScript is a superset of JavaScript that provides type notation with the JavaScript, so we can handle our server, and very scalable for the future. Express is web framework helps to create server-side handling with the help of Nod
2 min read
How to integrate React-PDF in ReactJS ?
React-PDF is a package that helps users to display PDF files in their React app. By using the react-pdf package we can add PDF files in our React app as if they were images. To use the latest version of react-pdf package, our project should use React 16.3 or later. We can integrate react-pdf using t
2 min read
How to use third-party middleware in Express JS?
Express JS is a robust web application framework of Node JS which has the capabilities to build web and mobile applications. Middleware is the integral part of the framework. By using the third party middleware we can add additional features in our application.PrerequisitesNode JSExpress JSPostmanTa
2 min read
How To Make A GET Request using Postman and Express JS
Postman is an API(application programming interface) development tool that helps to build, test and modify APIs. In this tutorial, we will see how To Make A GET Request using Postman and Express JS PrerequisitesNode JSExpress JSPostmanTable of Content What is GET Request?Steps to make a GET Request
3 min read
How to Create a Simple Server Using ExpressJS?
The server plays an important role in the development of the web application. It helps in managing API requests and communication between the client and the backend. ExpressJS is the fast and famous framework of the Node.Js which is used for creating the server.In this article, we will create a simp
3 min read
How to Integrate Paytm Test API in Node.js ?
Paytm stands for Pay through mobile is used for online transactions. We can integrate it with our node.js application using Paytm developer API. This API can be used for testing as well as for development purposes. Â There are two methods for doing so: Test API and Production API. Production API will
2 min read
How to pass value between Screens in React Native ?
With React Navigation, we can also pass values or parameters between screens in React Native. We will create a simple stack navigator with 2 screens and pass values from one screen to another. Letâs watch a short video to see what we are going to create.Demo VideoStep-by-Step ImplementationStep 1: C
6 min read