├── pay2me ├── __init__.py ├── wsgi.py ├── urls.py └── settings.py ├── payments ├── __init__.py ├── migrations │ ├── __init__.py │ └── 0001_initial.py ├── admin.py ├── tests.py ├── apps.py ├── urls.py ├── templates │ └── payments │ │ ├── pay.html │ │ ├── callback.html │ │ └── redirect.html ├── models.py ├── views.py └── paytm.py ├── .gitignore ├── templates └── registration │ └── login.html └── manage.py /pay2me/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /payments/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /payments/migrations/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /payments/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | # Register your models here. 4 | -------------------------------------------------------------------------------- /payments/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | 3 | # Create your tests here. 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | env/ 2 | venv/ 3 | .vscode/ 4 | .idea/ 5 | *.sqlite3 6 | __pycache__/ 7 | *.pyc 8 | 9 | -------------------------------------------------------------------------------- /payments/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class PaymentsConfig(AppConfig): 5 | name = 'payments' 6 | -------------------------------------------------------------------------------- /payments/urls.py: -------------------------------------------------------------------------------- 1 | from django.urls import path 2 | from .views import initiate_payment, callback 3 | 4 | urlpatterns = [ 5 | path('pay/', initiate_payment, name='pay'), 6 | path('callback/', callback, name='callback'), 7 | ] 8 | -------------------------------------------------------------------------------- /templates/registration/login.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Login 4 | 5 | 6 | 7 |

Login

8 |
9 | {% csrf_token %} 10 | {{ form.as_p }} 11 | 12 |
13 | 14 | 15 | -------------------------------------------------------------------------------- /pay2me/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for pay2me project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pay2me.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """Django's command-line utility for administrative tasks.""" 3 | import os 4 | import sys 5 | 6 | 7 | def main(): 8 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pay2me.settings') 9 | try: 10 | from django.core.management import execute_from_command_line 11 | except ImportError as exc: 12 | raise ImportError( 13 | "Couldn't import Django. Are you sure it's installed and " 14 | "available on your PYTHONPATH environment variable? Did you " 15 | "forget to activate a virtual environment?" 16 | ) from exc 17 | execute_from_command_line(sys.argv) 18 | 19 | 20 | if __name__ == '__main__': 21 | main() 22 | -------------------------------------------------------------------------------- /payments/templates/payments/pay.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Payment Home 5 | 6 | 7 | 8 |

Payment Home

9 | {% if error %} 10 |

{{ error }}

11 | {% endif %} 12 |
13 | {% csrf_token %} 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | -------------------------------------------------------------------------------- /payments/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | from django.contrib.auth import get_user_model 3 | 4 | 5 | User = get_user_model() 6 | 7 | 8 | class Transaction(models.Model): 9 | made_by = models.ForeignKey(User, related_name='transactions', on_delete=models.CASCADE) 10 | made_on = models.DateTimeField(auto_now_add=True) 11 | amount = models.IntegerField() 12 | order_id = models.CharField(unique=True, max_length=100, null=True, blank=True) 13 | checksum = models.CharField(max_length=100, null=True, blank=True) 14 | 15 | def save(self, *args, **kwargs): 16 | if self.order_id is None and self.made_on and self.id: 17 | self.order_id = self.made_on.strftime('PAY2ME%Y%m%dODR') + str(self.id) 18 | return super().save(*args, **kwargs) 19 | -------------------------------------------------------------------------------- /pay2me/urls.py: -------------------------------------------------------------------------------- 1 | """pay2me URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/2.2/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | from django.contrib import admin 17 | from django.urls import path, include 18 | from django.contrib.auth.views import LoginView 19 | 20 | urlpatterns = [ 21 | path('admin/', admin.site.urls), 22 | path('login/', LoginView.as_view(), name='login'), 23 | path('', include('payments.urls')) 24 | ] 25 | -------------------------------------------------------------------------------- /payments/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.2.5 on 2020-01-20 19:52 2 | 3 | from django.conf import settings 4 | from django.db import migrations, models 5 | import django.db.models.deletion 6 | 7 | 8 | class Migration(migrations.Migration): 9 | 10 | initial = True 11 | 12 | dependencies = [ 13 | migrations.swappable_dependency(settings.AUTH_USER_MODEL), 14 | ] 15 | 16 | operations = [ 17 | migrations.CreateModel( 18 | name='Transaction', 19 | fields=[ 20 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 21 | ('made_on', models.DateTimeField(auto_now_add=True)), 22 | ('amount', models.IntegerField()), 23 | ('order_id', models.CharField(blank=True, max_length=100, null=True, unique=True)), 24 | ('checksum', models.CharField(blank=True, max_length=100, null=True)), 25 | ('made_by', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='transactions', to=settings.AUTH_USER_MODEL)), 26 | ], 27 | ), 28 | ] 29 | -------------------------------------------------------------------------------- /payments/templates/payments/callback.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Callback 4 | 5 | 6 | 7 |

Callback Messsage:


8 |

Checksum Verification: {{ message }}


9 | MID: {{ MID }}
10 | TXNID: {{ TXNID }}
11 | ORDERID: {{ ORDERID }}
12 | BANKTXNID: {{ BANKTXNID }}
13 | TXNAMOUNT: {{ TXNAMOUNT }}
14 | CURRENCY: {{ CURRENCY }}
15 |

STATUS: {{ STATUS }}


16 | RESPCODE: {{ RESPCODE }}
17 | RESPMSG: {{ RESPMSG }}
18 | TXNDATE: {{ TXNDATE }}
19 | GATEWAYNAME: {{ GATEWAYNAME }}
20 | BANKNAME: {{ BANKNAME }}
21 | BIN_NAME: {{ BIN_NAME }}
22 | PAYMENTMODE: {{ PAYMENTMODE }}
23 | CHECKSUMHASH: {{ CHECKSUMHASH }} 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /payments/templates/payments/redirect.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Merchant Check Out Page 4 | 5 | 6 |

Please do not refresh this page...

7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 |
21 | 24 |
25 | 26 | 27 | -------------------------------------------------------------------------------- /payments/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render 2 | from django.contrib.auth import authenticate, login as auth_login 3 | from django.views.decorators.csrf import csrf_exempt 4 | from django.conf import settings 5 | from .models import Transaction 6 | from .paytm import generate_checksum, verify_checksum 7 | 8 | 9 | def initiate_payment(request): 10 | if request.method == "GET": 11 | return render(request, 'payments/pay.html') 12 | try: 13 | username = request.POST['username'] 14 | password = request.POST['password'] 15 | amount = int(request.POST['amount']) 16 | user = authenticate(request, username=username, password=password) 17 | if user is None: 18 | raise ValueError 19 | auth_login(request=request, user=user) 20 | except: 21 | return render(request, 'payments/pay.html', context={'error': 'Wrong Accound Details or amount'}) 22 | 23 | transaction = Transaction.objects.create(made_by=user, amount=amount) 24 | transaction.save() 25 | merchant_key = settings.PAYTM_SECRET_KEY 26 | 27 | params = ( 28 | ('MID', settings.PAYTM_MERCHANT_ID), 29 | ('ORDER_ID', str(transaction.order_id)), 30 | ('CUST_ID', str(transaction.made_by.email)), 31 | ('TXN_AMOUNT', str(transaction.amount)), 32 | ('CHANNEL_ID', settings.PAYTM_CHANNEL_ID), 33 | ('WEBSITE', settings.PAYTM_WEBSITE), 34 | # ('EMAIL', request.user.email), 35 | # ('MOBILE_N0', '9911223388'), 36 | ('INDUSTRY_TYPE_ID', settings.PAYTM_INDUSTRY_TYPE_ID), 37 | ('CALLBACK_URL', 'http://127.0.0.1:8000/callback/'), 38 | # ('PAYMENT_MODE_ONLY', 'NO'), 39 | ) 40 | 41 | paytm_params = dict(params) 42 | checksum = generate_checksum(paytm_params, merchant_key) 43 | 44 | transaction.checksum = checksum 45 | transaction.save() 46 | 47 | paytm_params['CHECKSUMHASH'] = checksum 48 | print('SENT: ', checksum) 49 | return render(request, 'payments/redirect.html', context=paytm_params) 50 | 51 | 52 | @csrf_exempt 53 | def callback(request): 54 | if request.method == 'POST': 55 | paytm_checksum = '' 56 | print(request.body) 57 | print(request.POST) 58 | received_data = dict(request.POST) 59 | print(received_data) 60 | paytm_params = {} 61 | paytm_checksum = received_data['CHECKSUMHASH'][0] 62 | for key, value in received_data.items(): 63 | if key == 'CHECKSUMHASH': 64 | paytm_checksum = value[0] 65 | else: 66 | paytm_params[key] = str(value[0]) 67 | # Verify checksum 68 | is_valid_checksum = verify_checksum(paytm_params, settings.PAYTM_SECRET_KEY, str(paytm_checksum)) 69 | if is_valid_checksum: 70 | print("Checksum Matched") 71 | received_data['message'] = "Checksum Matched" 72 | else: 73 | print("Checksum Mismatched") 74 | received_data['message'] = "Checksum Mismatched" 75 | 76 | return render(request, 'payments/callback.html', context=received_data) 77 | 78 | 79 | 80 | 81 | -------------------------------------------------------------------------------- /pay2me/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for pay2me project. 3 | 4 | Generated by 'django-admin startproject' using Django 2.2.5. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.2/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/2.2/ref/settings/ 11 | """ 12 | 13 | import os 14 | 15 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 16 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = 's^2s%n2#d=bx5k)gbfityrum%_9-j43c!$3cx#g_)+oisotc#n' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | 'payments' 41 | ] 42 | 43 | MIDDLEWARE = [ 44 | 'django.middleware.security.SecurityMiddleware', 45 | 'django.contrib.sessions.middleware.SessionMiddleware', 46 | 'django.middleware.common.CommonMiddleware', 47 | 'django.middleware.csrf.CsrfViewMiddleware', 48 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 49 | 'django.contrib.messages.middleware.MessageMiddleware', 50 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 51 | ] 52 | 53 | ROOT_URLCONF = 'pay2me.urls' 54 | 55 | TEMPLATES = [ 56 | { 57 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 58 | 'DIRS': ['templates'], 59 | 'APP_DIRS': True, 60 | 'OPTIONS': { 61 | 'context_processors': [ 62 | 'django.template.context_processors.debug', 63 | 'django.template.context_processors.request', 64 | 'django.contrib.auth.context_processors.auth', 65 | 'django.contrib.messages.context_processors.messages', 66 | ], 67 | }, 68 | }, 69 | ] 70 | 71 | WSGI_APPLICATION = 'pay2me.wsgi.application' 72 | 73 | 74 | # Database 75 | # https://docs.djangoproject.com/en/2.2/ref/settings/#databases 76 | 77 | DATABASES = { 78 | 'default': { 79 | 'ENGINE': 'django.db.backends.sqlite3', 80 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 81 | } 82 | } 83 | 84 | 85 | # Password validation 86 | # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators 87 | 88 | AUTH_PASSWORD_VALIDATORS = [ 89 | { 90 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 91 | }, 92 | { 93 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 94 | }, 95 | { 96 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 97 | }, 98 | { 99 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 100 | }, 101 | ] 102 | 103 | 104 | # Internationalization 105 | # https://docs.djangoproject.com/en/2.2/topics/i18n/ 106 | 107 | LANGUAGE_CODE = 'en-us' 108 | 109 | TIME_ZONE = 'UTC' 110 | 111 | USE_I18N = True 112 | 113 | USE_L10N = True 114 | 115 | USE_TZ = True 116 | 117 | 118 | # Static files (CSS, JavaScript, Images) 119 | # https://docs.djangoproject.com/en/2.2/howto/static-files/ 120 | 121 | STATIC_URL = '/static/' 122 | 123 | PAYTM_MERCHANT_ID = 'AE567YGVB98YGHJI87YG' 124 | 125 | PAYTM_SECRET_KEY = 'f7cg897scsCSHScs' 126 | 127 | PAYTM_WEBSITE = 'WEBSTAGING' 128 | 129 | PAYTM_CHANNEL_ID = 'WEB' 130 | 131 | PAYTM_INDUSTRY_TYPE_ID = 'Retail' 132 | -------------------------------------------------------------------------------- /payments/paytm.py: -------------------------------------------------------------------------------- 1 | import base64 2 | import string 3 | import random 4 | import hashlib 5 | from Crypto.Cipher import AES 6 | 7 | 8 | IV = "@@@@&&&&####$$$$" 9 | BLOCK_SIZE = 16 10 | 11 | 12 | def generate_checksum(param_dict, merchant_key, salt=None): 13 | params_string = __get_param_string__(param_dict) 14 | salt = salt if salt else __id_generator__(4) 15 | final_string = '%s|%s' % (params_string, salt) 16 | 17 | hasher = hashlib.sha256(final_string.encode()) 18 | hash_string = hasher.hexdigest() 19 | 20 | hash_string += salt 21 | 22 | return __encode__(hash_string, IV, merchant_key) 23 | 24 | 25 | def generate_refund_checksum(param_dict, merchant_key, salt=None): 26 | for i in param_dict: 27 | if("|" in param_dict[i]): 28 | param_dict = {} 29 | exit() 30 | params_string = __get_param_string__(param_dict) 31 | salt = salt if salt else __id_generator__(4) 32 | final_string = '%s|%s' % (params_string, salt) 33 | 34 | hasher = hashlib.sha256(final_string.encode()) 35 | hash_string = hasher.hexdigest() 36 | 37 | hash_string += salt 38 | 39 | return __encode__(hash_string, IV, merchant_key) 40 | 41 | 42 | def generate_checksum_by_str(param_str, merchant_key, salt=None): 43 | params_string = param_str 44 | salt = salt if salt else __id_generator__(4) 45 | final_string = '%s|%s' % (params_string, salt) 46 | 47 | hasher = hashlib.sha256(final_string.encode()) 48 | hash_string = hasher.hexdigest() 49 | 50 | hash_string += salt 51 | 52 | return __encode__(hash_string, IV, merchant_key) 53 | 54 | 55 | def verify_checksum(param_dict, merchant_key, checksum): 56 | # Remove checksum 57 | if 'CHECKSUMHASH' in param_dict: 58 | param_dict.pop('CHECKSUMHASH') 59 | 60 | # Get salt 61 | paytm_hash = __decode__(checksum, IV, merchant_key) 62 | salt = paytm_hash[-4:] 63 | calculated_checksum = generate_checksum(param_dict, merchant_key, salt=salt) 64 | return calculated_checksum == checksum 65 | 66 | 67 | def verify_checksum_by_str(param_str, merchant_key, checksum): 68 | # Remove checksum 69 | #if 'CHECKSUMHASH' in param_dict: 70 | #param_dict.pop('CHECKSUMHASH') 71 | 72 | # Get salt 73 | paytm_hash = __decode__(checksum, IV, merchant_key) 74 | salt = paytm_hash[-4:] 75 | calculated_checksum = generate_checksum_by_str(param_str, merchant_key, salt=salt) 76 | return calculated_checksum == checksum 77 | 78 | 79 | def __id_generator__(size=6, chars=string.ascii_uppercase + string.digits + string.ascii_lowercase): 80 | return ''.join(random.choice(chars) for _ in range(size)) 81 | 82 | 83 | def __get_param_string__(params): 84 | params_string = [] 85 | for key in sorted(params.keys()): 86 | if "REFUND" in params[key] or "|" in params[key]: 87 | respons_dict = {} 88 | exit() 89 | value = params[key] 90 | params_string.append('' if value == 'null' else str(value)) 91 | return '|'.join(params_string) 92 | 93 | 94 | __pad__ = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * chr(BLOCK_SIZE - len(s) % BLOCK_SIZE) 95 | __unpad__ = lambda s: s[0:-ord(s[-1])] 96 | 97 | 98 | def __encode__(to_encode, iv, key): 99 | # Pad 100 | to_encode = __pad__(to_encode) 101 | # Encrypt 102 | c = AES.new(key.encode('utf-8'), AES.MODE_CBC, iv.encode('utf-8')) 103 | to_encode = c.encrypt(to_encode.encode('utf-8')) 104 | # Encode 105 | to_encode = base64.b64encode(to_encode) 106 | return to_encode.decode("UTF-8") 107 | 108 | 109 | def __decode__(to_decode, iv, key): 110 | # Decode 111 | to_decode = base64.b64decode(to_decode) 112 | # Decrypt 113 | c = AES.new(key.encode('utf-8'), AES.MODE_CBC, iv.encode('utf-8')) 114 | to_decode = c.decrypt(to_decode) 115 | if type(to_decode) == bytes: 116 | # convert bytes array to str. 117 | to_decode = to_decode.decode() 118 | # remove pad 119 | return __unpad__(to_decode) 120 | 121 | 122 | if __name__ == "__main__": 123 | params = { 124 | "MID": "mid", 125 | "ORDER_ID": "order_id", 126 | "CUST_ID": "cust_id", 127 | "TXN_AMOUNT": "1", 128 | "CHANNEL_ID": "WEB", 129 | "INDUSTRY_TYPE_ID": "Retail", 130 | "WEBSITE": "xxxxxxxxxxx" 131 | } 132 | 133 | print(verify_checksum( 134 | params, 'xxxxxxxxxxxxxxxx', 135 | "CD5ndX8VVjlzjWbbYoAtKQIlvtXPypQYOg0Fi2AUYKXZA5XSHiRF0FDj7vQu66S8MHx9NaDZ/uYm3WBOWHf+sDQAmTyxqUipA7i1nILlxrk=")) 136 | 137 | # print(generate_checksum(params, "xxxxxxxxxxxxxxxx")) --------------------------------------------------------------------------------