In today’s digital economy, integrating a secure and efficient payment gateway is crucial for businesses offering online transactions. PhonePe, one of India’s leading payment platforms, provides a seamless API for accepting payments. In this guide, we will walk you through the step-by-step process of integrating the PhonePe payment gateway into your React (Frontend) and Node.js (Backend) application.
Prerequisites
Before getting started, ensure you have the following:
- A PhonePe Merchant Account (register on the PhonePe developer portal)
- Node.js installed on your system
- React.js for the frontend
- Axios for making API requests
Step 1: Setting Up the Backend (Node.js & Express)
First, let’s create the backend to handle payment requests and responses.
1.1 Install Dependencies
Run the following command to initialize a Node.js project and install required packages:
mkdir phonepe-payment && cd phonepe-payment
npm init -y
npm install express dotenv crypto axios cors
1.2 Create the server.js
File
Create a server.js
file and configure the Express server:
import express from "express";
import cors from "cors";
import dotenv from "dotenv";
import crypto from "crypto";
import axios from "axios";
dotenv.config();
const app = express();
const PORT = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
const PHONEPE_BASE_URL = "https://api.phonepe.com/apis/hermes/pg/v1";
const MERCHANT_ID = process.env.MERCHANT_ID;
const SALT_KEY = process.env.SALT_KEY;
const SALT_INDEX = process.env.SALT_INDEX;
app.post("/create-payment", async (req, res) => {
try {
const { amount } = req.body;
if (!amount || amount <= 0) {
return res.status(400).json({ error: "Invalid amount" });
}
const transactionId = "TXN_" + Date.now();
const payload = {
merchantId: MERCHANT_ID,
transactionId,
amount: amount * 100, // Convert to paisa
redirectUrl: "http://localhost:5173/success",
callbackUrl: "http://localhost:5000/payment-status"
};
const payloadString = JSON.stringify(payload);
const checksum = crypto.createHash("sha256").update(payloadString + SALT_KEY).digest("hex") + "###" + SALT_INDEX;
const response = await axios.post(`${PHONEPE_BASE_URL}/initiate`, payload, {
headers: { "X-VERIFY": checksum, "Content-Type": "application/json" }
});
res.json({ checkoutPageUrl: response.data.data.instrumentResponse.redirectInfo.url });
} catch (error) {
console.error("Payment Error:", error);
res.status(500).json({ error: "Payment initiation failed" });
}
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
1.3 Create the .env
File
Create a .env
file and add:
MERCHANT_ID=your_merchant_id
SALT_KEY=your_salt_key
SALT_INDEX=your_salt_index
Step 2: Setting Up the Frontend (React.js)
Now, let’s build a simple React frontend to trigger payments.
2.1 Install React and Axios
npx create-react-app phonepe-frontend
cd phonepe-frontend
npm install axios
2.2 Modify App.js
Edit src/App.js
to create a payment button:
import { useState } from "react";
import axios from "axios";
function App() {
const [amount, setAmount] = useState(100);
const backendUrl = "http://localhost:5000";
const handlePayment = async () => {
try {
const response = await axios.post(`${backendUrl}/create-payment`, { amount });
if (response.data.checkoutPageUrl) {
window.location.href = response.data.checkoutPageUrl;
}
} catch (error) {
console.error("Payment error:", error);
}
};
return (
<div className="flex flex-col items-center justify-center h-screen bg-gray-100 p-6">
<div className="bg-white p-6 rounded-lg shadow-lg text-center w-96">
<h2 className="text-2xl font-bold mb-4">Make a Payment</h2>
<input
type="number"
className="border rounded p-2 mb-4 w-full"
value={amount}
onChange={(e) => setAmount(Number(e.target.value))}
min="1"
/>
<button
onClick={handlePayment}
className="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600 transition"
>
Pay Now
</button>
</div>
</div>
);
}
export default App;
Step 3: Running the Application
Now, let’s run our application:
3.1 Start the Backend
cd phonepe-payment
node server.js
3.2 Start the Frontend
cd phonepe-frontend
npm start
Once everything is running, open your browser and test the integration by entering an amount and clicking Pay Now.
Download Source Code
Conclusion
By following these steps, you have successfully integrated the PhonePe Payment Gateway in your React and Node.js application. This setup allows users to make secure online payments seamlessly. You can further enhance this by implementing database storage for transactions, webhooks for real-time updates, and mobile payment support.
🚀 Start integrating PhonePe today and simplify online payments for your users!