VOOZH about

URL: https://dev.to/madhubankhatri/razorpay-integration-with-django-step-by-step-guide-1cmn

⇱ Razorpay Integration with Django: Step-by-Step Guide 💳 - DEV Community


If you're building a Django-based application and want to accept payments online, Razorpay is one of the easiest and most developer-friendly gateways to integrate. In this post, I’ll walk you through the Razorpay integration process with Django, step-by-step — from setting up the environment to handling the payment success callback.

🛠️ Prerequisites
Before we begin, make sure you have:

  • Python and Django installed.
  • A Razorpay account (Sign up at https://razorpay.com)
  • Razorpay API Keys (from the Razorpay dashboard)
  • Basic understanding of Django views and templates.

🔧 Step 1: Install Razorpay Python SDK

pip install razorpay

📁 Step 2: Setup Razorpay Keys

In your Django project settings (settings.py), add your RAZORPAY_KEY_ID and RAZORPAY_KEY_SECRET:

RAZORPAY_KEY_ID = 'your_key_id'
RAZORPAY_KEY_SECRET = 'your_key_secret'

You can also use environment variables for security.

🧠 Step 3: Create the Payment View

Views.py

from django.shortcuts import render
from django.http import HttpResponse
import razorpay
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponseBadRequest

# authorize razorpay client with API Keys.
razorpay_client = razorpay.Client(auth=(settings.RAZOR_KEY_ID, settings.RAZOR_KEY_SECRET))

# Create your views here.
def home(request):
 currency = 'INR'
 if request.method == "POST":
 amount_rupees = int(request.POST.get("amount", 1))
 amount = amount_rupees * 100 # Convert to paise
 request.session['latest_payment_amount'] = amount

 razorpay_order = razorpay_client.order.create(dict(amount=amount,
 currency=currency,
 payment_capture='0'))

 razorpay_order_id = razorpay_order['id']
 callback_url = 'paymenthandler/'

 context = {}
 context['razorpay_order_id'] = razorpay_order_id
 context['razorpay_merchant_key'] = settings.RAZOR_KEY_ID
 context['razorpay_amount'] = amount
 context['currency'] = currency
 context['callback_url'] = callback_url
 return render(request, 'home.html', context=context)
 return render(request, 'home.html')


@csrf_exempt
def paymenthandler(request):
 # only accept POST request.
 if request.method == "POST":
 try:
 payment_id = request.POST.get('razorpay_payment_id', '')
 razorpay_order_id = request.POST.get('razorpay_order_id', '')
 signature = request.POST.get('razorpay_signature', '')

 params_dict = {
 'razorpay_order_id': razorpay_order_id,
 'razorpay_payment_id': payment_id,
 'razorpay_signature': signature
 }

 result = razorpay_client.utility.verify_payment_signature(params_dict)
 print(result)
 if result is not None:
 amount = request.session['latest_payment_amount']
 try:
 razorpay_client.payment.capture(payment_id, amount)
 return render(request, 'paymentsuccess.html', params_dict)
 except:

 return render(request, 'paymentfail.html')
 else:
 return render(request, 'paymentfail.html')
 except:
 return HttpResponseBadRequest()
 else:
 return HttpResponseBadRequest()

urls.py

from django.urls import path
from . import views

urlpatterns = [
 path('',views.home, name='home'),
 path('paymenthandler/', views.paymenthandler, name='paymenthandler'),
]

home.html

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>Home</title>
</head>
<body>
 <h1>Razorpay Integration</h1>

 <form method="post" action="{% url 'home' %}">
 {% csrf_token %}
 <label for="amount">Enter amount (INR): </label>
 <input type="number" id="amount" name="amount" required>
 <button id="pay-btn" type="submit">Proceed to Pay</button>
 </form>


 {% if razorpay_order_id %} 
 <!-- Razorpay's Javascript code. -->
 <script src="https://checkout.razorpay.com/v1/checkout.js"></script>

 <script>
 var options = {
 key: "{{ razorpay_merchant_key }}", 
 amount: "{{ razorpay_amount }}", 
 currency: "{{ currency }}",

 // Your/store name.
 name: "Dj Razorpay", 

 // Pass the `id` obtained in the response of Step 1
 order_id: "{{ razorpay_order_id }}", 
 callback_url: "{{ callback_url }}",
 };

 // initialise razorpay with the options.
 var rzp1 = new Razorpay(options);

 rzp1.open();
 </script>
 {% endif %}
</body>
</html>

paymentsuccess.html

<!DOCTYPE html>
<html>
<head>
 <title>Payment Successful</title>
 <style>
 body {
 font-family: Arial;
 text-align: center;
 padding: 50px;
 background-color: #f4f4f4;
 }
 .box {
 background: white;
 padding: 30px;
 border-radius: 10px;
 display: inline-block;
 box-shadow: 0px 0px 10px #ccc;
 }
 h2 {
 color: green;
 }
 </style>
</head>
<body>
 <div class="box">
 <h2>🎉 Payment Successful!</h2>
 <p>Thank you for your payment.</p>
 <p><strong>Payment ID:</strong> {{ razorpay_payment_id }}</p>
 <a href="/">Go back to Home</a>
 </div>
</body>
</html>

Razorpay makes payment integration smooth and developer-friendly. With just a few steps, you can start accepting payments in your Django application.

Source code is available on Github : Movie Booking System

Thanks for reading.