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 https://payu.in/ and check out for yourself.

Prerequisites

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

Preface

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:

how-to-implement-payu-payment-gateway

Now let’s start the integration process.

Create A Merchant Account In PayU

  • Go to https://payu.in/ 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

INSTALLED_APPS = [

..., 'payu', ]

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

PAYU_MERCHANT_KEY = "ADD_YOUR_MERCHANT_KEY"
PAYU_MERCHANT_SALT = "ADD_YOUR_MERCHANT_SALT"
# Change the PAYU_MODE to 'LIVE' for production.
PAYU_MODE = "TEST"

4. Migrating The App To Database

python manage.py 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 settings.py

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 settings.py 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(request.data.get('txnid'))
       amount = str(request.data.get('amount'))
       productinfo = str(request.data.get('productinfo'))
       firstname = str(request.data.get('firstname'))
       email = str(request.data.get('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('')
               else:
                   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.objects.create(
               transaction_id=input_data.get('txnid'), amount=input_data.get('amount'))
           return hash_value

       get_generated_hash = generate_hash(request.data)
       output_data['hash_key'] = get_generated_hash

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

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

       try:
           additional_charges = request.data["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 = request.data.get('PG_TYPE')
           transaction.transaction_date_time = request.data.get('addedon')
           transaction.mode = request.data.get('mode')
           transaction.status = status
           transaction.amount = amount
           transaction.mihpayid = request.data.get('mihpayid')
           transaction.bankcode = request.data.get('bankcode')
           transaction.bank_ref_num = request.data.get('bank_ref_num')
           transaction.discount = request.data.get('discount')
           transaction.additional_charges = request.data.get('additionalCharges', 0)
           transaction.txn_status_on_payu = request.data.get('unmappedstatus')
           transaction.hash_status = "Success" if resonse_hash == request.data.get('hash') else "Failed"
           transaction.save()
           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."]
       else:
           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,
                   GenerateHashKeyView
                   )

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 setting.py, 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: settings.py 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

  • Service
  • Career
  • Let's create something together!

  • We’re looking for the best. Are you in?