Integration Guides · 7 MIN
How to integrate Razorpay in Django (2026 guide, no SDK needed)
Step-by-step Razorpay integration for Django. Create orders, open Checkout, verify the HMAC signature and handle the order.paid webhook, with tested code.
To integrate Razorpay in Django, create an order on your server with the Orders API, open Razorpay Checkout in the browser with that order ID, then verify the HMAC-SHA256 signature on your server before you mark anything paid. A webhook for order.paid is the backstop for customers who close the tab. This guide builds all four parts in plain Django and the Python standard library.
- The amount is always set on your server and sent to Razorpay in paise, so Rs 499 is
49900. - A payment counts only after your server checks
razorpay_signatureagainst your own copy of the order ID. - Webhooks are signed with the webhook secret over the raw request body, not with your API key secret.
- Razorpay can deliver the same webhook more than once, so store
X-Razorpay-Event-Idand skip repeats. - Every snippet here was run against Django 6.0 with a local mock of the Orders API before publishing.
- Nactore is a technology and growth company that builds, ships, ranks and grows products, and this is the checkout pattern we run in production.
How does Razorpay Checkout work with Django?
Razorpay Checkout with Django is a four-step handshake. Your server creates an order, the browser opens Checkout for that order, Razorpay returns a signed result, and your server verifies the signature. A webhook then confirms the same payment server to server, so you never depend on the browser alone.
| Step | Where it runs | What it proves |
|---|---|---|
| Create order | Django view to Razorpay API | The price came from you |
| Open Checkout | Browser, checkout.js | The customer paid for that order |
| Verify signature | Django view | The result was not forged |
order.paid webhook | Razorpay to Django | Payment is captured, even if the tab closed |
Take your test mode Key ID and Key Secret from the Dashboard, create a webhook secret, and keep all three in environment variables. Test keys locally, live keys only on the production host.
export RAZORPAY_KEY_ID=rzp_test_xxxxxxxx
export RAZORPAY_KEY_SECRET=your_test_key_secret
export RAZORPAY_WEBHOOK_SECRET=your_webhook_secretStep 1: Create the order on the server
Two small models hold your orders and the webhook events you have already processed.
# payments/models.py
from django.db import models
class Order(models.Model):
amount_paise = models.PositiveIntegerField()
razorpay_order_id = models.CharField(max_length=64, unique=True, null=True)
razorpay_payment_id = models.CharField(max_length=64, blank=True)
status = models.CharField(max_length=16, default="created")
class WebhookEvent(models.Model):
event_id = models.CharField(max_length=64, unique=True)
received_at = models.DateTimeField(auto_now_add=True)The client is one authenticated POST to the Orders API and two HMAC checks.
# payments/razorpay_client.py
import base64, hashlib, hmac, json, os, urllib.request
KEY_ID = os.environ["RAZORPAY_KEY_ID"]
KEY_SECRET = os.environ["RAZORPAY_KEY_SECRET"]
WEBHOOK_SECRET = os.environ["RAZORPAY_WEBHOOK_SECRET"]
API = os.environ.get("RAZORPAY_API_BASE", "https://api.razorpay.com")
def create_order(amount_paise, receipt):
body = json.dumps({"amount": amount_paise, "currency": "INR", "receipt": receipt}).encode()
auth = base64.b64encode(f"{KEY_ID}:{KEY_SECRET}".encode()).decode()
req = urllib.request.Request(f"{API}/v1/orders", data=body, method="POST", headers={
"Authorization": f"Basic {auth}",
"Content-Type": "application/json",
"User-Agent": "yourapp-payments/1.0",
})
with urllib.request.urlopen(req, timeout=15) as resp:
return json.load(resp)
def _sign(secret, message: bytes):
return hmac.new(secret.encode(), message, hashlib.sha256).hexdigest()
def payment_signature_ok(order_id, payment_id, signature):
expected = _sign(KEY_SECRET, f"{order_id}|{payment_id}".encode())
return hmac.compare_digest(expected, signature or "")
def webhook_signature_ok(raw_body: bytes, signature):
return hmac.compare_digest(_sign(WEBHOOK_SECRET, raw_body), signature or "")hmac.compare_digest compares in constant time, which the Python docs recommend for exactly this check.
Step 2: Open Checkout in the browser
The view creates your order first, then the Razorpay order, and returns only what the browser needs.
# payments/views.py
import json
from django.http import HttpResponse, HttpResponseBadRequest, JsonResponse
from django.shortcuts import get_object_or_404
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from . import razorpay_client as rzp
from .models import Order, WebhookEvent
PRICE_PAISE = 49900 # Rs 499, set on the server, never read from the browser
@require_POST
def create_order(request):
order = Order.objects.create(amount_paise=PRICE_PAISE)
rz = rzp.create_order(order.amount_paise, receipt=f"order-{order.pk}")
order.razorpay_order_id = rz["id"]
order.save(update_fields=["razorpay_order_id"])
return JsonResponse({"key": rzp.KEY_ID, "order_id": rz["id"],
"amount": rz["amount"], "currency": rz["currency"]})On the page, load Razorpay Checkout and send Django's CSRF token with each call.
<button id="pay">Pay Rs 499</button>
<script src="https://checkout.razorpay.com/v1/checkout.js"></script>
<script>
const csrf = document.cookie.match(/csrftoken=([^;]+)/)?.[1];
const post = (url, body) => fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json", "X-CSRFToken": csrf },
body: JSON.stringify(body || {}),
}).then((r) => r.json());
document.getElementById("pay").onclick = async () => {
const o = await post("/pay/order/");
new Razorpay({
key: o.key,
order_id: o.order_id,
amount: o.amount,
currency: o.currency,
name: "Your company",
handler: async (resp) => {
const v = await post("/pay/verify/", resp);
window.location.href = v.ok ? "/thanks/" : "/payment-failed/";
},
}).open();
};
</script>Step 3: Verify the payment signature
Razorpay signs order_id|payment_id with your Key Secret. Look the order up in your own database and use that ID, as Razorpay's docs advise, so a customer cannot swap in another order.
@require_POST
def verify_payment(request):
data = json.loads(request.body)
order = get_object_or_404(Order, razorpay_order_id=data.get("razorpay_order_id"))
ok = rzp.payment_signature_ok(order.razorpay_order_id,
data.get("razorpay_payment_id", ""),
data.get("razorpay_signature"))
if ok:
order.razorpay_payment_id = data["razorpay_payment_id"]
order.status = "paid"
order.save(update_fields=["razorpay_payment_id", "status"])
return JsonResponse({"ok": ok}, status=200 if ok else 400)Step 4: Handle the order.paid webhook
The webhook covers the customer who pays and closes the tab before your handler runs. Razorpay's webhook validation guide says to verify the raw body and to use x-razorpay-event-id to spot duplicates.
@csrf_exempt
@require_POST
def razorpay_webhook(request):
raw = request.body # the exact bytes Razorpay signed, do not parse first
if not rzp.webhook_signature_ok(raw, request.headers.get("X-Razorpay-Signature")):
return HttpResponseBadRequest("invalid signature")
_, created = WebhookEvent.objects.get_or_create(
event_id=request.headers.get("X-Razorpay-Event-Id", ""))
if not created:
return HttpResponse(status=200) # duplicate delivery, already handled
event = json.loads(raw)
if event.get("event") == "order.paid":
rz_order = event["payload"]["order"]["entity"]
rz_payment = event["payload"]["payment"]["entity"]
Order.objects.filter(razorpay_order_id=rz_order["id"]).update(
status="paid", razorpay_payment_id=rz_payment["id"])
return HttpResponse(status=200)# payments/urls.py
from django.urls import path
from . import views
urlpatterns = [
path("pay/order/", views.create_order),
path("pay/verify/", views.verify_payment),
path("webhooks/razorpay/", views.razorpay_webhook),
]Only the webhook is CSRF exempt. Your own order and verify views keep Django's CSRF protection.
What went wrong for us, and how to test it
We run pay-first checkouts on a Django backend this way, shared across several paid products. These are the failures we hit or tested for.
| Problem | Cause | Fix |
|---|---|---|
| Checkout dead in production | An older SDK release raised No module named 'pkg_resources', since Python 3.12 no longer installs setuptools in a venv | Plain HTTP and HMAC as above |
| Webhook always 400 | Body parsed and re-serialized before the check | Verify request.body bytes |
| Webhook always 400 | Signed with the API Key Secret | Use the webhook secret |
| Order paid twice in your logs | Same event delivered again | Unique event_id row |
| Wrong amount charged | Rupees sent instead of paise | Multiply by 100 on the server |
In a fresh Python 3.12 venv on 17 November 2026, the current SDK (2.0.1) imported cleanly, so the import error is fixed upstream. We kept the standard library version because it is less code than the dependency.
To test without money, use test keys, the UPI ID success@razorpay or failure@razorpay, or the test Visa card 4100 2800 0000 1007 from the integration guide. Localhost cannot receive webhooks, so expose it with a tunnel while testing.
Test your webhook against a body with odd spacing. If your code re-serializes the JSON before checking the signature, that test fails at once, which is exactly what you want to learn before launch.
Frequently asked questions
Do I need the Razorpay Python SDK for Django?
No. Order creation is one authenticated POST and both signature checks are HMAC-SHA256, which the standard library covers. The SDK is fine if you prefer it. The code here simply removes a dependency.
Is the Checkout handler enough without a webhook?
Not on its own. The handler runs in the browser, so a closed tab or dropped connection means your server never hears about a real payment. The order.paid webhook closes that gap.
Why does Razorpay signature verification fail?
The usual causes are signing a parsed body instead of the raw bytes, using the Key Secret for webhooks, or using an order ID from the browser instead of your database.
Which amount format does Razorpay expect?
The smallest currency unit. For INR that is paise, so Rs 499 is sent as 49900.
When to get help
If checkout is costing you sales or your payment records do not match Razorpay's, tell us what you are seeing. Read what breaks when you ship a product with payments for the wider checklist, or see how we work. Nactore is one partner that builds, ships, ranks and grows, measured on your growth.
Want to apply this to your business?
Book a free 30-minute call. We will tell you what we would do first.