Integrating Payment Gateway in a MERN App

 Introduction

E-commerce and online services often require secure, seamless payment processing. In a MERN stack application (MongoDB, Express.js, React, Node.js), integrating a payment gateway lets you accept payments directly from your app. This blog explains how to integrate a popular payment gateway like Stripe in your MERN stack project.

Setting Up the Backend with Node and Express

First, install the Stripe Node.js library:

npm install stripe

In your Express backend, initialize Stripe with your secret key and create an endpoint to handle payment intents:

const express = require('express');

const Stripe = require('stripe');

const router = express.Router();

const stripe = new Stripe('sk_test_YOUR_SECRET_KEY'); // Replace with your real secret key

router.post('/create-payment-intent', async (req, res) => {

  const { amount, currency } = req.body;

  try {

    const paymentIntent = await stripe.paymentIntents.create({

      amount,

      currency,

    });

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

  } catch (error) {

    res.status(500).send({ error: error.message });

  }

});

module.exports = router;

This creates a /create-payment-intent endpoint your React frontend can call to start a payment.

Integrating Payments in the React Frontend

In your React app, install the Stripe.js library and React Stripe.js components:

npm install @stripe/stripe-js @stripe/react-stripe-js

In your component, load Stripe, create a payment intent, and display a payment form:

import { loadStripe } from '@stripe/stripe-js';

import { Elements, CardElement, useStripe, useElements } from '@stripe/react-stripe-js';

const stripePromise = loadStripe('pk_test_YOUR_PUBLIC_KEY'); // Replace with your real public key

function CheckoutForm() {

  const stripe = useStripe();

  const elements = useElements();

  const handleSubmit = async (e) => {

    e.preventDefault();

    const { clientSecret } = await fetch('/create-payment-intent', {

      method: 'POST',

      headers: { 'Content-Type': 'application/json' },

      body: JSON.stringify({ amount: 5000, currency: 'usd' }),

    }).then((res) => res.json());

    const result = await stripe.confirmCardPayment(clientSecret, {

      payment_method: { card: elements.getElement(CardElement) },

    });

    if (result.error) console.error(result.error.message);

    else if (result.paymentIntent.status === 'succeeded') alert('Payment successful!');

  };

  return (

    <form onSubmit={handleSubmit}>

      <CardElement />

      <button type="submit" disabled={!stripe}>Pay</button>

    </form>

  );

}

// In your main component

<Elements stripe={stripePromise}>

  <CheckoutForm />

</Elements>

Conclusion

Integrating a payment gateway like Stripe in your MERN app ensures secure, smooth payment processing. By coordinating your Express backend with your React frontend using Stripe’s APIs, you can provide a professional payment experience for your users. Always remember to keep secret keys safe and use test keys during development.

Learn MERN Stack Training Course

Read More:

Authentication in MERN Stack Using JWT

React Router DOM: Simplifying Navigation

Using Axios to Handle API Requests in React

How to Build a Real-Time Chat App Using MERN and Socket.io

Visit Quality Thought Training Institute

Get Direction

Comments

Popular posts from this blog

DevOps vs Agile: Key Differences Explained

Regression Analysis in Python

Top 10 Projects to Build Using the MERN Stack