
This blog post provides a detailed tutorial on integrating the Razorpay payment gateway into a website using ExpressJS and NodeJS. It covers the concept of payment gateways, the steps to create an account with Razorpay, and the practical implementation of the payment process, including order creation, payment verification, and handling responses.
In this tutorial, we will learn how to integrate the Razorpay payment gateway into our websites using ExpressJS and NodeJS. Payment gateways are essential for e-commerce websites, allowing users to make payments directly to your bank account without needing to implement APIs for every bank. Razorpay simplifies this process by providing a unified API for various payment methods.
A payment gateway is a service that authorizes credit card or direct payments for e-commerce websites. It acts as a bridge between your website and the bank, ensuring that transactions are processed securely. For instance, if you have an e-commerce website, when a user purchases a product, the payment should be processed seamlessly, regardless of the user's bank or payment method.
Razorpay is a popular payment gateway in India that supports multiple payment methods, including credit cards, debit cards, UPI, and net banking. It charges a commission ranging from 1% to 3% per transaction, making it a cost-effective solution for businesses.
To start using Razorpay, you need to create an account on their official website. You can sign up using your email or phone number and select your country (currently, Razorpay operates in India, Singapore, and the United States). After signing up, you will need to verify your account.
Once your account is verified, Razorpay will provide you with an API key and a secret key. These keys are essential for authenticating your requests to the Razorpay server. Keep your secret key confidential to ensure the security of your transactions.
To integrate Razorpay into your ExpressJS project, you need to install the Razorpay package. You can do this using npm:
npm install razorpay
Create a new ExpressJS application and set up the necessary routes for handling payments. Below is a basic structure of your app.js file:
const express = require('express');
const Razorpay = require('razorpay');
const app = express();
const port = 3000;
app.use(express.json());
const razorpay = new Razorpay({
key_id: 'YOUR_API_KEY',
key_secret: 'YOUR_SECRET_KEY'
});
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
You need to create a route to handle order creation. This route will receive the payment amount from the client and create an order in Razorpay:
app.post('/create-order', async (req, res) => {
const options = {
amount: req.body.amount * 100, // Convert to paise
currency: "INR",
receipt: `receipt_${new Date().getTime()}`
};
try {
const order = await razorpay.orders.create(options);
res.json(order);
} catch (error) {
res.status(500).send(error);
}
});
On the client side, you will need to create a checkout form where users can enter the amount they wish to pay. When the user clicks the pay button, you will call the /create-order route to create an order and then initiate the Razorpay checkout:
<form id="payment-form">
<input type="number" id="amount" placeholder="Enter amount" required />
<button type="submit">Pay</button>
</form>
<script src="https://checkout.razorpay.com/v1/checkout.js"></script>
<script>
document.getElementById('payment-form').addEventListener('submit', async (e) => {
e.preventDefault();
const amount = document.getElementById('amount').value;
const response = await fetch('/create-order', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ amount })
});
const orderData = await response.json();
const options = {
key: 'YOUR_API_KEY', // Enter the Key ID generated from the Dashboard
amount: orderData.amount,
currency: orderData.currency,
name: 'Demo Store',
description: 'Test Transaction',
order_id: orderData.id,
handler: function (response) {
// Handle successful payment
console.log(response);
},
prefill: {
name: 'Customer Name',
email: 'customer@example.com',
contact: '9999999999'
},
theme: {
color: '#3399cc'
}
};
const rzp = new Razorpay(options);
rzp.open();
});
</script>
After the payment is completed, Razorpay will send a response back to your server. You need to verify this response to ensure that the payment was successful. Create a route to handle payment verification:
app.post('/verify-payment', (req, res) => {
const { order_id, payment_id, signature } = req.body;
const generated_signature = crypto.createHmac('sha256', 'YOUR_SECRET_KEY').update(order_id + '|' + payment_id).digest('hex');
if (generated_signature === signature) {
res.json({ status: "success" });
} else {
res.status(400).json({ status: "failure" });
}
});
You can redirect users to a success or failure page based on the payment verification result. This can be done in the handler function of the Razorpay checkout options.
In this tutorial, we have covered the essential steps to integrate the Razorpay payment gateway into an ExpressJS application. By following these steps, you can enable secure payment processing on your e-commerce website. Remember to test your implementation thoroughly before going live.
If you found this tutorial helpful, please like and subscribe to our channel for more updates.
Paste a YouTube link and let Magica create the key takeaways.
Summarize another video