Integrating PayU With Django Rest Framework

PayU is one of India’s most popular Payment Gateways and it is used by small as well as large companies for selling their products online and collecting payments in an easy way. The SDK provided by PayU is very easy to implement and we are going to learn about it further in the post.

Note: This article does not cover the features provided by the Payment Gateway and how it works under the hood. For all such details, you can go to and check out for yourself.


This article assumes that you’ve theoretical and practical knowledge of Python, Django Rest Framework, and implementing third party libraries in it.


This article is going to be covering how to set-up a PayU account and implement a PayU payment gateway at the server side.

We will follow the steps below in order:


Now let’s start the integration process.

Create A Merchant Account In PayU

  • Go to and click on Sign Up.
  • Enter your email address and proceed.
  • Enter your personal details and verify your phone number and email address.
  • After signup, you will get your Merchant Id on the first page.
  • Select Collect Payments, you will be redirected to the merchant dashboard, you can complete all your business details on the same page and activate your account.
  • Two options occur Complete Your Profile or Start Integration
  • Select Start Integration for starting with development.
  • You will be redirected to a new page where you will get a Merchant Key and Merchant Salt for your account.

We will require Merchant Key and Merchant Salt on the server-side as it is used for generating hash for secure payment gateway transfer. Merchant ID is required on the Client-side with Merchant Key for making the payment request to PayU. The combination of Merchant Id, Key, and Salt is used for securing the Payments in the gateway. The Merchant Id and Key should be stored in Android Application. Salt should be always generated via a PHP Hash Generator Script(included in the next step).

Note: Do not share your Merchant Key, Merchant Salt and Merchant ID with anyone as it might result in tampering of the payments.

Starting With The Development Process.

1. Installation

pip3 install django-payu

2. Adding PayU App In Our Project


..., 'payu', ]

3. Adding Required Values In Settings.Py File For PayU

# Change the PAYU_MODE to 'LIVE' for production.

4. Migrating The App To Database

python migrate

What Have We Done So Far?

Step 1:

We’ve installed third party library django-payu from which we’ll be using their transaction model instead of creating our own new models.

Step 2:

As we’ve installed django-payu library, now we need to add it in our project so we add an app provided by django-payu i.e is PayU, so we add it in our INSTALLED_APPS in

Step 3:

PayU app requires your PayU account credentials like Merchant key and Merchant Salt for making transactions, so we need to provide them by adding it in file.

Step 4:

As we’ve done with our setup we will now add payu app to our database by migrating the payu app.

5. Creating Views For Generating Hash Key And Success Transactions

  • View for generating hash key
class GenerateHashKeyView(GenericAPIView):
   permission_classes = ()
   authentication_classes = ()

   def post(self, request, *args, **kwags):
       key = PAYU_MERCHANT_KEY
       txnid = str('txnid'))
       amount = str('amount'))
       productinfo = str('productinfo'))
       firstname = str('firstname'))
       email = str('email'))
       salt = PAYU_MERCHANT_SALT

       output_data = {
           'key': key,
           'salt': salt,
           'txnid': txnid,
           'amount': amount,
           'productinfo': productinfo,
           'firstname': firstname,
           'email': email,

       keys = ('txnid', 'amount', 'productinfo', 'firstname', 'email', 'udf1', 'udf2', 'udf3', 'udf4', 'udf5', 'udf6', 'udf7', 'udf8', 'udf9', 'udf10')

       def generate_hash(input_data, *args, **kwargs):
           hash_value = str(getattr(settings, 'PAYU_MERCHANT_KEY', None))

           for k in keys:
               if input_data.get(k) is None:
                   hash_value += '|' + str('')
                   hash_value += '|' + str(input_data.get(k))

           hash_value += '|' + str(getattr(settings, 'PAYU_MERCHANT_SALT', None))
           hash_value = sha512(hash_value.encode()).hexdigest().lower()
               transaction_id=input_data.get('txnid'), amount=input_data.get('amount'))
           return hash_value

       get_generated_hash = generate_hash(
       output_data['hash_key'] = get_generated_hash

       return Response(output_data)
  • View for success transaction
class SuccessView(GenericAPIView):

   def post(self, request):
       status =["status"]
       firstname =["firstname"]
       amount =["amount"]
       txnid =["txnid"]
       posted_hash =["hash"]
       key =["key"]
       productinfo =["productinfo"]
       email =["email"]
       salt = PAYU_MERCHANT_SALT

           additional_charges =["additionalCharges"]
           ret_hash_seq = additional_charges + '|' + salt + '|' + status + '|||||||||||' + email + '|' + firstname + '|' + productinfo + '|' + amount + '|' + txnid + '|' + key
       except Exception:
           ret_hash_seq = salt + '|' + status + '|||||||||||' + email + '|' + firstname + '|' + productinfo + '|' + amount + '|' + txnid + '|' + key

       resonse_hash = hashlib.sha512(ret_hash_seq.encode()).hexdigest().lower()

       if resonse_hash == posted_hash:
           transaction = Transaction.objects.get(transaction_id=txnid)
           transaction.payment_gateway_type ='PG_TYPE')
           transaction.transaction_date_time ='addedon')
           transaction.mode ='mode')
           transaction.status = status
           transaction.amount = amount
           transaction.mihpayid ='mihpayid')
           transaction.bankcode ='bankcode')
           transaction.bank_ref_num ='bank_ref_num')
           transaction.additional_charges ='additionalCharges', 0)
           transaction.txn_status_on_payu ='unmappedstatus')
           transaction.hash_status = "Success" if resonse_hash =='hash') else "Failed"
           message = ["Thank You. Your order status is " + status,
                      "Your Transaction ID for this transaction is " + txnid,
                      "We have received a payment of Rs. " + amount,
                      "Your order will soon be shipped."]
           message = ["Invalid Transaction. Please try again."]
       output_data = {
           "txnid": txnid,
           "status": status,
           "amount": amount
       return Response(output_data, message)

6. Adding The Newly Created Views In Urls.Py

from .views import (SuccessView,

urlpatterns = [
url('generateHashKey', GenerateHashKeyView.as_view(), name="generate-hash"),
    url('success', SuccessView.as_view(), name="success"),

Step 5:

We’ve already made the setup required until step 4. Now when we start to initiate a transaction PayU needs a hash key which is generally generated at server-side, which is combination of user data and PayU credentials as follows:

sha512(key | txnid | amount | productinfo | firstname | email | udf1 | udf2 | udf3 | udf4 | udf5 |||||| SALT)

A hash (checksum) is generated by a mathematical function using the Merchant key, user data and the Merchant Salt as input. The Checksum algorithm used is SHA512.

In GenerateHashKeyView Django-payu library provides functions to create a hash key but instead, we’ve used our own function to create it.

All the user data is taken as input from the client application as our view serves POST requests and returns a hash key.

The SuccessView is needed when a transaction is successfully completed and the transaction details need to be stored in the database models.

Step 6:

Our last step for development is now to add the generated view to urls so that they can be accessed as API endpoints.

Points To Remember:

  • While you are testing PayU in development mode always set PAYU_MODE=’TEST’ in, and set PAYU_MODE=’LIVE’ while using PayU in the live environment.
  • You need to set Test Mode in the PayU dashboard while you are testing in the development environment.
  • Before switching to Live Mode in the PayU you need to complete your registration process.
  • If you’re getting errors, probable solutions could be:
    1. Check your environment is the same on development code and on the PayU dashboard. For eg: file has set PAYU_MODE=’TEST’ and PayU dashboard has set Test Mode ON.
    2. Check your Merchant Key, Merchant Salt is valid or you can use Test Credentials of PayU.
    3. Most of the time you must not be generating the hash key in a proper format, the hash key generation format is needed to be in a sequential manner only as defined by PayU.

You can find the whole implementation here.

Keep Reading

Keep Reading

Struggling with EHR integration? Learn about next-gen solutions in our upcoming webinar on Mar 6, at 11 AM EST.

Register Now

Let's create something together!