Payment gateways are an essential part of e-commerce websites, enabling businesses to securely process online transactions. Paytm is one of the popular payment gateways in India, and integrating it into your Django web application is relatively straightforward. In this tutorial, we will walk you through the steps to integrate Paytm payment gateway into your Django app.
Prerequisites
Before we get started, make sure you have the following prerequisites:
- Django installed on your system.
- Paytm API credentials (MID, Key, Website, and Client ID), which you can obtain from your Paytm Dashboard.
- Basic knowledge of Django.
Step 1: Create a Django Project and App
First, create a new Django project and a new app within the project:
django-admin startproject myproject
cd myproject
python manage.py startapp payment_app
Step 2: Install Required Libraries
Install the necessary libraries for making HTTP requests and generating checksums:
pip install requests
pip install paytm-pg
pip install paytmchecksum
Step 3: Configure Paytm Credentials
In your project’s settings.py
file, configure your Paytm API credentials:
# paytm_integration/settings.py
PAYTM_MID = "YOUR_MID_HERE"
PAYTM_KEY = "YOUR_MERCHANT_KEY" # 16, 24, or 32 bytes AES key
PAYTM_WEBSITE = "YOUR_WEBSITE_NAME"
PAYTM_CLIENT_ID = "YOUR_CLIENT_ID_HERE"
PAYTM_CALLBACK_URL = "MERCANT_CALLBACK_URL"
Step 4: Create Payment Views
In your payment_app/views.py
file, create views for initiating payments, checking payment status, and handling payment responses. Replace the placeholder code with actual Paytm integration code:
# payment_app/views.py
import logging
import requests
import json
from django.conf import settings
from django.http import HttpResponse
from django.shortcuts import render
from paytmpg import EnumCurrency, EChannelId, UserSubWalletType
from paytmpg import ExtendInfo, ShippingInfo, GoodsInfo, UserInfo, PaymentMode, Money
from paytmpg import PaymentDetailsBuilder, PaymentStatusDetailBuilder
from paytmpg import RefundDetailBuilder, RefundStatusDetailBuilder
from paytmpg import MerchantProperty, LibraryConstants
from paytmpg import Payment, Refund
from paytmchecksum import PaytmChecksum
logger = logging.getLogger(__name__)
def initiate_payment(request):
# Your initialization code here
# Create a dictionary with payment parameters
paytmParams = {
"MID": settings.PAYTM_MID,
"ORDERID": "UNIQUE_ORDER_ID", # Replace with your unique order ID
"TXN_AMOUNT": "1.00", # Replace with the transaction amount
"CUST_ID": "CUSTOMER_ID", # Replace with the customer's ID
"MOBILE_NO": "CUSTOMER_MOBILE_NO",
"EMAIL": "CUSTOMER_EMAIL_ID",
"INDUSTRY_TYPE_ID": "Retail",
"WEBSITE": settings.PAYTM_WEBSITE,
"CHANNEL_ID": "WEB",
"CALLBACK_URL": settings.PAYTM_CALLBACK_URL,
}
# Generate the checksum using PaytmChecksum library
paytmChecksum = PaytmChecksum.generateSignature(paytmParams, settings.PAYTM_KEY)
# Add the checksum to the parameters
paytmParams["CHECKSUMHASH"] = paytmChecksum
# Redirect the user to the Paytm payment gateway
paytm_url = "https://securegw.paytm.in/theia/processTransaction"
response = requests.post(paytm_url, json=paytmParams)
response_dict = response.json()
return render(request, 'payment_app/payment_form.html', {'paytm_dict': response_dict})
def payment_status(request):
if request.method == 'POST':
# Get the payment status from Paytm using the provided SDK code
order_id = request.POST['ORDERID']
read_timeout = 30 * 1000
payment_status_detail = PaymentStatusDetailBuilder(order_id).set_read_timeout(read_timeout).build()
response = Payment.getPaymentStatus(payment_status_detail)
return render(request, 'payment_app/payment_status.html', {'payment_status': response})
return HttpResponse("Invalid Request Method")
def payment_response(request):
# Handle the payment response from Paytm here
# This view will be called by Paytm after payment is completed
# You can extract payment details from the request and update your database accordingly
# Be sure to validate the response for security
return HttpResponse("Payment Response Received")
Step 5: Create Payment Form and Templates
Create templates for displaying the payment form and payment status. Place these templates in a templates
folder within your app directory:
payment_form.html
for displaying the payment form.
<!-- payment_form.html -->
<!DOCTYPE html>
<html>
<head>
<title>Paytm Payment</title>
</head>
<body>
<h1>Paytm Payment Form</h1>
<form method="post" action="https://securegw.paytm.in/theia/processTransaction">
{% csrf_token %}
<input type="hidden" name="MID" value="{{ paytm_dict.MID }}">
<input type="hidden" name="ORDER_ID" value="{{ paytm_dict.ORDER_ID }}">
<input type="hidden" name="CUST_ID" value="{{ paytm_dict.CUST_ID }}">
<input type="hidden" name="TXN_AMOUNT" value="{{ paytm_dict.TXN_AMOUNT }}">
<input type="hidden" name="CHANNEL_ID" value="{{ paytm_dict.CHANNEL_ID }}">
<input type="hidden" name="INDUSTRY_TYPE_ID" value="{{ paytm_dict.INDUSTRY_TYPE_ID }}">
<input type="hidden" name="WEBSITE" value="{{ paytm_dict.WEBSITE }}">
<input type="hidden" name="EMAIL" value="{{ paytm_dict.EMAIL }}">
<input type="hidden" name="MOBILE_NO" value="{{ paytm_dict.MOBILE_NO }}">
<input type="hidden" name="CALLBACK_URL" value="{{ paytm_dict.CALLBACK_URL }}">
<input type="hidden" name="CHECKSUMHASH" value="{{ paytm_dict.CHECKSUMHASH }}">
<button type="submit">Pay Now</button>
</form>
</body>
</html>
payment_status.html
for showing the payment status.
<!-- payment_status.html -->
<!DOCTYPE html>
<html>
<head>
<title>Payment Status</title>
</head>
<body>
<h1>Payment Status</h1>
<p>Status: {{ payment_status.STATUS }}</p>
<p>Transaction ID: {{ payment_status.TXNID }}</p>
<p>Amount: {{ payment_status.TXNAMOUNT }}</p>
</body>
</html>
Step 6: Define URL Patterns
In your app’s urls.py
file, define URL patterns for the payment views:
# payment_app/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('initiate-payment/', views.initiate_payment, name='initiate_payment'),
path('payment-status/', views.payment_status, name='payment_status'),
path('payment-response/', views.payment_response, name='payment_response'),
]
Include these app-specific URL patterns in your project’s urls.py
:
# paytm_integration/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('payment/', include('payment_app.urls')),
]
Step 7: Run the Development Server
Run the Django development server:
python manage.py runserver
You can now access the payment initiation form at http://localhost:8000/payment/initiate-payment/
. After the payment, Paytm will redirect the user to your payment_response
view, where you can handle the payment response.
That’s it! You’ve successfully integrated the Paytm payment gateway into your Django app, allowing you to securely process online payments.
Find this project on Github.
Read our blog on How to Protect Sensitive Data in Python Projects like Django and Flask
As you are using sensitive data in your project, like api keys and secrets. You need protect it.