How to Integrate Stripe Payment with Node js & React js Part 1

5 months ago admin Nodejs

In this tutorial, we will see how to integrate stripe payment with Node js and React js, in this first part we will handle the backend logic so I assume that you have already created a stripe account and you have your API keys.


Install the packages

First, let's install the packages that we need. 

                                                        
                                                                                                                        
npm install stripe --save

Create the route

Next, let's create the route I name it 'paymentRouter', this route will receive the amount to pay and send the client secret to the front end.

                                                            
                                                                                                                                
import express from 'express';
import stripe from 'stripe';

// This is your test secret API key.
const Stripe = new stripe('YOUR SECRET KEY');

const paymentRouter = express.Router();

paymentRouter.post("/pay", async (req, res) => {
    const { amount } = req.body;

    // Create a PaymentIntent with the order amount and currency
    const paymentIntent = await Stripe.paymentIntents.create({
        amount,
        currency: "usd",
        // In the latest version of the API, specifying the `automatic_payment_methods` parameter is optional because Stripe enables its functionality by default.
        automatic_payment_methods: {
            enabled: true,
        },
    });

    res.send({
        clientSecret: paymentIntent.client_secret,
    });
});


export default paymentRouter;

Use the route

Next, let's import and use the route inside the index.js file.

                                                            
                                                                                                                                
import express from "express";
import cors from "cors";
import mongoose from "mongoose";
import paymentRouter from './routes/paymentRouter.js';


const app = express();
app.use(express.json());

app.use(cors());

app.use('/order', paymentRouter);

//connect to the database
mongoose.connect('YOUR DATABASE LINK').then(() => {
    app.listen(3001, () => {
        console.log('App is running on port 3001');
    });
}).catch(error => console.log(error));