Ashutosh is an Application Developer at Thoughtworks. Apart from his love for Backend Development and DevOps, he has a keen interest in writing technical blogs and articles.
HomeBlogWeb DevelopmentHow to Integrate Stripe Payment Gateway in Node.js App
In this article, you’ll learn how to integrate Stripe Payments into your Node.js application. You’ll set up a sample web application using React and Express. If you’re looking to enter the world of Web Development, you can enroll in our course to learn Node.js with us. This article is helpful for those who are looking to integrate payments into their Node.js applications.
Payment gateways make it easier for you to integrate payments into your app and for users to pay through it. There are multiple payment gateways in the market, including Paytm, Razorpay, and others. But Stripe is one of the most often used gateways. Stripe's software and APIs are used by millions of companies, from small startups to major corporations, to collect payments, send payouts, and manage their businesses online. Not only does Stripe help with payment, but also helps you to send invoices to your customers after the payments using Stripe invoice.
It is pretty easy to set up Stripe in your app. You just need to create your account on Stripe and get the secret access keys. Then, you’re ready to use their API to process payments. In addition to production, they provide you with test credentials to test your payment flow. Stripe has very clean API documentation to get started. In this article, we’ll use React and Node.js to create our application and integrate Stripe payments into it. Explore our Full Stack Developer Course to work on similar live projects while learning.
Before getting started, make sure you have Node.js installed in your system. Alternatively, you can install it from here.
In order to use Stripe, you need to register yourself on Stripe.
If you have already registered, you can sign in using the link below Create Account button.
Stripe Requirements
Once you sign in to your Stripe account, you may be required to go through some necessary steps in order to activate payments. Make sure you go through it. After you’re done, you’ll be redirected to the Stripe Dashboard similar to below.
On the top left of the dashboard, you’ll find an option to create a new account. Click on New Account, add your Account Name and Country of Operation and click on Create account.
Once you create a new account, you’ll be required to activate the payments again for this account.
Once you’re done with all the steps mentioned above, click on the Developers button on the top-right of the dashboard. Then click on the API Keys to go to the page where you’ll get your Standard Keys to authenticate API requests.
These keys are test data and cannot be used in actual payments. Once you activate your account, you can enable live keys as well.
Before jumping to the front-end, you’re going to create the Node.js server that will interact with Stripe and handle the payments. For the sake of simplicity, we’ll use as few dependencies as required. The dependencies required for the backend are as follows:
While you’ll create a simple application in this article, you can create a far better web application as you learn Node.js at KnowledgeHut.
Before getting started, create a folder named backend, where you can store all your backend code right here. Now, fire up your terminal in this directory and follow along.
To create a Node project, use the below command:
>> npm init
It will ask you for some details, which are not that important for the sake of this article.
After you’re done, you will find a package.json file in your backend directory. Now, open this directory in your favorite code editor and create a file named index.js inside it. Make sure the filename is the same as the entry point you have set during the project initialization.
Now, use the command below to install all the dependencies mentioned above:
>> npm i cors express stripe dotenv nodemon
Let us also add the script to start the Node.js server in the package.json file.
{
"name": "backend",
"version": "1.0.0",
"description": "Sample backend server for integrating Stripe payments",
"main": "index.js",
"scripts": {
"start": "nodemon index.js"
},
"author": "Ashutosh Krishna",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^16.0.1",
"express": "^4.18.1",
"nodemon": "^2.0.19",
"stripe": "^9.14.0",
"uuid": "^8.3.2"
}
}
Now, create a file named .env where you will store your secret keys. The contents of the file should be similar to the below:
STRIPE_PUBLISHABLE_KEY=your-publishable-key-here STRIPE_SECRET_KEY=your-secret-key-here
We can load these environment variables using the dotenv dependency and then access them as process.env.KEY_NAME.
Now let us create our server in the index.js file.
In the script below, we’ll import the required dependencies first. Then, create an app using express. The required middleware is also defined. A sample route is created, which just responds with a Hello World message. The server listens on port 8000.
Notice how we load the environment variables using the dotenv dependency and used them.
const cors = require("cors"); const express = require("express"); require("dotenv").config(); const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY); const app = express(); // Middlewares here app.use(express.json()); app.use(cors()); // Routes here app.get("/", (req, res) => { res.send("Hello World"); }); // Listen app.listen(8000, () => { console.log("Server started at port 8000"); });
Once you run the server using the npm start command, you can go to http://localhost:8000 on your browser, and you will find your Hello World message there.
Now you need a POST route that can be hit by the front-end. In this route, you’ll create a customer and will charge the amount. Let us create this route now.
app.post("/api/create-checkout-session", async (req, res) => { const { product } = req.body; const session = await stripe.checkout.sessions.create({ payment_method_types: ["card"], line_items: [ { price_data: { currency: "inr", product_data: { name: product.name, }, unit_amount: product.price * 100, }, quantity: product.quantity, }, ], mode: "payment", success_url: "http://localhost:3000/success", cancel_url: "http://localhost:3000/cancel", }); res.json({ id: session.id }); });
In the above script, an asynchronous “/api/create-session-checkout” POST route is created. Inside the function, the product is fetched from the request's body. This product shall be passed from the front end. Next, you’re creating a Stripe checkout session where you declare the payment method type as card, the price and product details, the mode, and the success and cancel URLs. You can add more details about the product if you wish to. Refer to the Stripe documentation to learn more about this. The function responds with an id, that is, the session's id. This id is used by Stripe later. That’s pretty much about the backend part of our application.
Now that you have a backend server ready, it’s time to create a React app that can make use of the backend server. When you install npm, you get npx too. For the sake of the article, you’re going to create a React app named frontend. To create a React app, you can use the below command:
>> npx create-react-app frontend
The command will set up a sample React app. To see if the setup is working fine, you can run the npm start command. If you see the below output, your setup is ready.
Now, before you start working on the front-end of the application, you need to install a few dependencies here too. They are:
Now, as always, to install the above-mentioned dependencies, you need to run the following command:
>> npm i react-router-dom @stripe/stripe-js react-bootstrap
Here comes the main frontend task now. You’re going to create three components - one for the checkout page where you’ll have a simple product card with a pay button, one for the success page and the final one for the cancel page. These all components will be present inside a components directory inside the src folder.
Inside the components directory, create a file named StripePayment.js. Let us import all the dependencies we’d be using in the component:
import React, { useState } from "react"; import "bootstrap/dist/css/bootstrap.min.css"; import Button from "react-bootstrap/Button"; import Card from "react-bootstrap/Card"; import { loadStripe } from "@stripe/stripe-js";
Now, create an empty function called StripePayment and export it as below:
function StripePayment() { } export default StripePayment;
Now, we will require something to buy. Let us create a simple product with few details in the function as below:
function StripePayment() { const [product, setProduct] = useState({ name: "Go FullStack with KnowledgeHut", price: 1000, productOwner: "KnowledgeHut", description: "This beginner-friendly Full-Stack Web Development Course is offered online in blended learning mode, and also in an on-demand self-paced format.", quantity: 1, }); } export default StripePayment;
To create a product, we have used the useState() function. The product contains few details such as name, price, productOwner, description and quantity. Now, let us create a product card using react-bootstrap inside the function.
import React, { useState } from "react"; import "bootstrap/dist/css/bootstrap.min.css"; import Button from "react-bootstrap/Button"; import Card from "react-bootstrap/Card"; function StripePayment() { const [product, setProduct] = useState({ name: "Go FullStack with KnowledgeHut", price: 1000, productOwner: "KnowledgeHut", description: "This beginner-friendly Full-Stack Web Development Course is offered online in blended learning mode, and also in an on-demand self-paced format.", quantity: 1, }); return ( <Card style={{ width: "20rem" }}> <Card.Img variant="top" src="https://images.pexels.com/photos/12428359/pexels-photo-12428359.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1" /> <Card.Body> <Card.Title>{product.name}</Card.Title> <Card.Text>{product.description}</Card.Text> <Button variant="primary" onClick={makePayment}> Buy Now for {product.price} </Button> </Card.Body> </Card> ); } export default StripePayment;
The above script is pretty easy to understand where you have created a Bootstrap card with top-image, card title, card body text and a button. We have also added an onClick parameter on the button, which calls a makePayment function. Let us create the makePayment function now.
const makePayment = async () => { const stripe = await loadStripe("your-publishable-key"); const body = { product }; const headers = { "Content-Type": "application/json", }; const response = await fetch( "http://localhost:8000/api/create-checkout-session", { method: "POST", headers: headers, body: JSON.stringify(body), } ); const session = await response.json(); const result = stripe.redirectToCheckout({ sessionId: session.id, }); if (result.error) { console.log(result.error); } };
The makePayment is an asynchronous function that makes requests to our backend server. An instance of Stripe is loaded using the loadStripe function. The product is added in the body of the request. Do you remember we sent a session id in the response from the backend? This session id is then extracted from the response and provided to the redirectToCheckout function from the stripe dependency.
In addition to the checkout page, you’ll create two other pages for success and canceled transactions. Inside the components directory, create two files - Success.js and Cancel.js.
Success.js import React from "react"; function Success() { return ( <> <h2>Thanks for your order!</h2> <h4>Your payment is successful.</h4> <p> We appreciate your business! If you have any questions, please email us at <a href="mailto:orders@example.com">orders@example.com</a>. </p> <div> </div> </> ); } export default Success; Cancel.js import React from "react"; function Cancel() { return ( <> <h4>Oops! Your payment has been cancelled.</h4> <p> We appreciate your business! If you have any questions, please email us at <a href="mailto:orders@example.com">orders@example.com</a>. </p> <div> <button> Go to Home page</button> </div> </> ); } export default Cancel;
Now that all the components are ready, you’ll need to route them as below:
To route the pages, you’re going to use react-router-dom as below:
import React from "react"; import { BrowserRouter, Routes, Route } from "react-router-dom"; import StripePayment from "./components/StripePayment"; import Success from "./components/Success"; import Cancel from "./components/Cancel"; function App() { return ( <BrowserRouter> <Routes> <Route path="/success" element={<Success />} /> <Route path="/cancel" element={<Cancel />} /> <Route path="/" element={<StripePayment />} /> </Routes> </BrowserRouter> ); } export default App;
With this, the frontend of the application is ready too. It might not look that good, but it fulfills its purpose. You can run your backend and frontend of the application using the npm start command.
In order to test your integration, you’re not going to use real cards for sure. To help you with this, Stripe provides you with test cards.
Test cards let you simulate several scenarios:
The test cards can only be used when you’re using Stripe Test Keys. You can find a lot of cards on this page.
Looking to level up your coding skills? Join our Python course training and unlock endless possibilities. From web development to data analysis, Python is the language of the future. Don't miss out on this opportunity to become a Python pro!
In this article, you learned how to integrate Stripe payment gateway into your Node.js application. You created a sample React Application and a Node.js server to interact with Stripe APIs. This was a very basic example of payment integration. Stripe supports many more features such as Subscription, Recurring Payments, etc.
Stripe provides you with a dependency called @stripe/stripe-js that helps you use Stripe.js as an ES module. You need to have a backend server to interact with Stripe APIs. In addition to that, there are several third-party dependencies available on npmjs.org too, that can help you integrate Stripe payments easily in your application. One of the most popular is react-stripe-checkout.
Payment gateways make it easier for you to integrate payments into your app and for users to pay through it. Stripe payment gateway is one of them. It is used by millions of companies of all kinds, from small startups to major corporations, to collect payments, send payouts, and manage their businesses online.
Stripe.js is a Javascript library that helps you interact with Stripe APIs. When the user fills the details on the checkout form, Stripe.js passes the card details to the Stripe server, where it is verified and stored if it is correct. It then sends a temporary token and the personal details to your server. By using Stripe.js, your server doesn’t need to handle any card data, and hence it’s secure.
Name | Date | Fee | Know more |
---|