DEV Community


Posted on

Razozpay Integration with Django

To make use of razorpay in our application we are going to use this razorpay python package. We need to install it first.

pip install razorpay
Enter fullscreen mode Exit fullscreen mode

Once signup is complete, Make sure you are in test mode and not live mode. Visit Razorpay Dashboard and create new api keys.

The api keys are shown just once so, make sure you save it. Ok so, you have already put it in your settings file,good. Not Good !!! Secrets should remain secrets, either we should put them as environment variables or in a json file which we won't push to Github.
Lets create an url, upon visiting which we should be provided with a Button, When we click on the button then we should be provided us with payment gateway screen.
But for this lets create our view first.

import os
import razorpay

from django.shortcuts import render
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt

def payment(request):
    amount = 100 #100 here means 1 dollar,1 rupree if currency INR
    client = razorpay.Client(auth=(os.getenv('razorpaykey'), os.getenv('razorpaysecret')))
    response = client.order.create({'amount':amount,'currency':'USD','payment_capture':1})
    context = {'response':response}
    return render(request,"payments/payment.html",context)

def payment_success(request):
    if request.method =="POST":
        return HttpResponse("Done payment hurrey!")
Enter fullscreen mode Exit fullscreen mode

This will be our HTML file and it will be responsible for getting a razozpay button which when click will generate the payment form.
Alt Text

{% if response %}
<form action="/success/" method="POST">
        data-buttontext="Pay with Razorpay"
    <input type="hidden" custom="Hidden Element" name="hidden">
{% endif %}
Enter fullscreen mode Exit fullscreen mode

Hook up the views i.e. payment and payment_success with url of your choice, Make sure to update the HTML file form-action with your success url. One more thing is once payment is success, Razorpay will send a POST request to our application at success url. Since the form is not having csrf_token we can exempt csrf_token. It is advised that, we should make use of webhooks and then exempt csrf_token.

This is an e.g. of my file:

from django.urls import path

from apps.payments.views import payment,payment_success

urlpatterns = [

Enter fullscreen mode Exit fullscreen mode

This is a minimal configuration to get Razorpay to work with django. There are still things which needs to be improved or integrated e.g. Subscription, invoices, refunds, routes, and most important security and signature verification etc.

I am planning to update more payment options e.g. paypal and instamojo :

Top comments (1)

jumar98 profile image
Julián David Martínez Villarreal

Nice work, I enjoy reading this article, go ahead with a second part.