Razorpay Documentation
Razorpay Documentation
1
GANTT CHART
analyis
design
Coding+
testing
implementio
n
Documention
2
INDEX
Sr.No. Contents Page No. Sign
1. Introduction 8
2. Requirement Specification 9
3. Dataflow 10
4. System Implementation (Code) 12
5. Result (Input And Output) 20
6. Conclusion 25
7. Reference 26
3
Introduction
In today’s fast-paced digital world, online payments have become an integral part of
almost every web application. Whether it's an e-commerce platform, a subscription-
based service, or a donation portal, providing users with a smooth and secure way to
complete transactions is essential. As developers, integrating a payment gateway that
is both powerful and easy to use is a top priority. Razorpay, a leading Indian payment
gateway, offers a simple yet robust solution for accepting online payments. In this
essay, we explore the process of building a full-fledged Razorpay payment application
using ReactJS for the frontend and MongoDB with Node.js and Express for the
backend.
The project aims to create a seamless user experience for handling online payments,
4
while ensuring all sensitive information is handled securely. ReactJS is chosen as the
frontend framework due to its component-based architecture and ability to build
dynamic and responsive user interfaces. The user will be able to select a product or
service, initiate a payment, and interact with Razorpay’s secure
Background :
With the rapid growth of digital commerce, businesses today require robust online
payment solutions that are secure, efficient, and user-friendly. Traditional methods of
payment collection are being replaced by digital payment gateways that offer seamless
integration into websites and mobile applications. Razorpay is one such leading
payment gateway in India, widely used by businesses of
all sizes to facilitate digital transactions.
Razorpay provides a suite of tools for accepting payments via credit card, debit card,
net banking, UPI, and various other methods. The availability of its official APIs and
SDKs has made it a preferred choice among developers and organizations aiming to
build reliable payment systems.
This project aims to harness the capabilities of Razorpay by integrating it into a web
application developed using Python and Django, with HTML forming the base of the
frontend interface.
Django is a powerful high-level Python web framework that enables rapid
development and clean design. Combined with Razorpay, it forms a solid
foundation for developing secure and responsive payment systems.
This integration will demonstrate how a Django-based application can be equipped to
handle online payments while ensuring data integrity, security, and a positive user
experience. The project will serve as a practical implementation of payment gateway
integration and backend management, reflecting real-world use case
Objective:
The primary objective of this project is to develop a web-based payment system that
integrates Razorpay using Python’s Django framework and HTML for the frontend
structure. The system is intended to support smooth, one-time online payments
initiated by users through a web interface.
The application will provide the functionality to generate payment orders, redirect
users to Razorpay’s
hosted checkout page, handle callbacks, and verify the authenticity of the payment
using Razorpay’s signature verification process.
5
Scope of the Project :
6
✅ Test Cases for Razorpay Payment Integration
Functional Requirements
7
The functional requirements describe the essential tasks the system must perform to
meet the expectations of users and ensure smooth operation. At the core, the
application should offer an intuitive and interactive web page where users can initiate
a transaction. This interface should include fields for basic input such as the payer’s
name, email address, and the payment amount.
Once the user submits their information, the system should generate a unique payment
order. This order acts as a transaction identifier and includes details such as the total
amount to be paid, the currency (typically INR for Indian users), and metadata
necessary for the payment gateway to process the request. This order must be created
securely and stored for future reference or verification.
Following the order generation, the system must invoke the Razorpay Checkout — a
secure and embedded payment interface that supports a variety of payment methods
including credit and debit cards, UPI, net banking, and digital wallets. This interface
must be integrated in such a way that users do not leave the environment of the
original web application unless absolutely necessary. The system should ensure a
smooth transition between order creation and payment processing.
After the user completes the payment on the Razorpay interface, the payment gateway
sends a response indicating whether the transaction was successful or failed. The
system must be equipped to handle both scenarios. For a successful transaction, it
must verify the legitimacy of the response through Razorpay’s signature verification
system. This step is crucial to ensure that the transaction has not been tampered with
or spoofed.
Upon successful verification, the user should be redirected to a success page that
displays their transaction details and confirmation message. In case of a failure, the
system should notify the user accordingly, ideally with an explanation or the option to
retry. Regardless of the outcome, the system must log all transaction attempts with
relevant details such as payment ID, order ID, transaction status, user email, and a
timestamp. This logging is important for record-keeping, resolving disputes, or
conducting audits.
Performance Requirements:
8
Performance is a crucial aspect of any web-based payment system. Users expect fast
and reliable interactions, especially when handling sensitive financial data. In an
online payment application, performance requirements ensure that the system operates
smoothly, responds quickly, and maintains consistency even under load. This section
outlines the performance expectations of the payment gateway integration system and
discusses how it should behave in various conditions to provide an optimal user
experience.
Response time :
One of the primary performance goals is to minimize response time across all user
interactions. From the moment a user lands on the payment page to the final
confirmation message, each step must occur with minimal delay. Ideally, the system
should load all frontend components in under 2 seconds, even on slower network
connections.
After submitting a payment request, the Razorpay Checkout form should load within
1–2 seconds, allowing users to proceed without interruption. Similarly, once the
payment is completed, the server should process and verify the transaction details in
real-time, typically within 2–3 seconds, and immediately redirect the user to a
confirmation page.
Delays in these processes can lead to user frustration or payment abandonment, which
can directly impact business goals. Therefore, the system must be optimized to deliver
real-time feedback at every stage of the transaction lifecycle.
9
A critical performance metric for payment systems is uptime. Since users may attempt
to make payments at any time of the day, the application must ensure 99.9%
availability throughout the year. Unexpected downtime can result in loss of revenue
and customer trust. To achieve high availability, the system should be hosted on a
reliable infrastructure with appropriate failover mechanisms, automatic scaling, and
monitoring tools.
Additionally, error handling and fallback procedures should be in place. If the
payment gateway (Razorpay) experiences temporary downtime, the application should
display informative messages and allow users to retry or return to their order later
without data loss.
4. Scalability
While the initial version of the system may support a limited number of users or
transactions, it must be designed with future scalability in mind. As business needs
grow, the system should be able to handle increased traffic, larger transaction
1
0
1. Importance of Testing in Payment Systems
A payment gateway handles sensitive user data, financial transactions, and real-time
processing. Any failure in payment systems — whether due to bugs, security
loopholes, or poor user experience — can lead to loss of trust, revenue, and legal
complications. Therefore, comprehensive testing of the Razorpay integration ensures:
Transactions are processed correctly
Errors and exceptions are handled gracefully
The system is secure and reliable
The end-user experience is smooth and error-free
Testing Methodology Used
A structured Black Box Testing approach was followed, where the internal logic of the
code was not evaluated. Instead, focus was placed on the inputs and outputs of the
system, especially how the application interacts with the Razorpay API.
The testing process was divided into the following stages:
Unit Testing for individual functions (e.g., Razorpay order generation)
Integration Testing to verify interactions between the frontend, backend, and
Razorpay servers
System Testing to test the end-to-end flow
User Acceptance Testing (UAT) to validate real-world usability and business
needs
All testing was done using Razorpay's sandbox (test) environment, which simulates
real payment behavior without actual money transfers.
Functional Testing
Functional testing focused on verifying the correctness of the core features. Key test
scenarios included:
- Creating a Razorpay order with valid input (amount, currency, user details)
- Loading the Razorpay Checkout UI with correct data
- Completing a payment successfully
- Simulating failed payments or cancellations
- Verifying post-payment redirection and confirmation
- Validating Razorpay signature to prevent tampering
All functions were tested for proper input validation, status codes, and system
response.
Validation Techniques :
1
1
Validation ensures that the system behaves as expected under normal and edge-case
conditions. The Razorpay integration was validated through:
Live Testing on Sandbox Mode: Using Razorpay test cards and UPI IDs
Cross-Browser Testing: Ensuring payment flow works on Chrome, Firefox,
Edge, and mobile browsers
End-to-End Flow Validation: From form submission to payment confirmation
and database logging
User Feedback (UAT): Mock users were asked to complete test payments and
share feedback
Only after all major bugs were resolved and critical test cases passed, the Razorpay
integration was considered ready for production deployment.
1
2
Hardware Specifications
64-bit Microsoft Window
Processor :- X86 - 64 CPU Architecture, Intel core
Ram :- 4 GB or more
HardDrive :- 8 GB RAM or More
Software Specifications
Operating System :- Microsoft Windows 8/8.1/10/11
Required Architecture :- 32 bit or 64 bit
Software :- Visual Studio Code , Python (Django) , HTML
1
3
DATA flow
The data flow for Razorpay Payment Gateway is as
10
11
SYSTEM IMPLEMENTATION (CODING)
Home page :
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import logo from "../assets/logo.jpg"
const paymentData = {
name,
email,
amount: parseFloat(amount),
};
return (
<div className="min-h-screen bg-gray-100 flex items-center justify-center">
<div className="bg-white p-6 rounded-lg shadow-lg w-full max-w-md">
<div className="flex justify-center mb-6">
<img src={logo}/>
</div>
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label htmlFor="name" className="block text-sm font-medium text-
gray-700">Enter Name</label>
<input
type="text"
id="name"
value={name}
onChange={(e) => setName(e.target.value)}
className="mt-1 h-10 block w-full border-gray-300 pl-4 rounded-md
shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
required
/>
</div>
<div>
<label htmlFor="email" className="block text-sm font-medium text-
gray-700">Enter email</label>
<input
type="email"
id="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
className="mt-1 h-10 block w-full pl-4 border-gray-300 rounded-md
shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
required
/>
</div>
<div>
22
<label htmlFor="amount" className="block text-sm font-medium text-
gray-700">Enter Amount</label>
<input
type="number"
id="amount"
value={amount}
onChange={(e) => setAmount(e.target.value)}
className="mt-1 h-10 block w-full pl-4 border-gray-300 rounded-md
shadow-sm focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
required
/>
</div>
<button
type="submit"
className="w-full bg-green-600 text-white p-2 rounded-md hover:bg-
green-700 transition duration-300"
>
Submit
</button>
<button
onClick={handleBackToHome}
className="mt-4 px-4 py-2 bg-blue-600 text-white rounded hover:bg-
blue-700"
>
History
</button>
</form>
</div>
</div>
);
};
function PaymentPage() {
const [loading, setLoading] = useState(false);
const navigate = useNavigate();
const location = useLocation();
try {
setLoading(true);
const isScriptLoaded = await loadRazorpayScript();
if (!isScriptLoaded) {
24
toast.error('Failed to load Razorpay SDK');
setLoading(false);
return;
}
const options = {
key: 'rzp_test_lGcdgDS9fsw9qp',
amount: razorpayAmount,
currency: 'INR',
order_id: id,
name: 'Razorpay Integration',
description: `Payment of ₹${amount} for ${name}`,
method: {
upi: true,
card: true,
netbanking: true,
wallet: true,
},
handler: async (response) => {
const payload = {
payment_id: response.razorpay_payment_id,
amount: amount,
name: name,
email: email,
};
console.log("Sending to /save-payment:", payload); // Log payload
try {
await axios.post('http://localhost:5000/razorpay/save-payment', payload);
toast.success('Payment successful: ' + response.razorpay_payment_id);
25
navigate('/history');
} catch (error) {
console.error('Error processing payment:', error.response?.data ||
error.message);
toast.error(error.response?.data?.message || 'Failed to process payment');
}
},
prefill: {
name: name || 'Customer Name',
email: email || 'customer@example.com',
amount: '99999', // Optional, not saved in schema
},
theme: {
color: '#2563EB',
},
};
return (
<div className="container mx-auto p-6 max-w-md mt-10 pt-20">
<Toaster />
<h2 className="text-3xl font-bold text-gray-800 mb-6 text-center flex items-
center justify-center gap-2">
<CreditCard className="w-8 h-8 text-blue-600" />
Payment
</h2>
<div className="bg-white p-6 rounded-lg shadow-md space-y-6">
<div className="space-y-2">
<p className="text-gray-700"><strong>Name:</strong> {name}</p>
<p className="text-gray-700"><strong>Email:</strong> {email}</p>
<p className="text-gray-700"><strong>Amount:</strong> ₹
{amount.toFixed(2)}</p>
</div>
{loading ? (
<p className="text-blue-600 text-center">Initiating payment...</p>
):(
<button
onClick={handlePayment}
disabled={loading}
className="w-full bg-blue-600 text-white p-3 rounded-lg hover:bg-blue-
700 transition duration-300 flex items-center justify-center gap-2 disabled:bg-
blue-400 disabled:cursor-not-allowed"
>
<CreditCard className="w-5 h-5" />
Pay Now
</button>
)}
</div>
</div>
);
}
const options = {
amount: amount * 100, // Convert to paise (Razorpay
expects amount in smallest unit)
currency: "INR",
receipt: `order_${Date.now()}`, // Unique receipt
using timestamp
};
28
const order = await razorpay.orders.create(options);
res.json({
id: order.id,
amount: order.amount,
});
} catch (error) {
console.error("Error creating order:", error);
res.status(500).json({ error: "Some error occurred
while creating the order" });
}
});
app.post("/razorpay/save-payment", async (req, res) => {
try {
const { payment_id, amount, name, email } =
req.body;
console.log("Received in /save-payment:",
req.body); // Log incoming data
29
// Ensure amount is a number
const paymentAmount = Number(amount);
if (isNaN(paymentAmount)) {
console.log("Validation failed: Amount is not a
number");
return res.status(400).json({ error: "Amount must be
a number" });
}
res.json({
message: "Payment saved successfully",
payment: {
21
0
id: savedPayment._id,
payment_id: savedPayment.payment_id,
amount: savedPayment.amount,
name: savedPayment.name,
email: savedPayment.email,
},
});
} catch (error) {
console.error("Error saving payment:", {
message: error.message,
stack: error.stack,
code: error.code, // For MongoDB-specific errors
});
res.status(500).json({
error: "Failed to save payment details",
details: error.message,
});
}
});
21
2
21
3
3) Payment Page
21
4
4) Success Page
21
5
Future scope :
The implementation of a payment gateway system using Razorpay lays a strong
foundation for modern, secure, and efficient digital transactions. However, as
technology continues to evolve and user expectations increase, there is significant
potential to expand the system’s functionality, usability, and scalability. This section
explores the future scope of the Razorpay integration project, focusing on features and
improvements that can be introduced to meet emerging business needs and industry
trends.
1. Multi-Currency Payment Support
At present, the system may be limited to transactions in a single currency, most
commonly the Indian Rupee (INR). In the future, as the application scales to
international markets or caters to global clients, there will be a need to support
multiple currencies. Razorpay provides the ability to accept international payments,
which can be integrated into the system to allow users to pay in their local currencies.
This would make the platform more versatile and inclusive for users outside India.
2. Subscription and Recurring Payment Integration
Another significant enhancement involves the integration of subscription models and
recurring billing. Businesses that operate on a monthly or yearly payment basis, such
as SaaS platforms, e-learning websites, or digital services, can benefit greatly from
automated recurring transactions. Razorpay’s subscription module allows developers
to set up and manage recurring payment plans effortlessly. Future versions of the
system could allow users to subscribe to plans, view billing cycles, and manage their
subscriptions directly from the interface.
3. Enhanced Dashboard and Analytics
Currently, the backend may only support basic transaction logging and status tracking.
In the future, this can be expanded into a full-featured analytics dashboard. Such a
dashboard can include:
Payment success/failure trends over time
Revenue tracking (daily, weekly, monthly)
User-specific payment history
Filtered search by date, email, or order ID This data can be invaluable for
businesses to make data-driven decisions and to identify bottlenecks or
fraudulent activities quickly.
4. Mobile Application Integration
With mobile usage surpassing desktop usage globally, the future scope includes
extending the Razorpay payment functionality to mobile applications. Integrating
Razorpay’s SDK into Android and iOS apps would provide users with a seamless
payment experience on their mobile devices. This would involve syncing mobile and
web payment records, improving user engagement, and ensuring consistency across
platforms.
21
6
5. Wallet and BNPL (Buy Now, Pay Later) Options
As digital wallets and deferred payment systems gain popularity, integrating support
for services like Paytm Wallet, Amazon Pay, or Razorpay's native BNPL features can
improve user convenience. By offering flexible payment choices, the system becomes
more user-friendly, and businesses may see improved conversion rates at checkout.
6. Refund and Dispute Management System
Currently, handling refunds or transaction disputes may be a manual process. In future
versions, automated refund initiation, tracking, and status updates can be implemented.
Integration with Razorpay’s refund API would allow users to request a refund, view
the refund status, and receive real-time notifications. Adding features to handle
chargebacks or disputes would also enhance the system's robustness and user trust.
7. Integration with E-Commerce Platform
Conclusion :
We are a developer-oriented and easy to integrate gateway. Our API is
entirely REST based, and over checkout experience is Seamless, with no
redirect away from your website. we offer 24x7 support.
Razorpay is only payment solution in India which allow businesses to
accept, process and disburse payments with its product suite.
Manage Your mrkrtplace, automate NEFT/RTGS/IMPS bank transfers,
collect recurring payments, share invoices with customers – all from a
single platform.
Online Activation within 2 working days.
21
7
REFERENCE
www.google.com
www.youtube.com
www.razorpay.com
www.geeksforgeeks.com
www.w3schools.com
www.javatpoint.com
21
8