Paytm Payment Gateway Integration in PHP Step by Step

In this tutorial we explain how to integrate Paytm Payment Gateway into PHP. In today’s scenario, Paytm is the most popular and reliable mobile wallet system. According to a survey by Economic Time, Paytm has reached around 200 million registered users. Yes, that’s a very large number. Paytm payment accept only in India. Paytm payment does not accept International payment gateway.

Today many e-commerce websites or other services use Paytm payment gateways. It also reduces the risk of disclosing credit card or bank passwords. Send or receive payments easily from your mobile. So Paytm is undoubtedly a better online payment service for your website or mobile app. It’s best payment gateway for woo-commerce.

How to use Paytm Payment gateway in PHP

Let’s start the process of Paytm Payment Gateway Integration. It’s very easy to integrate in your application as compared to other payment gateways. Follow the below :

See also

Register for Paytm Account

Signup or Sign-in for a Paytm business Payment gateway account from here: https://business.paytm.com/

During registration or login process, you need to select the required options Paytm Payment Gateway for website or APP. Also provide a valid redirect URL where you want to redirect the user once payment has been successfully received. If you haven’t submitted your business records yet, it is very important that you do so.

Note:

They ask for some official information like business type, address, proof of verification, bank details etc. Although you can get Paytm sandbox credentials without completing this process. But for production you need to provide all the necessary information.

Download Official Paytm Payment Gateway PHP Kit On Git hub

Paytm Official has announced the source code of the library in all languages. Just download the Paytm Payment Gateway PHP Kit from GitHub.
Unzip the zip file, there is a Paytm Payment Gateway PHP Kit folder which contains all the necessary files. you need to copy and Paymt kit folder in document root of your server.

Generate your Unique keys & Configure Paytm Credential

After create Paymt account generate your Unique keys Test API like Test Merchant ID, Test Merchant Key. By default source code ready for testing mode. When you want to move to Production update the PAYTM_ENVIRONMENT value by PROD. Merchant Id and Merchant key set up your project path C:\xampp\htdocs\Project-Folder\PaytmKit\lib\config_paytm.php.

Paytm Payment Gateway Integration in PHP Step by Step

config_paytm.php

<?php
/*
*|======================================================================|
*|	PayTM Payment Gateway Integration Kit (Stack Version : 1.0.0.0)		|
*|	@Author : Chandan Sharma 											|
*|	@Email: <devchandansh@gmail.com>									|
*|	@Website: <www.chandansharma.co.in>									|
*|======================================================================|
*/
  
/*
- Use PAYTM_ENVIRONMENT as 'PROD' if you wanted to do transaction in production environment else 'TEST' for doing transaction in testing environment.
- Change the value of PAYTM_MERCHANT_KEY constant with details received from Paytm.
- Change the value of PAYTM_MERCHANT_MID constant with details received from Paytm.
- Change the value of PAYTM_MERCHANT_WEBSITE constant with details received from Paytm.
- Above details will be different for testing and production environment.
*/

// define('PAYTM_ENVIRONMENT', 'TEST'); // PROD
// define('PAYTM_MERCHANT_KEY', 'O0zUdIG%OQViK_'); //Change this constant's value with Merchant key received from Paytm.
// define('PAYTM_MERCHANT_MID', 'dZlzzF171371019'); //Change this constant's value with MID (Merchant ID) received from Paytm.
// define('PAYTM_MERCHANT_WEBSITE', 'WEBSTAGING'); //Change this constant's value with Website name received from Paytm.


//=================================================
//	For PayTM Settings::
//=================================================

$PAYTM_ENVIRONMENT = "PROD";	// For Production /LIVE
$PAYTM_ENVIRONMENT = "TEST";	// For Staging / TEST

if(!defined("PAYTM_ENVIRONMENT") ){
	define('PAYTM_ENVIRONMENT', $PAYTM_ENVIRONMENT); 
}

// For LIVE
if (PAYTM_ENVIRONMENT == 'PROD') {
	//===================================================
	//	For Production or LIVE Credentials
	//===================================================
	$PAYTM_STATUS_QUERY_NEW_URL='https://securegw.paytm.in/merchant-status/getTxnStatus';
	$PAYTM_TXN_URL='https://securegw.paytm.in/theia/processTransaction';

	//Change this constant's value with Merchant key received from Paytm.
	$PAYTM_MERCHANT_MID 		= "ENTER_YOUR_MERCHANT_ID";
	$PAYTM_MERCHANT_KEY 		= "ENTER_YOUR_MERCHANT_KEY";

	$PAYTM_CHANNEL_ID 	= "WEB";
	$PAYTM_INDUSTRY_TYPE_ID = "";
	$PAYTM_MERCHANT_WEBSITE = "";
	$PAYTM_CALLBACK_URL 	= "";
	
}else{
	//===================================================
	//	For Staging or TEST Credentials
	//===================================================
	$PAYTM_STATUS_QUERY_NEW_URL='https://securegw-stage.paytm.in/merchant-status/getTxnStatus';
	$PAYTM_TXN_URL='https://securegw-stage.paytm.in/theia/processTransaction';

	//Change this constant's value with Merchant key received from Paytm.
	$PAYTM_MERCHANT_MID 	= "Test Merchant ID";  // ENTER YOUR MERCHANT ID 
	$PAYTM_MERCHANT_KEY 	= "Test Merchant Key"; // ENTER YOUR MERCHANT Key

	$PAYTM_CHANNEL_ID 		= "Channel ID (For Website)"; // Channel Id 
	$PAYTM_INDUSTRY_TYPE_ID = "Industry Type"; // 
	$PAYTM_MERCHANT_WEBSITE = "Website Name"; // Website Name

	$PAYTM_CALLBACK_URL 	= "http://localhost/Paytm-payment-gateway-in-php/PaytmKit/pgResponse.php";
	
}

define('PAYTM_MERCHANT_KEY', $PAYTM_MERCHANT_KEY); 
define('PAYTM_MERCHANT_MID', $PAYTM_MERCHANT_MID);

define("PAYTM_MERCHANT_WEBSITE", $PAYTM_MERCHANT_WEBSITE);
define("PAYTM_CHANNEL_ID", $PAYTM_CHANNEL_ID);
define("PAYTM_INDUSTRY_TYPE_ID", $PAYTM_INDUSTRY_TYPE_ID);
define("PAYTM_CALLBACK_URL", $PAYTM_CALLBACK_URL);


define('PAYTM_REFUND_URL', '');
define('PAYTM_STATUS_QUERY_URL', $PAYTM_STATUS_QUERY_NEW_URL);
define('PAYTM_STATUS_QUERY_NEW_URL', $PAYTM_STATUS_QUERY_NEW_URL);
define('PAYTM_TXN_URL', $PAYTM_TXN_URL);

?>

Create Database and Table by SQL query

For example, we need to create database and table, so here I created webscodex database payment_txn table. payment_txn table holds the records which will be payment success or failed. You can simply create table as following SQL query.

-- Database: `webscodex`
-- --------------------------------------------------------
-- Table structure for table `payment_txn`
--

CREATE TABLE `payment_txn` (
  `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
  `order_id` varchar(100) NOT NULL,
  `amount` float(10,2) NOT NULL,
  `status` varchar(100) NOT NULL,
  `txns_id` varchar(100) NOT NULL,
  `payment_mode` varchar(100) NOT NULL,
  `currency` varchar(100) NOT NULL,
  `txns_date` datetime NOT NULL,
  `gateway_name` varchar(100) NOT NULL,
  `bank_name` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

Create Database Configuration File

In this step, we require to create database configuration file, here we will set database name, username and password. So let’s create config.php file on your root directory and put bellow code:

config.php

<?php
   // Database configuration    
   $hostname = "localhost"; 
   $username = "root"; 
   $password = ""; 
   $dbname   = "webscodex";
    
   // Create database connection 
   $con = mysqli_connect($hostname, $username, $password, $dbname);
    
   // Check connection 
   if (mysqli_connect_errno()) {
      echo "Failed to connect  to MySQL: " . mysqli_connect_error();
      exit();
   }
?>

Create HTML Payment Form

After configuring the credential, your code is ready to process. Now create an HTML form to make the online transactions. create checkout page to get customer and products details. When click on checkout button then redirect to Paytm payment page. insert payment details in payment transaction table.

index.php

<!DOCTYPE html>
<html lang="">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Paytm Payment Gateway Integration in PHP Step by Step</title>
        <!-- Bootstrap CSS -->
        <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
        <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
    </head>
    <body>
    <div class="container">
        <div class="py-5 text-center">
            <h2> Paytm Payment Gateway Integration Checkout Form</h2>
            <p class="lead">This Checkout page using Paytm Payment Gateway for Testing purpose </p>
        </div>
        <form action="http://localhost/Paytm-payment-gateway-in-php/PaytmKit/pgRedirect.php" method="POST">
            <div class="row">
                <div class="col-md-8 order-md-1">
                    <h4 class="mb-3">Billing address</h4>
                    <div class="card p-3">
                        <div class="row">
                            <div class="col-md-12 mb-3">
                                <label for="firstName">Full Name </label>
                                <input type="text" class="form-control" name="full_name" placeholder="Full Name" required="">
                            </div>
                        </div>
                        <div class="mb-3">
                            <label for="mobile">Mobile Number</label>
                            <div class="input-group">                              
                                <input type="text" class="form-control" name="mobile_number" placeholder="Mobile Number" required="">
                            </div>
                        </div>
                        <div class="mb-3">
                            <label for="email">Email <span class="text-muted">(Optional)</span></label>
                            <input type="email" class="form-control" name="email" placeholder="Email">
                        </div>
                        <div class="mb-3">
                            <label for="address">Flat, House no. Area, Street, Sector, Village</label>
                            <input type="text" class="form-control" name="address" required="">
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="city">Town/City</label>
                                <input type="text" class="form-control" placeholder="Town/City">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="pincode">Pincode</label>
                                <input type="text" class="form-control" name="pincode" placeholder="6 digits [0-9] Pin code" required="">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-4 order-md-2 mb-4">
                    <h4 class="d-flex justify-content-between align-items-center mb-3">
                        <span>Your cart</span>
                        <span class="badge badge-secondary badge-pill">3</span>
                    </h4>
                    <ul class="list-group mb-3 sticky-top">
                        <li class="list-group-item d-flex justify-content-between lh-condensed">
                            <div>
                                <h6 class="my-0">First Product</h6>
                                <small class="text-muted">Brief description</small>
                            </div>
                            <span class="text-muted">₹12,000</span>
                        </li>
                        <li class="list-group-item d-flex justify-content-between lh-condensed">
                            <div>
                                <h6 class="my-0">Second Product</h6>
                                <small class="text-muted">Brief description</small>
                            </div>
                            <span class="text-muted">₹8,000</span>
                        </li>
                        <li class="list-group-item d-flex justify-content-between lh-condensed">
                            <div>
                                <h6 class="my-0">Third Product</h6>
                                <small class="text-muted">Brief description</small>
                            </div>
                            <span class="text-muted">₹5,000</span>
                        </li>
                        <li class="list-group-item d-flex justify-content-between">
                            <span><strong> Order Total: </strong></span>
                            <input type="hidden" name="order_amount" value="25000" />
                            <strong>₹25,000</strong>
                        </li>
                    </ul>
                    <div class="card p-2">
                        <button class="btn btn-primary btn-block" type="submit" name="check_out">Continue to checkout</button>
                    </div>
                </div>
            </div>
        </form>
    </div>
    <!-- jQuery -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <!-- Bootstrap JavaScript -->
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script>
</body>
</html>

Checkout Page Output

Paytm Payment Gateway Integration in PHP Step by Step

Payment Page Redirect

Form action should be to this file pgRedirect.php inside PaytmKit folder. This file handle checksum and other require details and redirect to you Paytm payment page. After click on checkout button user can process the payment via the paytm wallet.

pgRedirect.php

<?php
header("Pragma: no-cache");
header("Cache-Control: no-cache");
header("Expires: 0");
// following files need to be included
require_once("./lib/config_paytm.php");
require_once("./lib/encdec_paytm.php");

$checkSum = "";
$paramList = array();

if (isset($_POST['check_out'])) {
   
	$ORDER_ID = "WC".rand(1111,9999); // Get customer order Id
	$CUST_ID = rand(1,9999); // Make dynamic customer Id
	$TXN_AMOUNT = $_POST["order_amount"]; // Get total order amount
	$MSISDN = $_POST["mobile_number"]; // Get total order amount
	$EMAIL = $_POST['email'];
	
	// Create an array having all required parameters for creating checksum.
	$paramList["ORDER_ID"] = $ORDER_ID;
	$paramList["CUST_ID"] = $CUST_ID;
	$paramList["TXN_AMOUNT"] = $TXN_AMOUNT;
	$paramList["INDUSTRY_TYPE_ID"] = PAYTM_INDUSTRY_TYPE_ID;
	$paramList["CHANNEL_ID"] = PAYTM_CHANNEL_ID;
	$paramList["MID"] = PAYTM_MERCHANT_MID;
	$paramList["WEBSITE"] = PAYTM_MERCHANT_WEBSITE;


	$paramList["CALLBACK_URL"] = PAYTM_CALLBACK_URL;
	$paramList["MSISDN"] = $MSISDN; //Mobile number of customer
	$paramList["EMAIL"] = $EMAIL; //Email ID of customer
	$paramList["VERIFIED_BY"] = "EMAIL"; //
	$paramList["IS_USER_VERIFIED"] = "YES"; //

}

//Here checksum string will return by getChecksumFromArray() function.
$checkSum = getChecksumFromArray($paramList,PAYTM_MERCHANT_KEY);

?>
<html>
<head>
<title>Merchant Check Out Page</title>
</head>
<body>
	<center><h1>Please do not refresh this page...</h1></center>
		<form method="post" action="<?php echo PAYTM_TXN_URL ?>" name="f1">
		<table border="1">
			<tbody>
			<?php
			foreach($paramList as $name => $value) {
				echo '<input type="hidden" name="' . $name .'" value="' . $value . '">';
			}
			?>
			<input type="hidden" name="CHECKSUMHASH" value="<?php echo $checkSum ?>">
			</tbody>
		</table>
		<script type="text/javascript">
			document.f1.submit();
		</script>
	</form>
</body>
</html>

Final Output

Paytm Payment Gateway Integration in PHP Step by Step

Payment Response and Insert In Payment_txn Table

After payment transaction success insert user payment records into the payment transaction table to store payment record.

pgResponse.php

<?php
header("Pragma: no-cache");
header("Cache-Control: no-cache");
header("Expires: 0");

// following files need to be included
require_once("./lib/config_paytm.php");
require_once("./lib/encdec_paytm.php");

$paytmChecksum = "";
$paramList = array();
$isValidChecksum = "FALSE";

$paramList = $_POST;
$paytmChecksum = isset($_POST["CHECKSUMHASH"]) ? $_POST["CHECKSUMHASH"] : ""; //Sent by Paytm pg

//Verify all parameters received from Paytm pg to your application. Like MID received from paytm pg is same as your application�s MID, TXN_AMOUNT and ORDER_ID are same as what was sent by you to Paytm PG for initiating transaction etc.
$isValidChecksum = verifychecksum_e($paramList, PAYTM_MERCHANT_KEY, $paytmChecksum); //will return TRUE or FALSE string.

if($isValidChecksum == "TRUE") {
	echo "<b>Checksum matched and following are the transaction details:</b>" . "<br/>";
	if ($_POST["STATUS"] == "TXN_SUCCESS") {
		echo "<b>Transaction status is success</b>" . "<br/>";
		//Process your transaction here as success transaction.
		//Verify amount & order id received from Payment gateway with your application's order id and amount.
	} else {
		echo "<b>Transaction status is failure</b>" . "<br/>";
	}

	/* Insert Payment transaction record in database  */
	
	require_once("../config.php");

	$orderId = $_POST['ORDERID'];
	$txnsId  = $_POST['TXNID'];
	$amount  = $_POST['TXNAMOUNT'];
	$paymentMode = $_POST['PAYMENTMODE'];
	$txnsDate = $_POST['TXNDATE'];
	$status = $_POST['STATUS'];
	$gatewayName = $_POST['GATEWAYNAME'];
	$bankName = $_POST['BANKNAME'];
	$currency = $_POST['CURRENCY'];
	
	$query  = "INSERT INTO payment_txn (order_id, amount, status, txns_id, payment_mode, currency, txns_date, gateway_name, bank_name) 
              VALUES ('$orderId', '$amount', '$status', '$txnsId', '$paymentMode','$currency', '$txnsDate', '$gatewayName', '$bankName')";
    
	mysqli_query($con, $query);

	/*  End  */

	// if (isset($_POST) && count($_POST)>0 )
	// { 
	// 	foreach($_POST as $paramName => $paramValue) {
	// 			echo "<br/>" . $paramName . " = " . $paramValue;
	// 	}
	// }
}
else {
	echo "<b>Checksum mismatched.</b>";
	//Process transaction as suspicious.
}
?>

For more information, visit Paytm official documentation and do changes as per your requirement. Using the above steps you can easily do the Paytm Payment Gateway Integration in PHP. We hope this tutorial helps you. If you want to better understanding for this project download the full source code click on below download button. Thanks

Paytm Payment Gateway Integration in PHP Step by Step

Frequently asked questions

How can I implement Paytm payment gateway in PHP?

You will have to first create an account with Paytm Payment Gateway. While creating your account, keep in mind to choose the option that requires a website or app for integrating Paytm Payment Gateway. The sign up process will also ask for a URL where you want your customers to be redirected after the payment.

What is payment integration API?

A payment API, also known as payment gateway API or payment processing API operates to integrate a payment solution with another, existing application, such as connecting a business’s checkout function to the payment system.

Which programming language is used in Paytm?

Gatsby is an open source static website generator based on React and GraphQL. JavaScript is a lightweight, object-oriented, cross-platform scripting language.

You can always support by sharing on social media or recommending my blog to your friends and colleagues. If you have any suggestions or problems about this tutorial, please comment on the form below.😊

Leave a Reply

Your email address will not be published. Required fields are marked *