adding paytm payment gateway
views.py
#paytm folder bna ke usme checksum.py file hogi isko import kra
#ye vo funtion he jo order place krne pr form ka data lega or paytm.html pr pahucha dega
from django.shortcuts import render
import json
from django.views.decorators.csrf import csrf_exempt #FOR PAYMENT SECURE
from paytm import checksum
MERCHANT_KEY = 'NcwqXL#gRfC0hZgW' #global veriable merchant key paytm dega
def place(request):
param_dict = {
'MID':'pPRnOe00001423145082', #apni merchand id
'ORDER_ID':str(id1), #oder ki id
'TXN_AMOUNT':str(amount),
'CUST_ID':'acfff@paytm.com',
'INDUSTRY_TYPE_ID':'Retail',
'WEBSITE':'WEBSTAGING',
'CHANNEL_ID':'WEB',
'CALLBACK_URL':'http://127.0.0.1:8000/shop/handlerequest/'
#callback_url-:paymenthone ke baad kha pr jaye ki bta ske ki payment success he ya failure
}
param_dict['CHECKSUMHASH'] = checksum.generate_checksum(param_dict, MERCHANT_KEY)
return render(request, 'shop/paytm.html', {'param_dict': param_dict})
#hamesha dictionary send hoti he render me
#ye vo funtion he jo payment sucess ya fail hone pr use handle kr status btayega
1)ye ek decorator he 20@csrf_exemp jaruri
#decorator
@csrf_exempt
def handlerequest(request):
#paytm will send you post request here
form=request.POST
response_dict={}
for i in form.keys():
response_dict[i] = form[i]
if i == 'CHECKSUMHASH':
check = form[i]
verify = checksum.verify_checksum(response_dict, MERCHANT_KEY, check)
if verify:
if response_dict['RESPCODE'] == '01':
print('order successful')
else:
print('order was not successful because' + response_dict['RESPMSG'])
return render(request, 'shop/paymentstatus.html', {'response': response_dict})
#paytm.html
#form automatic submit ho jayega /redirect ho jayega payment gateway pr
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Paytm merchant payment page</title>
</head>
<body>
<h1>Redirecting you to the merchant....</h1>
<h1>Please do not refresh your page....</h1>
<!-- for staging purpose action ki link ye rahegi production time pr alag hogi -->
<form action="https://securegw-stage.paytm.in/theia/processTransaction" method="post" name="paytm">
{% for key, value in param_dict.items %}
<input type="hidden" name="{{key}}" value="{{value}}">
{% endfor %}
</form>
</body>
<script>
document.paytm.submit() //to automatic form submit
</script>
</html>
#paymentstatus.html
#to show payment status
{% extends 'shop/basic.html' %}
{% block title%} My Awesome Cart Tracker{% endblock %}
{% block body %}
<div class="container">
{{response}}
<div class="col my-4">
<h2>Payment status regarding your order Id {{response.ORDERID}}</h2>
{% if response.RESPCODE == "01" %}
ORDER SUCCESS
{% else %}
ORDER FAILURE
{% endif%}
</div>
</div>
{% endblock %}
{% block js %}
<script>
</script>
{% endblock %}
#checksum.py
# pip install pycryptodome ko install krna pdega
import base64
import string
import random
import hashlib
from Crypto.Cipher import AES
IV = "@@@@&&&&####$$$$"
BLOCK_SIZE = 16
def generate_checksum(param_dict, merchant_key, salt=None):
params_string = __get_param_string__(param_dict)
salt = salt if salt else __id_generator__(4)
final_string = '%s|%s' % (params_string, salt)
hasher = hashlib.sha256(final_string.encode())
hash_string = hasher.hexdigest()
hash_string += salt
return __encode__(hash_string, IV, merchant_key)
def generate_refund_checksum(param_dict, merchant_key, salt=None):
for i in param_dict:
if("|" in param_dict[i]):
param_dict = {}
exit()
params_string = __get_param_string__(param_dict)
salt = salt if salt else __id_generator__(4)
final_string = '%s|%s' % (params_string, salt)
hasher = hashlib.sha256(final_string.encode())
hash_string = hasher.hexdigest()
hash_string += salt
return __encode__(hash_string, IV, merchant_key)
def generate_checksum_by_str(param_str, merchant_key, salt=None):
params_string = param_str
salt = salt if salt else __id_generator__(4)
final_string = '%s|%s' % (params_string, salt)
hasher = hashlib.sha256(final_string.encode())
hash_string = hasher.hexdigest()
hash_string += salt
return __encode__(hash_string, IV, merchant_key)
def verify_checksum(param_dict, merchant_key, checksum):
# Remove checksum
if 'CHECKSUMHASH' in param_dict:
param_dict.pop('CHECKSUMHASH')
# Get salt
paytm_hash = __decode__(checksum, IV, merchant_key)
salt = paytm_hash[-4:]
calculated_checksum = generate_checksum(param_dict, merchant_key, salt=salt)
return calculated_checksum == checksum
def verify_checksum_by_str(param_str, merchant_key, checksum):
# Remove checksum
#if 'CHECKSUMHASH' in param_dict:
#param_dict.pop('CHECKSUMHASH')
# Get salt
paytm_hash = __decode__(checksum, IV, merchant_key)
salt = paytm_hash[-4:]
calculated_checksum = generate_checksum_by_str(param_str, merchant_key, salt=salt)
return calculated_checksum == checksum
def __id_generator__(size=6, chars=string.ascii_uppercase + string.digits + string.ascii_lowercase):
return ''.join(random.choice(chars) for _ in range(size))
def __get_param_string__(params):
params_string = []
for key in sorted(params.keys()):
if("REFUND" in params[key] or "|" in params[key]):
respons_dict = {}
exit()
value = params[key]
params_string.append('' if value == 'null' else str(value))
return '|'.join(params_string)
__pad__ = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * chr(BLOCK_SIZE - len(s) % BLOCK_SIZE)
__unpad__ = lambda s: s[0:-ord(s[-1])]
def __encode__(to_encode, iv, key):
# Pad
to_encode = __pad__(to_encode)
# Encrypt
c = AES.new(key.encode('utf-8'), AES.MODE_CBC, iv.encode('utf-8'))
to_encode = c.encrypt(to_encode.encode('utf-8'))
# Encode
to_encode = base64.b64encode(to_encode)
return to_encode.decode("UTF-8")
def __decode__(to_decode, iv, key):
# Decode
to_decode = base64.b64decode(to_decode)
# Decrypt
c = AES.new(key.encode('utf-8'), AES.MODE_CBC, iv.encode('utf-8'))
to_decode = c.decrypt(to_decode)
if type(to_decode) == bytes:
# convert bytes array to str.
to_decode = to_decode.decode()
# remove pad
return __unpad__(to_decode)
if __name__ == "__main__":
params = {
"MID": "mid",
"ORDER_ID": "order_id",
"CUST_ID": "cust_id",
"TXN_AMOUNT": "1",
"CHANNEL_ID": "WEB",
"INDUSTRY_TYPE_ID": "Retail",
"WEBSITE": "xxxxxxxxxxx"
}
print(verify_checksum(
params, 'xxxxxxxxxxxxxxxx',
"CD5ndX8VVjlzjWbbYoAtKQIlvtXPypQYOg0Fi2AUYKXZA5XSHiRF0FDj7vQu66S8MHx9NaDZ/uYm3WBOWHf+sDQAmTyxqUipA7i1nILlxrk="))
# print(generate_checksum(params, "xxxxxxxxxxxxxxxx"))
urls.py(shop app vala)
from django.urls import path
from . import views
#path me name dena bahut jaruri he
urlpatterns = [
path('handlerequest/',views.handlerequest,name='handlerequest')
]
urls.py(main vala)
from django.contrib import admin
from django.urls import path,include
from django.conf import settings
from django.conf.urls.static import static
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('shop/',include('shop.urls')), #ye url ko http://127.0.0.1:8000/shop/ yesa bna dega baki aage path('blog/',include('blog.urls')), ka shop ka url add kr lega
path('',views.index) #to open with writing shop or blog
]
~/mca$ tree -a
.
├── blog
│ ├── admin.py
│ ├── apps.py
│ ├── __init__.py
│ ├── migrations
│ ├── models.py
│ ├── templates
│ │ └── blog
│ │ └── bpage.html
│ ├── tests.py
│ ├── urls.py
│ └── views.py
├── db.sqlite3
├── manage.py
├── mca
│ ├── asgi.py
│ ├── __init__.py
│ ├── settings.py
│ ├── templates
│ │ └── index.html
│ ├── urls.py
│ ├── views.py
│ └── wsgi.py
├── media
│ └── shop
│ └── images
│ ├── 3.jpeg
│ ├── aalo.jpeg
│ ├── avacardo.png
│ ├── BED.jpg
│ ├── coconuts.jpeg
│ ├── Custard_Apple.jpg
│ ├── download_1.jpeg
│ ├── download.jpeg
│ ├── Gooseberry.jpg
│ ├── Guava.jpg
│ ├── Guava_RV7Rn9M.jpg
│ ├── Jackfruit.jpg
│ ├── lemon.jpeg
│ ├── peach.jpeg
│ ├── pic.jpg
│ └── sb.jpeg
├── paytm
│ ├── checksum.py
│
├── shop
│ ├── admin.py
│ ├── apps.py
│ ├── images
│ │ ├── 7.jpeg
│ │ └── pic.jpg
│ ├── __init__.py
│ ├── migrations
│ │
│ ├── models.py
│ ├
│ ├── static
│ │ ├── 1.jpeg
│ │ ├── 2.jpeg
│ │ ├── 3.jpeg
│ │ ├── 4.jpeg
│ │ ├── 5.jpeg
│ │ └── 7.jpeg
│ ├── templates
│ │ └── shop
│ │ ├── about.html
│ │ ├── basic.html
│ │ ├── checkout.html
│ │ ├── contact.html
│ │ ├── paymentstatus.html
│ │ ├── paytm.html
│ │ ├── productview.html
│ │ ├── spage.html
│ │ └── track.html
│ ├── tests.py
│ ├── urls.py
│ └── views.py
Comments
Post a Comment