Integrating Razorpay with Django: A Step-by-Step Guide
Tags: django, razorpay, payment, backend
Published: 2023-07-17 05:57:02

Razorpay is a popular payment gateway solution that enables seamless online transactions. If you're developing a Django project and looking to integrate Razorpay as the payment gateway, this step-by-step guide will walk you through the process. By following these instructions, you'll be able to seamlessly incorporate Razorpay into your Django web application and start accepting payments in no time.

**Prerequisites:**

Before you begin, make sure you have a Razorpay account. If you haven't signed up yet, head over to https://razorpay.com/ and create an account. Once you have your account, you're ready to proceed with the integration.


**Step 1: Install the Razorpay Package**

Start by installing the Razorpay Python package in your Django project. Open your terminal or command prompt and run the following command:


```
pip install razorpay
```



**Step 2: Set Up the Integration Code**

In your Django project, create a new directory called 'razorpay_integration' (or any other name of your choice) inside your app directory. This directory will house the integration code. Within the 'razorpay_integration' directory, create a new file called 'razorpay_integration.py'.


**Step 3: Initialize the Razorpay Client**

In the 'razorpay_integration.py' file, import the necessary modules:


```
import razorpay
from django.conf import settings
```


Next, initialize the Razorpay client with your API credentials:


```
client = razorpay.Client(auth=(settings.RAZORPAY_API_KEY, settings.RAZORPAY_API_SECRET))
```


**Step 4: Create a Payment Function**

Define a function to initiate a payment. This function will handle the creation of a Razorpay order and return the order ID. Feel free to customize this function according to your project's requirements. Here's an example:


```
def initiate_payment(amount, currency='INR'):
   data = {
       'amount': amount * 100,  # Razorpay expects amount in paise (e.g., 100 INR = 10000 paise)
       'currency': currency,
       'payment_capture': '1'  # Auto capture the payment after successful authorization
   }
   response = client.order.create(data=data)
   return response['id']
```

**Step 5: Create a Payment View**

Build a Django view that calls the 'initiate_payment' function and renders a payment page with the order ID. Customize the view according to your project's needs. Here's an example:


```
from django.shortcuts import render

def payment_view(request):
   amount = 100  # Set the amount dynamically or based on your requirements
   order_id = initiate_payment(amount)
   context = {
       'order_id': order_id,
       'amount': amount
   }
   return render(request, 'payment.html', context)

```


**Step 6: Design the Payment Page**

Create a template file called 'payment.html' to display the payment page. Utilize Razorpay's JavaScript code to handle the payment form submission. Here's an example:


```
<script src="https://checkout.razorpay.com/v1/checkout.js"></script>
<form action="{% url 'payment_success' %}" method="POST">
   <input type="hidden" name="order_id" value="{{ order_id }}">
   <script>
       var options = {
           "key": "{{ settings.RAZORPAY_API_KEY }}",
           "amount": "{{ amount }}",
           "currency": "INR",
           "name": "Your Company Name",
           "description": "Payment Description",
           "order_id": "{{ order_id }}",
           "handler": function(response) {
               // Handle the payment success response
               // You can submit the form or redirect to a success page
               document.forms[0].submit();
           },
           "prefill": {
               "name": "John Doe",
               "email": "john@example.com",
               "contact": "9876543210"
           }
       };
       var rzp = new Razorpay(options);
       rzp.open();
   </script>
</form>
```


**Step 7: Handle the Payment Success Callback**

Create another Django view to handle the payment success callback. This view will verify the payment status and perform any necessary actions. Here's an example:


```
def payment_success_view(request):
   order_id = request.POST.get('order_id')
   payment_id = request.POST.get('razorpay_payment_id')
   signature = request.POST.get('razorpay_signature')
   params_dict = {
       'razorpay_order_id': order_id,
       'razorpay_payment_id': payment_id,
       'razorpay_signature': signature
   }
   try:
       client.utility.verify_payment_signature(params_dict)
       # Payment signature verification successful
       # Perform any required actions (e.g., update the order status)
       return render(request, 'payment_success.html')
   except razorpay.errors.SignatureVerificationError as e:
       # Payment signature verification failed
       # Handle the error accordingly
       return render(request, 'payment_failure.html')
```


**Step 8: Update URLs**

Modify your Django project's URLs to include the new views. For example:


```
from django.urls import path
from .views import payment_view, payment_success_view

urlpatterns = [
   path('payment/', payment_view, name='payment'),
   path('payment/success/', payment_success_view, name='payment_success'),
]

```


Congratulations! You've successfully integrated Razorpay with your Django project. By following this step-by-step guide, you can now accept payments seamlessly within your web application. 
Remember to replace 'settings.RAZORPAY_API_KEY' and 'settings.RAZORPAY_API_SECRET' with your actual Razorpay API key and secret in the code. Now you're all set to provide your users with a smooth and secure payment experience. 
Happy coding!