Django Python Razorpay Payment Gateway Integration Example

Published On: 02/07/2022 | Category: Django Python


Hi Dev,

This article goes in detailed on razorpay payment gateway integration with python django. we will help you to give example of razorpay payment gateway integration with django app. This post will give you simple example of razorpay payment gateway integration with django developer. you'll learn razorpay payment gateway integration with python django database. Let's see bellow example razorpay payment gateway integration with django example.

Razorpay is very simple, hassle free and easy to integrate payment gateway.Razorpay is one of the popular payment gateway, that allows us to accept payment from your customer.

Here i explained simply step by step let's see bellow example razorpay payment gateway integration with django example.

Step 1 : Create a Project

In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject example
Step 2 : Create a App
python3 manage.py startapp payment
Step 3 : Update setting.py

In this step we require to do two things in our settings.py file, One is to change the path of template look up directory. Second one is to configure our media folder. Add the below lines to your settings.py file:

So, in this exmaple we will use bootstrap 4 crispy forms Crispy Bootstrap Template Pack so if you have not installed so you can follow this article will help you..

Next, you need to add it in the settings.py file as follows:

....
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'payment',
    'crispy_forms',
]
Step 4 : Database Setup

Next step, we will modify the settings.py file and update the database settings to configure the mydb database:

settings.py
DATABASES = {  
    'default': {  
        'ENGINE': 'django.db.backends.mysql',  
        'NAME': 'example',  
        'USER':'root',  
        'PASSWORD':'root',  
        'HOST':'localhost',  
        'PORT':'3306'  
    }  
}  
Step 5: Create Razorpay Account

First you need to create account on razorpay. then you can easily get account key id and key secret.

Create Account from here: www.razorpay.com.

After register successfully. you need to go bellow link and get id and secret as bellow screen shot:

Go Here: https://dashboard.razorpay.com/app/keys.

Next you can get account key id and secret and add on settings.py file as like bellow:

setting.py
RAZORPAY_KEY_ID = YOUR_KEY_ID
RAZORPAY_KEY_SECRET = YOUR_KEY_SECRET
Step 6: Install Razorpay Library

In this step, we need to install razorpay package to use razorpay api. so let's run bellow command:

pip install razorpay
Step 7: Create a Model

In this step we will require the database model for storing contacts.Open the payment/models.py file and add the following code:

payment/models.py
from django.db import models

class Order(models.Model):
    name = models.CharField(max_length=100)
    amount = models.CharField(max_length=100)
    order_id = models.CharField(max_length=100, blank=True)
    razorpay_payment_id = models.CharField(max_length=100, blank=True)
    paid = models.BooleanField(default=False)
Step 8: Create a FormClass

In this step we will require the create a formclass for some adding bootstrap class and add button.Open the payment/models.py file and add the following code:

payment/forms.py
from django import forms
from .models import Order
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Submit

class OrderForm(forms.ModelForm):
    class Meta:
        model = Order
        fields = "__all__"

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper(self)
        self.helper.layout = Layout(
            'name',
            'amount',
            Submit('submit', 'Buy', css_class='button white btn-block btn-primary')
        )

After creating these model, you need to create migrations using the following command:

Step 9 : Create a Migrations
python manage.py makemigrations

After successfully run the above command go to the payment/migrations/0001_initial.py

payment/migrations/0001_initial.py
# Generated by Django 4.0.5 on 2022-07-01 06:10

from django.db import migrations, models


class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Order',
            fields=[
                ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=100)),
                ('amount', models.CharField(max_length=100)),
                ('order_id', models.CharField(blank=True, max_length=100)),
                ('razorpay_payment_id', models.CharField(blank=True, max_length=100)),
                ('paid', models.BooleanField(default=False)),
            ],
        ),
    ]

Next, you need to migrate your database using the following command:

python manage.py migrate
Step 10 : Creating the Views

In this step, we need to create the views for performing fetch record to the database.Open the payment/views.py file and add:

payment/views.py
from django.shortcuts import render
from .forms import OrderForm
import razorpay
from .models import Order
from django.conf import settings

def payment(request):
    if request.method == "POST":
        name = request.POST.get('name')
        amount = int(request.POST.get('amount')) * 100

        # create Razorpay client
        client = razorpay.Client(auth=(settings.RAZORPAY_KEY_ID, settings.RAZORPAY_KEY_SECRET))

        # create order
        response_payment = client.order.create(dict(amount=amount,
                                                    currency='INR')
                                               )

        order_id = response_payment['id']
        order_status = response_payment['status']

        if order_status == 'created':
            order = Order(
                name=name,
                amount=amount,
                order_id=order_id,
            )
            order.save()
            response_payment['name'] = name

            form = OrderForm(request.POST or None)
            return render(request, 'payment.html', {'form': form, 'payment': response_payment})

    form = OrderForm()
    return render(request, 'payment.html', {'form': form})


def payment_status(request):
    response = request.POST
    params_dict = {
        'razorpay_order_id': response['razorpay_order_id'],
        'razorpay_payment_id': response['razorpay_payment_id'],
        'razorpay_signature': response['razorpay_signature']
    }

    # client instance
    client = razorpay.Client(auth=(settings.RAZORPAY_KEY_ID, settings.RAZORPAY_KEY_SECRET))

    try:
        status = client.utility.verify_payment_signature(params_dict)
        order = Order.objects.get(order_id=response['razorpay_order_id'])
        order.razorpay_payment_id = response['razorpay_payment_id']
        order.paid = True
        order.save()
        return render(request, 'callback.html', {'status': True})
    except:
        return render(request, 'callback.html', {'status': False})
Step 11 : Creating the Templates

Next, open the payment/templates/base.html file and the add:

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Tuts-Stations Member</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"
            integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="{% static 'css/font-awesome-4.7.0/css/font-awesome.min.css' %}">
    <style type="text/css">
        .success-animation {
          margin: 50px auto;
        }
        .checkmark {
          width: 100px;
          height: 100px;
          border-radius: 50%;
          display: block;
          stroke-width: 2;
          stroke: #4bb71b;
          stroke-miterlimit: 10;
          box-shadow: inset 0px 0px 0px #4bb71b;
          animation: fill 0.4s ease-in-out 0.4s forwards,
            scale 0.3s ease-in-out 0.9s both;
          position: relative;
          top: 5px;
          right: 5px;
          margin: 0 auto;
        }
        .checkmark__circle {
          stroke-dasharray: 166;
          stroke-dashoffset: 166;
          stroke-width: 2;
          stroke-miterlimit: 10;
          stroke: #4bb71b;
          fill: #fff;
          animation: stroke 0.6s cubic-bezier(0.65, 0, 0.45, 1) forwards;
        }
        .checkmark__check {
          transform-origin: 50% 50%;
          stroke-dasharray: 48;
          stroke-dashoffset: 48;
          animation: stroke 0.3s cubic-bezier(0.65, 0, 0.45, 1) 0.8s forwards;
        }
        @keyframes stroke {
          100% {
            stroke-dashoffset: 0;
          }
        }
        @keyframes scale {
          0%,
          100% {
            transform: none;
          }
          50% {
            transform: scale3d(1.1, 1.1, 1);
          }
        }
        @keyframes fill {
          100% {
            box-shadow: inset 0px 0px 0px 30px #4bb71b;
          }
        }
    </style>
</head>
<body>

{% block content %}
{% endblock content %}

</body>
</html>

Next, open the payment/templates/payment.html file and the add:

{% extends 'base.html' %}
{% load crispy_forms_tags %}

{% block content %}
    <div class="container mt-5 pt-5">
        <div class="row d-flex justify-content-center">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h3>Become a Member!</h3>
                    </div>
                    <div class="card-body">
                        {% crispy form %}
                        <div class="row mt-2">
                            <div class="col-md-12">
                                {% if payment %}
                                    <form action="{% url 'payment-status' %}" method="POST" class="payment-status">
                                        {% csrf_token %}
                                        <script
                                                src="https://checkout.razorpay.com/v1/checkout.js"
                                                data-key="rzp_test_pw9gzzwaOSMUxs"
                                                data-amount="{{ payment.amount }}"
                                                data-currency="{{ payment.currency }}"
                                                data-order_id="{{ payment.id }}"
                                                data-buttontext="Pay with Razorpay"
                                                data-name="Tuts-Station Membership"
                                                data-description="Become a Premium Member!"
                                                data-image="https://tuts-station.com/image/tuts-s-favicon.png"
                                                data-prefill.name="{{ payment.name }}"
                                                data-prefill.email="[email protected]"
                                                data-theme.color="#271EA2"
                                        ></script>
                                        <input type="hidden" custom="Hidden Element" name="hidden">
                                    </form>
                                {% endif %}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
<script type="text/javascript">
    $('.razorpay-payment-button').addClass('btn btn-success');
</script>
{% endblock %}

Next, open the payment/templates/callback.html file and the add:

{% extends 'base.html' %}

{% block content %}

    {% if status %}
        <div class="container" style="text-align: center;">
            <div class="success-animation">
              <svg class="checkmark" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 52 52">
                <circle class="checkmark__circle" cx="26" cy="26" r="25" fill="none" />
                <path class="checkmark__check" fill="none" d="M14.1 27.2l7.1 7.2 16.7-16.8" />
              </svg>
            </div>
        </div>
        <h2 style="text-align: center;">Thank you. Your payment was successful.</h2>
    {% else %}
        <h2 style="text-align: center;">Your Payment is failed! Try again.</h2>
    {% endif %}

    <div class="text-center mt-5">
        <a href="{% url 'payment' %}" class="btn btn-primary" role="button">Buy another one</a>
    </div>
{% endblock %}
Step 12 : Creating URLs

In this section, we’ll create the urls to access our views.Go to the urls.py payment/urls.py file and update it as follows:

payment/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('', views.payment, name='payment'),
    path('payment-status', views.payment_status, name='payment-status')
]

Next, we will require the modify the urls.py your root preoject folder lets update the file.

example/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('payment.urls')),
]
Run the Server

In this step, we’ll run the local development server for playing with our app without deploying it to the web.

python manage.py runserver

Next, go to the http://localhost:8000/ address with a web browser.

We can check all these payment in Razorpay dashboard



I Hope It will help you....