πŸš€ Razorpay Integration in Django with Complete Payment Lifecycle

HomePortfolio
πŸš€ Razorpay Integration in Django with Complete Payment Lifecycle
A Complete Guide to Integrating Razorpay in Django with Order Creation, Payment Handling, and Status Management

Integrating a payment gateway like Razorpay in your Django project opens up seamless online transactions. In this blog post, we’ll walk through Razorpay’s integration, how to capture payments, and handle payment statuses like success, pending, or failed β€” covering the full Razorpay Payment Lifecycle.

πŸ”§ Step 1: Install Razorpay Python SDK

First, install the Razorpay client SDK in your Django project using pip.

bash
pip install razorpay

πŸš€ Razorpay Integration in Django with Complete Payment Lifecycle
βš™οΈ Step 2: Add Razorpay Credentials in settings.py

Login to your Razorpay Dashboard and get your Test Key ID and Key Secret. Add them in your settings.py.

python
# settings.py
RAZORPAY_KEY_ID = "rzp_test_YourKeyId"
RAZORPAY_KEY_SECRET = "YourKeySecret"
TIME_ZONE = "Asia/Kolkata"

πŸš€ Razorpay Integration in Django with Complete Payment Lifecycle
🧱 Step 3: Create the Payment Model

This model stores payment data like order_id, payment_id, status, and amount.

python
# models.py
from django.db import models

class Payment(models.Model):
    order_id = models.CharField(max_length=100, unique=True)
    payment_id = models.CharField(max_length=100, blank=True, null=True)
    amount = models.DecimalField(max_digits=10, decimal_places=2)
    status = models.CharField(max_length=50, default="Pending")
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"Order {self.order_id} - {self.status}"

🌐 Step 4: Create Views to Handle Order & Payment

This Django view creates a Razorpay order and returns order details to the frontend.

python
# views.py
from django.shortcuts import render
import razorpay
from django.conf import settings
from django.http import JsonResponse
from .models import Payment

razorpay_client = razorpay.Client(auth=(settings.RAZORPAY_KEY_ID, settings.RAZORPAY_KEY_SECRET))

def home(request):
    return render(request, "home.html", {"RAZORPAY_KEY_ID": settings.RAZORPAY_KEY_ID})

def create_order(request):
    if request.method == "POST":
        amount = int(request.POST["amount"]) * 100
        data = {
            "amount": amount,
            "currency": "INR",
            "payment_capture": "1"
        }
        order = razorpay_client.order.create(data)
        Payment.objects.create(order_id=order["id"], amount=amount / 100, status="Created")
        return JsonResponse(order)
    return JsonResponse({"error": "Invalid request"}, status=400)

def payment_success(request):
    return render(request, "success.html")

πŸ’³ Step 5: Payment Page & JavaScript Integration

On the frontend, use Razorpay Checkout to initiate the payment. Razorpay requires the key, order_id, and a handler for payment success.

html
<!-- home.html -->
<input type="number" id="amount" placeholder="Enter Amount">
<button id="payBtn">Pay Now</button>

<script src="https://checkout.razorpay.com/v1/checkout.js"></script>
<script>
document.getElementById("payBtn").onclick = function () {
    let amount = document.getElementById("amount").value;

    fetch("/create-order/", {
        method: "POST",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            "X-CSRFToken": "{{ csrf_token }}"
        },
        body: `amount=${amount}`
    })
    .then(res => res.json())
    .then(order => {
        var options = {
            key: "{{ RAZORPAY_KEY_ID }}",
            amount: order.amount,
            currency: "INR",
            order_id: order.id,
            name: "Django Razorpay",
            handler: function (response) {
                window.location.href = "/payment-success/";
            }
        };
        var rzp = new Razorpay(options);
        rzp.open();
    });
};
</script>

Resources

πŸ“˜ Razorpay Docs :https://razorpay.com/docs/

πŸ’‘ Django Payment Gateways :https://djangopackages.org/grids/g/payment-processing/

πŸ” Secure Your Razorpay Integration :https://razorpay.com/docs/security/


βœ… Conclusion: Track Payment Lifecycle Easily

Razorpay offers a reliable and developer-friendly way to integrate payments in Django. With clear steps, order creation, secure checkout, and server-side verification, you're ready to manage real-time payments confidently. You can extend this flow to verify signatures and update statuses like Success, Failed, or Pending.


Likes β€’ 8 Views β€’ Apr 5, 2025