In India, Razorpay is the best and easiest payment solution for businesses to accept or process payments on their websites.
It can be easily integrated into any website in just a few minutes so, from a developer's point of view it is a seamless process for integration more than 1,50,000 + businesses use Razorpay for their websites.
In this article, we explain how to find the Razorpay Api key and Razorpay payment gateway integration in Nodejs.
Account Creation
To integrate Razorpay into your website first, you need to create an account on Razorpay you can follow the below steps:
Step 1: Navigate to https://razorpay.com/ and click on the signup button
Step 2: Now it will redirect to https://easy.razorpay.com/onboarding/l1/signup?field=MobileNumber&cta_btn=Navbar_Header
Now fill the proper details and after submission, it will land on the Dashboard
Step 3: To find your API key click on the account and setting link present on the sidebar
Step 4: Now click on the API Keys link
Step 5: Here you can find your Test Mode Api Keys
Razorpay payment gateway integration in Nodejs:
To integrate Razorpay payment gateway in nodejs can follow the below steps:
Step 1: Setup NodeJs Project(Create a folder) and install the following libraries
npm init -y // for nodejs setup
npm i express // Nodejs framework
npm i nodemon // automatically restarting the node application
npm i dotenv // for environment setup
npm i ejs // nodejs template engine
npm i path // for path and folder setup
npm i razorpay // for payment gateway integration
Step 2: Create a Server.js file in the root directory and create the following folders, we will follow the MVC structure:
server.js Controllers // For Communication with Models Models //For Database Schema Views // All pages PageRoutes // Handling pages ApiRoutes // Handling APIs public // For images , js ,css .env //For environment
Step 3: Setup the environment for Razorpay, create a .env file in the root directory and paste the following code
PORT = 4000
RAZORPAY_KEY = YOUR RAZORPAY KEY RAZORPAY_SECRECT = YOUR RAZORPAY SECRECT
Step 4: Open server.js and paste the following code
const express = require('express');
const app = express();
const dotenv = require('dotenv');
dotenv.config();
const APP_PORT = process.env.PORT || 4000;
const path = require('path');
const { readdirSync } = require('fs');
app.use(express.json());
app.set('Views', path.join(__dirname, 'Views'));
app.set('view engine', 'ejs');
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, '/public')));
app.listen(APP_PORT, () => {
console.log(`Server Started At PORT ${APP_PORT}`);
});
Now you can run your server by npm start
npm start
Step 5: Create the first routes for accessing the pages so navigate to PageRoutes ,create a file OrderRoutes.js and paste the following code
const express = require('express');
const router = express.Router();
module.exports = router;
Step 6: Now create a new file in Views folder named as Order.ejs and paste the following code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Razorpay Integration</h1>
<button id="payBtn">Pay Now</button>
<script>
const Baseurl = '<%= Baseurl %>';
</script>
<script
src="https://code.jquery.com/jquery-3.7.1.slim.min.js"
integrity="sha256-kmHvs0B+OpCW5GVHUNjv9rOmY0IvSIRcf7zGUDTDQM8="
crossorigin="anonymous"></script>
<script src="/assets/js/Order.js"></script>
</body>
</html>
Step 7: Now to access this page you need to add this route to your server.js so open server.js and add this line
// PAGE ROUTES readdirSync('./PageRoutes').map((route) => app.use('/', require(`./PageRoutes/${route}`)));
Note: It adds dynamically all files from PageRoutes
Step 8: Create Controller for Razorpay Order but before that we should understand the basic flow
When the user clicks on the Pay Now button then there will be a network request for creating a Razorpay order that request will be POST type in which the amount will be there after handling the request developer will get orderID in response and pass that order id in Razorpay another object and after that Razorpay interface will be initiated and amount will be shown on that interface and user can now pay with credit card or UPI.
Now create a new File named OrderController.js in the Controllers folder and paste the following code and paste the following code
const razorpay = require('razorpay');
const credentials = new razorpay({
key_id: process.env.RAZORPAY_KEY,
key_secret: process.env.RAZORPAY_SECRECT,
});
let OrderID = '';
const OrderController = {
async createRazorPayOrder(req,res,next){
try{
let options = {
amount: req.body.amount * 100,
currency: "INR",
}
credentials.orders.create(options, function (err, order) {
console.log(err)
OrderID = order.id;
return res.json({ status: 200, order });
});
}
catch(err){
console.log(err)
}
}
}
module.exports = OrderController;
Now the Controller is created now create a separate route for this, so create a new file in the ApiRoutes Folder named OrderRoutes.js and paste the following code
const express = require('express');
const router = express.Router();
const OrderController = require('../Controllers/OrderController');
router.post('/create/razorpay/order', OrderController.createRazorPayOrder);
module.exports = router;
Now after this include this in server.js or you can paste the following code
// API ROUTES readdirSync('./ApiRoutes').map((route) => app.use('/api', require(`./ApiRoutes/${route}`)));
Step 9: Now create an assets folder and in the assets, folder create a js folder and create a new file Order.js and paste the following code
$(document).ready(function(){
$('#payBtn').on('click',function(){
OrderController.createRazorPayOrder();
});
});
const OrderController = {
async createRazorPayOrder(){
try{
const API_URL = Baseurl + `/api/create/razorpay/order`;
let data = {
amount: 500
}
const options = {
headers: {
'content-type': 'application/json',
},
method: 'POST',
body: JSON.stringify(data)
}
let response = await fetch(API_URL, options);
response = await response.json();
OrderController.openRazorPayInterface(response)
}
catch(err){
console.log(err)
}
}
}
Now let's hit the URL by clicking the button
Now we getting OrderID cool, now the next step copy the following CDN in Order.ejs
<script src="https://checkout.razorpay.com/v1/checkout.js"></script>
Now go back to Order.js and create a new function for open Razorpay interface or paste the following code
$(document).ready(function(){
$('#payBtn').on('click',function(){
OrderController.createRazorPayOrder();
});
});
const OrderController = {
async createRazorPayOrder(){
try{
const API_URL = Baseurl + `/api/create/razorpay/order`;
let data = {
amount: 500
}
const options = {
headers: {
'content-type': 'application/json',
},
method: 'POST',
body: JSON.stringify(data)
}
let response = await fetch(API_URL, options);
response = await response.json();
OrderController.openRazorPayInterface(response)
}
catch(err){
console.log(err)
}
},
async openRazorPayInterface(response){
try{
var options = {
"key": "YOUR_KEY", // Enter the Key ID generated from the Dashboard
"amount": 500 * 100, // Amount is in currency subunits. Default currency is INR. Hence, 50000 refers to 50000 paise
"currency": "INR",
"name": "New Bussiness", //your business name
"description": "New Transaction",
"image": "http://localhost:4000/assets/images/app-logo.svg",
"order_id": response.order.orderID, //This is a sample Order ID. Pass the `id` obtained in the response of Step 1
"prefill": { //We recommend using the prefill parameter to auto-fill customer's contact information especially their phone number
"name": `Prince`, //your customer's name
"email": `officialprince52@gmail.com`,
"contact": `8299727256` //Provide the customer's phone number for better conversion rates
},
"handler": function (response) {
if (response) {
console.log(response);
}
},
"notes": {
"address": "Razorpay Corporate Office"
},
"theme": {
"color": "#dc3545"
}
}; var rzp1 = new Razorpay(options);
rzp1.open();
}
catch(err){
console.log(err)
}
}
}
Step 10: Now let's click on the Paynow button
Now Click on the Pay Now button and see the response in the console
Conclusion
From the above steps we learn how to find Razorpay API keys and after finding the key we can integrate the Razorpay Payment Gateway into our website in 10 Simple steps.
Anyway, this is all about this article. Kindly tell us about any missing points or mistakes for future improvements.
Helpful Links:
https://razorpay.com/docs/#home-payments
https://razorpay.com/docs/api/orders/
https://razorpay.com/docs/api/orders/create/
Read More
https://scribblersden.com/article/how-does-quick-commerce-work
Follow us on
Table of Contents
Leave a reply