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.
How to Effectively Hire and Manage a Remote Team of Developers.
Download NowThe Mindbowser team's professionalism consistently impressed me. Their commitment to quality shone through in every aspect of the project. They truly went the extra mile, ensuring they understood our needs perfectly and were always willing to invest the time to...
CTO, New Day Therapeutics
I collaborated with Mindbowser for several years on a complex SaaS platform project. They took over a partially completed project and successfully transformed it into a fully functional and robust platform. Throughout the entire process, the quality of their work...
President, E.B. Carlson
Mindbowser and team are professional, talented and very responsive. They got us through a challenging situation with our IOT product successfully. They will be our go to dev team going forward.
Founder, Cascada
Amazing team to work with. Very responsive and very skilled in both front and backend engineering. Looking forward to our next project together.
Co-Founder, Emerge
The team is great to work with. Very professional, on task, and efficient.
Founder, PeriopMD
I can not express enough how pleased we are with the whole team. From the first call and meeting, they took our vision and ran with it. Communication was easy and everyone was flexible to our schedule. I’m excited to...
Founder, Seeke
Mindbowser has truly been foundational in my journey from concept to design and onto that final launch phase.
CEO, KickSnap
We had very close go live timeline and Mindbowser team got us live a month before.
CEO, BuyNow WorldWide
If you want a team of great developers, I recommend them for the next project.
Founder, Teach Reach
Mindbowser built both iOS and Android apps for Mindworks, that have stood the test of time. 5 years later they still function quite beautifully. Their team always met their objectives and I'm very happy with the end result. Thank you!
Founder, Mindworks
Mindbowser has delivered a much better quality product than our previous tech vendors. Our product is stable and passed Well Architected Framework Review from AWS.
CEO, PurpleAnt
I am happy to share that we got USD 10k in cloud credits courtesy of our friends at Mindbowser. Thank you Pravin and Ayush, this means a lot to us.
CTO, Shortlist
Mindbowser is one of the reasons that our app is successful. These guys have been a great team.
Founder & CEO, MangoMirror
Kudos for all your hard work and diligence on the Telehealth platform project. You made it possible.
CEO, ThriveHealth
Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.
CEO, SMILINGMIND
They were a very responsive team! Extremely easy to communicate and work with!
Founder & CEO, TotTech
We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.
Co-Founder, TEAM8s
Mindbowser was very helpful with explaining the development process and started quickly on the project.
Executive Director of Product Development, Innovation Lab
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.
Co-Founder, Vesica
Mindbowser is professional, efficient and thorough.
Consultant, XPRIZE
Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.
Founder, S.T.A.R.S of Wellness
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.
Co-Founder, Flat Earth
Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.
Founder, Child Life On Call
The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!
CEO, SDOH2Health LLC
Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.
CEO, Stealth Startup
Mindbowser was an excellent partner in developing my fitness app. They were patient, attentive, & understood my business needs. The end product exceeded my expectations. Thrilled to share it globally.
Owner, Phalanx
Mindbowser's expertise in tech, process & mobile development made them our choice for our app. The team was dedicated to the process & delivered high-quality features on time. They also gave valuable industry advice. Highly recommend them for app development...
Co-Founder, Fox&Fork