In this blog post, we will walk you through the process of integrating the Stripe payment gateway into a Node.js and React application. We will set up a backend server with Express to handle payment processing and create a React frontend to initiate payments. This example will demonstrate how to create a simple product and process payments using Stripe’s API.
Prerequisites
Before we start, ensure you have the following installed:
- Node.js and npm
- Basic knowledge of React and Node.js
- A Stripe account
Setting Up the Backend with Node.js and Express
First, let’s set up the backend server using Node.js and Express, and integrate Stripe for payment processing.
Step 1: Install Dependencies
Run the following command to install the necessary packages:
bashCopy codenpm install express cors stripe
Step 2: Create the Server
Create a file named server.js
and add the following code:
javascriptCopy codeconst express = require('express');
const cors = require('cors');
const stripe = require('stripe')('your-stripe-secret-key');
const app = express();
app.use(cors());
app.use(express.json());
app.get('/', (req, res) => {
res.send('Hello World');
});
app.post('/payment', async (req, res) => {
try {
const product = await stripe.products.create({
name: "T-Shirt",
});
const price = await stripe.prices.create({
product: product.id,
unit_amount: 100 * 100, // 100 INR
currency: 'inr',
});
const session = await stripe.checkout.sessions.create({
line_items: [
{
price: price.id,
quantity: 1,
}
],
mode: 'payment',
success_url: 'http://localhost:3000/success',
cancel_url: 'http://localhost:3000/cancel',
customer_email: 'demo@gmail.com',
});
res.json({ url: session.url });
} catch (error) {
console.error('Error creating payment session:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
This code sets up an Express server with a /payment
endpoint that creates a product, a price, and a Stripe checkout session. The session URL is then returned to the client.
Step 3: Set Up Environment Variables
For security reasons, it’s best practice to use environment variables to store your Stripe secret key. Create a .env
file in your project root and add your Stripe secret key:
makefileCopy codeSTRIPE_SECRET_KEY=your-stripe-secret-key
Update your server.js
to use the environment variable:
javascriptCopy codeconst stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
Don’t forget to require the dotenv
package at the top of your server.js
:
javascriptCopy coderequire('dotenv').config();
Setting Up the Frontend with React
Next, let’s create the React frontend to interact with our backend.
Step 1: Create a React App
If you don’t already have a React application, you can create one using Create React App:
bashCopy codenpx create-react-app stripe-payment
cd stripe-payment
Step 2: Install Axios
We’ll use Axios for making HTTP requests to our backend. Install Axios with the following command:
bashCopy codenpm install axios
Step 3: Create the React Component
Replace the content of src/App.js
with the following code:
javascriptCopy codeimport React from 'react';
import axios from 'axios';
function App() {
const buyFunction = async () => {
try {
const response = await axios.post('http://localhost:3000/payment');
if (response.status === 200) {
window.location.href = response.data.url;
}
} catch (error) {
console.error('Error processing payment:', error);
}
};
return (
<div>
<h1>Buy a T-Shirt</h1>
<button onClick={buyFunction}>Buy Now</button>
</div>
);
}
export default App;
This code creates a simple React component with a button to initiate the payment process. When the button is clicked, it sends a request to the backend to create a Stripe checkout session and then redirects the user to the Stripe checkout page.
Step 4: Styling (Optional)
You can add some basic styling in src/App.css
to make the application look nicer:
cssCopy codebutton {
display: block;
margin: 20px auto;
padding: 10px 20px;
font-size: 16px;
background-color: #6772e5;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #5469d4;
}
Running the Application
To run the application, follow these steps:
- Start the backend server:
bashCopy codenode server.js
- Start the React frontend:
bashCopy codenpm start
Visit http://localhost:3000
in your browser. You should see a “Buy Now” button, and when you click it, you’ll be redirected to the Stripe checkout page to complete the purchase.
Download Source Code
Conclusion
In this tutorial, we learned how to integrate Stripe into a MERN stack application to handle payments. We set up an Express server with endpoints to create a product, a price, and a Stripe checkout session, and we built a React frontend to interact with our server. This basic setup can be expanded and customized to fit more complex requirements, such as adding authentication, displaying different products, and handling post-payment processes.
Feel free to ask any questions or share your thoughts in the comments below. Happy coding!