PayU With Django Rest Framework

PayU is a payment gateway used for secured payment transactions, PayU is available in 200+ countries across the globe that’s the reason it has a number of customers, and also it provides the best services to their customers and it gives service at a reasonable cost. The blog contains different steps so that we can understand how to use PayU using Django, we are going to add design templates with payment logic and PayU.

Different steps required to implement PayU using Django are given below

  1. Library required to use PayU in Django
  2. PayU dashboard and setup connectivity
  3. Creating templates
  4. Creating a view for checkout
  5. Handling Success
  6. Handling Failure

1. Library required to use PayU in Django

To integrate PayU with Django, you need to install paywix with the latest version 1.3.0 The following command is used to install PayU in Django.

pip install paywix

2. PayU dashboard and setup connectivity

In the PayU dashboard as we are now developing gateway, we need to switch live mode to test mode as shown in the below image.

To setup connectivity you need different keys of PayU, using PayU you require a merchant key and merchant salt key, and to get these keys you need to create your account and get it and then you need to add these details to settings.py of your project and to get the credentials you need to follow the below steps.

  • Sign in to PayU
  • Go to Integration help
  • Click on the credential
  • Get a publishable key and secret key as given in the below imagef

credentials

 

keys

  • Adding credentials to Django settings
  • Create an object with PAYU_CONFIG and inside that object, we need to add keys and mode. Mode means in which mode we are working test or live,
PAYU_CONFIG = {

    "merchant_key": *********,

    "merchant_salt":*********, ,

    "mode": "test",

   }

3. Creating templates

After adding keys to Django settings you need to create templates to design a payment gateway.to use templates in your project add templates in Django setting as shown below

TEMPLATES = [

   {

       'BACKEND': 'django.template.backends.django.DjangoTemplates',

       'DIRS': [BASE_DIR+'/templates'],

       'APP_DIRS': True,

       'OPTIONS': {

           'context_processors': [

               'django.template.context_processors.debug',

               'django.template.context_processors.request',

               'django.contrib.auth.context_processors.auth',

               'django.contrib.messages.context_processors.messages',

           ],

       },

   },

]

After that, you need to create a folder in the Django project as shown below

  • Firstly we need to create the design of a home page, the home page contains simple UI with pay button and price
<html>

  <head>

      <title>Loading...</title>

  </head>

<body>

<h1>Hello</h1>

<a href="{% url 'payu_demo' %}"> Pay_demo</a>

</body>


  </html>
  • After creating a template for the payment gateway home page we also need to create a template for payu checkout as shown below.
<html>

  <head>

      <title>Loading...</title>

  </head>


  <body onload="document.payuForm.submit()">

      <form action={{ posted.action }} method="post" name="payuForm">

          {% csrf_token %}

          <input type="hidden" name="key" value="{{posted.key}}" />

          <input type="hidden" name="hash_string" value="{{ posted.hash_string }}" />

          <input type="hidden" name="hash" value="{{ posted.hashh }}" />

          <input type="hidden" name="posted" value="{{ posted }}" />

          <input type="hidden" name="txnid" value="{{ posted.txnid }}" />

          <input type="hidden" name="amount" value="{{ posted.amount|default:'' }}" /></td>

          <input type="hidden" name="firstname" id="firstname" value="{{ posted.firstname|default:'' }}" /></td>

          <input type="hidden" name="email" id="email" value="{{ posted.email|default:'' }}" /></td>

          <input type="hidden" name="phone" value="{{ posted.phone|default:'' }}" /></td>

          <textarea type="hidden" name="productinfo" style="display:none;">{{ posted.productinfo|default:'' }}</textarea>

          </td>

          <input type="hidden" name="surl" value="{{ posted.surl }}" size="64" /></td>

          <input type="hidden" name="furl" value="{{ posted.furl }}" size="64" /></td>

          <input type="hidden" name="service_provider" value="{{posted.service_provider}}" size="64" />

          <input type="hidden" name="lastname" id="lastname" value="{{ posted.lastname }}" /></td>

          <input type="hidden" name="address1" value="{{ posted.address1 }}" /></td>

          <input type="hidden" name="address2" value="{{ posted.address2 }}" /></td>

          <input type="hidden" name="city" value="{{ posted.city }}" /></td>

          <input type="hidden" name="state" value="{{ posted.state }}" /></td>

          <input type="hidden" name="country" value="{{ posted.country }}" /></td>

          <input type="hidden" name="zipcode" value="{{ posted.zipcode }}" /></td>

          <input type="hidden" name="udf1" value="{{ posted.udf1 }}" /></td>

          <input type="hidden" name="udf2" value="{{ posted.udf2 }}" /></td>

          <input type="hidden" name="udf3" value="{{ posted.udf3 }}" /></td>

          <input type="hidden" name="udf4" value="{{ posted.udf4 }}" /></td>

          <input type="hidden" name="udf5" value="{{ posted.udf5 }}" /></td>

      </form>

  </body>

  </html>

4. Creating a view for checkout

Creating a view for checkout is a simple task. In this task, we have to send data html template only by using render method and need to send user details and hash key to template that we have created for payment gateway design.

class PayuDemoAPiView(GenericAPIView):

    """

       Class for creating API view for Payment.

       """


    def get(self, request):

        """

        Function for Payment.

        """

        data = {'amount': '10',

                'firstname': test,

                'email': 'test@gmail.com',

                'phone': '1122334455', 'productinfo': 'test',

                'lastname': 'test', 'address1': 'test',

                'address2': 'test', 'city': 'test',

                'state': 'test', 'country': 'test',

                'zipcode': 'tes'

                }


        data.update({"txnid": "123456789"})

        payu_data = payu.transaction(**data)

        return render(request, 'payu_checkout.html', {"posted": payu_data})

Hask hay is generated by using the PayU transaction method and then we can pass it to the checkout template.

5. Handling a success

Handling success is an important step in the payment process. In this process after the transaction successfully completed then we need to show all transaction details and for that, we need to call API view of a successful transaction.

  • Firstly we need to handle URL so that after a successful transaction success API view is called. So for that, we need to add URL details in settings.py in PAYU_CONFIG as below
PAYU_CONFIG = {

    "merchant_key": "********",

    "merchant_salt": "********",

    "mode": "test",

    "success_url": "http://127.0.0.1:8000/success",

}
  • After calling success API view we need to add API view for success as below
class PayuSuccessAPiView(GenericAPIView):

    """

       Class for creating API view for Payment Success.

       """

    serializer_class = TransactionDetailsSerializer


    def post(self, request):

        """

        Function for Payment Success.

        """

        serializer = self.get_serializer(data=request.data)

        data = {k: v[0] for k, v in dict(request.data).items()}

        if serializer.is_valid():

            serializer.save()

        response = payu.verify_transaction(data)

        return JsonResponse(response)

After successful payment, we have also stored payment transaction details to the database using serializers as shown in the above code.

6. Handling a failure

Handling failure is the last step in the transaction process. In this process after the transaction failed then we need to call api view of transaction failure.

  • Firstly we need to handle url so that after transaction failure api view is called.So for that we need to add url details in settings.py in PAYU_CONFIG as below
PAYU_CONFIG = {

    "merchant_key": "********",

    "merchant_salt": "********",

    "mode": "test",

    "failure_url": "http://127.0.0.1:8000/failure",

}
  • After calling failure api view we need to add api view for failure as below
class PayuFailureAPiView(GenericAPIView):

    """

       Class for creating API view for Payment Failure.

       """


    @csrf_exempt

    def post(self, request):

        """

        Function for Payment Failure.

        """

        data = {k: v[0] for k, v in dict(request.data).items()}

        response = payu.verify_transaction(data)

        return JsonResponse(response)

Here, we have also added the PayU method to .verify the transaction to check whether transactions are failed or not

Conclusion

This blog covered how to design a payment gateway with good UI and how we can add different fields in it, also how to use templates in Django, and it also gives us ideas about how to create checkout and generate hash keys and also covered how to handle transaction success and failure.

Code snippet

view.py

from django.http import JsonResponse

from django.shortcuts import render

from django.views.decorators.csrf import csrf_exempt

from django.conf import settings

from paywix.payu import Payu

from rest_framework.generics import GenericAPIView


from .serializers import TransactionDetailsSerializer


payu_config = settings.PAYU_CONFIG

merchant_key = payu_config.get('merchant_key')

merchant_salt = payu_config.get('merchant_salt')

surl = payu_config.get('success_url')

furl = payu_config.get('failure_url')

mode = payu_config.get('mode')


payu = Payu(merchant_key, merchant_salt, surl, furl, mode)


def home(request):

    print("request", request)


    return render(request, 'home.html')


class PayuDemoAPiView(GenericAPIView):

    """

       Class for creating API view for Payment.

       """

    def get(self, request):

        """

        Function for Payment.

        """

        data = {'amount': '10',

                'firstname': 'rishikesh',

                'email': 'rishidevkate@gmail.com',

                'phone': '7276034203', 'productinfo': 'test',

                'lastname': 'test', 'address1': 'test',

                'address2': 'test', 'city': 'test',

                'state': 'test', 'country': 'test',

                'zipcode': 'tes'

                }


        data.update({"txnid": "123456789"})

        payu_data = payu.transaction(**data)

        return render(request, 'payu_checkout.html', {"posted": payu_data})


class PayuSuccessAPiView(GenericAPIView):

    """

       Class for creating API view for Payment Success.

       """

    serializer_class = TransactionDetailsSerializer


    def post(self, request):

        """

        Function for Payment Success.

        """

        serializer = self.get_serializer(data=request.data)


        data = {k: v[0] for k, v in dict(request.data).items()}

        if serializer.is_valid():

            serializer.save()

        response = payu.verify_transaction(data)

        return JsonResponse(response)


class PayuFailureAPiView(GenericAPIView):

    """

       Class for creating API view for Payment Failure.

       """


    @csrf_exempt

    def post(self, request):

        """

        Function for Payment Failure.

        """

        data = {k: v[0] for k, v in dict(request.data).items()}

        response = payu.verify_transaction(data)

        return JsonResponse(response)

templates/checkout.html

 <html>

  <head>

      <title>Loading...</title>

  </head>


  <body onload="document.payuForm.submit()">

      <form action={{ posted.action }} method="post" name="payuForm">

          {% csrf_token %}

          <input type="hidden" name="key" value="{{posted.key}}" />

          <input type="hidden" name="hash_string" value=

                  "{{ posted.hash_string }}" />

          <input type="hidden" name="hash" value="{{ posted.hashh }}" 

          />

          <input type="hidden" name="posted" value="{{ posted }}" />

          <input type="hidden" name="txnid" value="{{ posted.txnid }}"

          />

          <input type="hidden" name="amount" value="{{ posted.amount

          |default:'' }}" /></td>

          <input type="hidden" name="firstname" id="firstname"

                 value="{{ posted.firstname|default:'' }}"

          /></td>

          <input type="hidden" name="email" id="email" value=

                  "{{ posted.email|default:'' }}"

          /></td>

          <input type="hidden" name="phone" value="

          {{ posted.phone|default:'' }}" /></td>

          <textarea type="hidden" name="productinfo" 

                    style="display:none;">{{

              posted.productinfo|default:

              '' }}

          </textarea>

          </td>

          <input type="hidden" name="surl" value="{{ posted.surl }}"

                 size="64" /></td>

          <input type="hidden" name="furl" value="{{ posted.furl }}" 

                 size="64" /></td>

          <input type="hidden" name="service_provider" value="

          {{posted.service_provider}}"

                 size="64" />

          <input type="hidden" name="lastname" id="lastname" 

                 value="{{ posted.lastname }}"

          /></td>

          <input type="hidden" name="address1" value="

          {{ posted.address1 }}" /></td>

          <input type="hidden" name="address2" value="

          {{ posted.address2 }}" /></td>

          <input type="hidden" name="city" value="

          {{ posted.city }}" /></td>

          <input type="hidden" name="state" value="

          {{ posted.state }}" /></td>

          <input type="hidden" name="country" value="

          {{ posted.country }}" /></td>

          <input type="hidden" name="zipcode" value="

          {{ posted.zipcode }}" /></td>

          <input type="hidden" name="udf1" value="

          {{ posted.udf1 }}" /></td>

          <input type="hidden" name="udf2" value="

          {{ posted.udf2 }}" /></td>

          <input type="hidden" name="udf3" value="

          {{ posted.udf3 }}" /></td>

          <input type="hidden" name="udf4" value="

          {{ posted.udf4 }}" /></td>

          <input type="hidden" name="udf5" value="

          {{ posted.udf5 }}" /></td>

      </form>

  </body>

  </html>

 

Rishikesh

Full-stack developer

Rishikesh is a Full-stack developer with 3+ years of experience. He has experience in web technologies like AngularJS, ReactJS. His expertise is building Python integrated web applications, creating REST APIs with well-designed, testable and efficient and optimized code. He loves to learn new technologies.

Get in touch for a detailed discussion.

Hear From Our 100+ Customers
coma

Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.

author
ADDIE WOOTTEN
CEO, SMILINGMIND
coma

We had very close go live timeline and MindBowser team got us live a month before.

author
Shaz Khan
CEO, BuyNow WorldWide
coma

They were a very responsive team! Extremely easy to communicate and work with!

author
Kristen M.
Founder & CEO, TotTech
coma

We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.

author
Chacko Thomas
Co-Founder, TEAM8s
coma

Mindbowser is one of the reasons that our app is successful. These guys have been a great team.

author
Dave Dubier
Founder & CEO, MangoMirror
coma

Mindbowser was very helpful with explaining the development process and started quickly on the project.

author
Hieu Le
Executive Director of Product Development, Innovation Lab
coma

The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.

author
Alex Gobel
Co-Founder, Vesica
coma

Mindbowser is professional, efficient and thorough. 

author
MacKenzie R
Consultant at XPRIZE
coma

Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.

author
Laurie Mastrogiani
Founder, S.T.A.R.S of Wellness
coma

MindBowser was great; they listened to us a lot and helped us hone in on the actual idea of the app.” “They had put together fantastic wireframes for us.

author
Bennet Gillogly
Co-Founder, Flat Earth
coma

They're very tech-savvy, yet humble.

author
Uma Nidmarty
CEO, GS Advisorate, Inc.
coma

Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.

author
Katie Taylor
Founder, Child Life On Call
coma

As a founder of a budding start-up, it has been a great experience working with Mindbower Inc under Ayush's leadership for our online digital platform design and development activity.

author
Radhika Kotwal
Founder of Courtyardly
coma

The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!

author
Michael Wright
Chief Executive Officer, SDOH2Health LLC
coma

They are focused, patient and; they are innovative. Please give them a shot if you are looking for someone to partner with, you can go along with Mindbowser.

author
David Cain
CEO, thirty2give
coma

We are a small non-profit on a budget and they were able to deliver their work at our prescribed budgets. Their team always met their objectives and I'm very happy with the end result. Thank you, Mindbowser team!!

author
Bart Mendel
Founder, Mindworks