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.
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.
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.
pip3 install django-payu
INSTALLED_APPS = [ ..., '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"
python manage.py migrate
We’ve installed third party library django-payu from which we’ll be using their transaction model instead of creating our own new models.
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
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.
As we’ve done with our setup we will now add payu app to our database by migrating the payu app.
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)
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"), ]
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.
Our last step for development is now to add the generated view to urls so that they can be accessed as API endpoints.
You can find the whole implementation here.
What’s on your mind? Tell us a little bit about yourself and your question, and we will be in touch with you within 12 hours
Free eBook on Telemedicine Platform Development: All About Telemedicine
Download Free eBook Now!