in this article, we will learn how to integrate the Paytm payment gateway.


We will make payment then upgrade the user membership to update the user table in the database. simply this is all about upgrading the user membership system using the Paytm payment gateway.


before jump into code we need a database signup table & membership table, use the following code to create tables


Database tables structure

use the following code to create tables

-- phpMyAdmin SQL Dump
-- version 5.0.4
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Jan 25, 2021 at 06:10 PM
-- Server version: 10.4.17-MariaDB
-- PHP Version: 7.3.25

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `paytm`
--

-- --------------------------------------------------------

--
-- Table structure for table `membership`
--

CREATE TABLE `membership` (
  `id` int(11) NOT NULL,
  `username` varchar(100) NOT NULL,
  `tr_id` varchar(300) NOT NULL,
  `amount` varchar(1000) NOT NULL,
  `state` varchar(300) NOT NULL,
  `tra_date` varchar(100) NOT NULL,
  `payment_email` text NOT NULL,
  `paypal_tra_Id` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `membership`
--

INSERT INTO `membership` (`id`, `username`, `tr_id`, `amount`, `state`, `tra_date`, `payment_email`, `paypal_tra_Id`) VALUES
(38, 'stint', '20190217111212800110168970757577571', '150 INR', 'TXN_SUCCESS', '2019/02/17 12:24:41', '', '');

-- --------------------------------------------------------

--
-- Table structure for table `signup`
--

CREATE TABLE `signup` (
  `id` int(11) NOT NULL,
  `username` varchar(100) NOT NULL,
  `email` varchar(120) NOT NULL,
  `password` varchar(400) NOT NULL,
  `ip` varchar(200) NOT NULL,
  `member_since` varchar(100) NOT NULL,
  `membership` int(11) NOT NULL,
  `dom` varchar(100) NOT NULL,
  `city` varchar(100) NOT NULL,
  `courtry` varchar(100) NOT NULL,
  `activate` tinyint(4) NOT NULL,
  `first_name` varchar(200) NOT NULL,
  `last_name` varchar(200) NOT NULL,
  `activation_has` varchar(300) NOT NULL,
  `activation_time` varchar(200) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `signup`
--

INSERT INTO `signup` (`id`, `username`, `email`, `password`, `ip`, `member_since`, `membership`, `dom`, `city`, `courtry`, `activate`, `first_name`, `last_name`, `activation_has`, `activation_time`) VALUES
(30, 'stint', 'gajanand.kgn@rediffmail.com', 'testpassword', '113.193.102.61', '2017/09/03 14:50:35', 1, '', 'Indore', 'India', 1, 'Gajanand', 'Rathor', 'null', '');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `membership`
--
ALTER TABLE `membership`
  ADD PRIMARY KEY (`id`);

--
-- Indexes for table `signup`
--
ALTER TABLE `signup`
  ADD PRIMARY KEY (`id`);
ALTER TABLE `signup` ADD FULLTEXT KEY `ft_signup` (`username`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `membership`
--
ALTER TABLE `membership`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8952;

--
-- AUTO_INCREMENT for table `signup`
--
ALTER TABLE `signup`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=45;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;



Create Controller

Create controller file Paytm.php and put the following code

application/controllers/
┣ Paytm.php

<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Paytm extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('PaytmModel', 'Paytm');
        $this->load->library('session');

        /* set the tempory session data
         *  you can remove if you have login and 
         * signup form in your project
         */
        $this->session->set_userdata('username', 'stint');
        $this->session->set_userdata('logged_in', TRUE);
    }

    public function index() {
        $this->load->view("header");
        $this->load->view("upgrade");
        $this->load->view("footer");
    }

    public function pgRedirect() {
        if ($this->session->userdata('username') != NULL && $this->session->userdata('logged_in') == TRUE) {
            $this->load->view("PaytmKit/pgRedirect");
        }
    }

    public function pgResponse() {
        if ($this->session->userdata('username') != NULL && $this->session->userdata('logged_in') == TRUE) {
            $data = array(
                "Paytm" => $this->Paytm
            );


            $this->load->view("PaytmKit/pgResponse", $data);
        }
    }

}



Create model

Create model file PaytmModel.php and put the following code


application/models/
┗ PaytmModel.php

<?php

defined('BASEPATH') OR exit('No direct script access allowed');


class PaytmModel extends CI_Model {

    public function __construct() {
        parent::__construct();
    }

    public function pay($username, $tid, $amount, $state) {
        $date = new DateTime();
        if ($this->check_txt_id($tid) == 0) {
            $tdate = $this->member_since = $date->format('Y/m/d H:i:s');
            $this->db->query("INSERT INTO `membership`(`username`, `tr_id`, `amount`, `state`, `tra_date` ) VALUES( '$username', '$tid', '$amount', '$state', '$tdate' )");
            return TRUE;
        }else{
            header("Location:". base_url().'ln');
        }
    }

    public function check_txt_id($tid) {
        $query = $this->db->query("SELECT COUNT(id) as total FROM membership WHERE tr_id = '$tid'");
        foreach ($query->result_array() as $total) {
            return $total['total'];
        }
    }

    public function update_membership($username) {
        $this->db->query("UPDATE signup SET membership = '1' WHERE username = '$username'");
    }

}



Create views

We need some view files for making payment like a payment success payment failed and upgrade membership page and also we need Paytm payment kit for the setting of your payment integration API.


views/
┣ PaytmKit/
┃ ┣ lib/
┃ ┃ ┣ config_paytm.php
┃ ┃ ┗ encdec_paytm.php
┃ ┣ pgRedirect.php
┃ ┣ pgResponse.php
┃ ┣ TxnStatus.php
┃ ┗ TxnTest.php
┣ footer.php
┣ header.php
┣ payment-fail.php
┣ payment-success.php
┣ upgrade.php


header.php

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="<?php if (isset($description)): ?><?php echo $description; ?><?php endif; ?>">
        <meta name="keywords" content="<?php if (isset($keywords)): ?><?php echo $keywords; ?><?php endif; ?>">

        <link rel="shortcut icon" type="image/ico" href="<?php echo base_url() ?>vendor/tr/logos/favicon.ico"/>


        <link rel='canonical' href="<?php echo base_url(uri_string()); ?>"/>
        <link href="https://fonts.googleapis.com/css?family=Fira+Sans:400,700&display=swap" rel="stylesheet">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css?ver=0.23">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css?ver=0.23">

        <title> <?php if (isset($title)): ?><?php echo $title; ?><?php else: ?>Signin<?php endif; ?></title>
        <script>var base_url = "<?php echo base_url(); ?>";</script>
        <style>
            body{
                background: #eacece;
            }

            .myform-container{
                background: #fff;
                padding: 30px;
                margin: 20px 0;
            }

            .myform-container .error{
                border: 1px solid red;
            }

            .myform-container h1{
                font-size: 1.5em;
            }

            .myform-container h3{
                font-size: 1.5em;
            }

            .myform-container ul li{
                margin: 15px 0;
            }

            .get-start:hover{
                color: #eacece;
            }

            .get-start{
                background: #253c50;
                border: none;
                color: #fff;
                border-radius: 0;
                padding: 10px 20px;
            }

            .contact-info{
                margin: 15% 0;
            }

            .mycontactuspage{
                margin: 30px 0;
            }

            .form-errors{
                color: red;
            }

            label {
                font-weight: 400;
            }

            footer{
                text-align: center;
                padding: 30px;
            }

        </style>
    </head>
    <body>

footer.php

<footer>© <?php echo date('Y'); ?> Rathorji.</footer>

<!--js scripts -->
<script src='https://code.jquery.com/jquery-2.2.4.min.js'></script>
<script src='https://www.google.com/recaptcha/api.js'></script>
<script src='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js'></script>

</body>
</html>

upgrade.php

<div class="container">
    <div class="row">
        <div class="col-md-3"></div>
        <div class="col-md-6">
            <!-- PayTm-->

            <h3><?php echo PAYTM_AMOUNT; ?> INR /Month</h3>
            <p>Upgrade your membership</p>

            <form method="post" action="<?php echo base_url(); ?>payTM">
                <input  type="hidden" id="ORDER_ID" tabindex="1" maxlength="20" size="20" name="ORDER_ID" autocomplete="off" value="<?php echo "ORDS" . rand(10000, 99999999) ?>">
                <input type="hidden" id="CUST_ID" tabindex="2" maxlength="12" size="12" name="CUST_ID" autocomplete="off" value="CUST001">
                <input type="hidden" id="INDUSTRY_TYPE_ID" tabindex="4" maxlength="12" size="12" name="INDUSTRY_TYPE_ID" autocomplete="off" value="Retail">
                <input type="hidden" id="CHANNEL_ID" tabindex="4" maxlength="12" size="12" name="CHANNEL_ID" autocomplete="off" value="WEB">
                <input type="hidden" title="TXN_AMOUNT" tabindex="240" type="text" name="TXN_AMOUNT" value="<?php echo PAYTM_AMOUNT; ?>">
                <button value="CheckOut" type="submit" onclick="" class="get-start" style="width: 100%;"> Pay with PayTM </button>
            </form>
        </div>
          <div class="col-md-3"></div>
    </div>
</div>

payment-success.php

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Payment done</title>
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <link href="https://fonts.googleapis.com/css?family=Roboto:400,700,900" rel="stylesheet">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
        
    </head>
    <body>


        <div class="container">
            <div class="col-md-2"></div>
            <div class="col-md-8">
                <div id="thanks-containt">

                    <h1 class="text-center email-icon"><i class="fa fa-check" aria-hidden="true"></i></h1>

                    <h1>Hello, <?php echo $this->session->userdata('username'); ?></h1>
                    <p>Payment successfully done, your transaction id is <?php
                        if (isset($txnid)) {
                            echo $txnid;
                        }
                        ?></p>


                    <h2>Having problems or questions?</h2>
                    <p>If you don’t know how to proceed please don’t hesitate to  <a href="<?php echo base_url() ?>contact-us">contact our support team</a></p>


                    <p class="text-center" style="margin-top: 25px;">
                        <a style="border: 1px solid #fff;padding: 5px; text-decoration: none;"class="btn my-btn" href="<?php echo base_url(); ?>ln" role="button">Begin Lesson</a>
                    </p>
                    <div class="clearfix"></div>
                </div>

                <div class="social-container">
                  

                    <ul class="share-social text-center">
                        <li>
                            <a href=""><i id="social-fb" class="fa fa-facebook fa-2x social"></i></a>
                        </li>
                        <li><a href=""><i id="social-tw" class="fa fa-twitter fa-2x social"></i></a></li>
                        <li><a href=""><i id="social-gp" class="fa fa-google fa-2x social"></i></a></li>
                        <li><a href="<?php echo base_url(); ?>contact-us"><i id="social-gp" class="fa fa-envelope fa-2x social"></i></a></li>
                    </ul>
                </div>
            </div>
            <div class="col-md-4"></div>
        </div>

        <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

    </body>
</html>

payment-fail.php


<div class="container">
    <div class="col-md-4"></div>
    <div class="col-md-4">
        <div class="myform-container">
            <div class="logo-container">
                <a href="<?php echo base_url(); ?>">
                    <img src="<?php echo base_url(); ?>vendor/v2/images/logo.png" alt="Rathorji" class="img-responsive" />
                </a>
            </div><br>
            <h1>Payment failed</h1>
            <p><a href="<?php echo base_url() ?>upgrade">Please try again</a></p>
            
            <h3>Having problems?</h3>
            <p>If you don’t know how to proceed please contact to our support team.</p><br>
            <p>
                <a href="<?php echo base_url() ?>contact-us" class="get-start btn" style="width: 100%;">Contact  Now</a>
            </p>
            <div class="clearfix"></div>
        </div>
    </div>
    <div class="col-md-4"></div>
</div>


PaytmKit/ pgRedirect.php

<?php


//check valid amount
if($_POST["TXN_AMOUNT"] != PAYTM_AMOUNT){
    
    //redirect back to upgrade page
    header("Location:".base_url().'/upgrade');
    exit;
}


header("Pragma: no-cache");
header("Cache-Control: no-cache");
header("Expires: 0");
// following files need to be included



$this->load->view('PaytmKit/lib/config_paytm');
$this->load->view('PaytmKit/lib/encdec_paytm');


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

$ORDER_ID = $_POST["ORDER_ID"];
$CUST_ID = $_POST["CUST_ID"];
$INDUSTRY_TYPE_ID = $_POST["INDUSTRY_TYPE_ID"];
$CHANNEL_ID = $_POST["CHANNEL_ID"];
$TXN_AMOUNT = $_POST["TXN_AMOUNT"];

// Create an array having all required parameters for creating checksum.
$paramList["MID"] = PAYTM_MERCHANT_MID;
$paramList["ORDER_ID"] = $ORDER_ID;
$paramList["CUST_ID"] = $CUST_ID;
$paramList["INDUSTRY_TYPE_ID"] = $INDUSTRY_TYPE_ID;
$paramList["CHANNEL_ID"] = $CHANNEL_ID;
$paramList["TXN_AMOUNT"] = $TXN_AMOUNT;
$paramList["WEBSITE"] = PAYTM_MERCHANT_WEBSITE;


//callback URL after cancel or after complete payment 
$paramList["CALLBACK_URL"] = base_url()."payTMRes";


/*
$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>

PaytmKit/ pgResponse.php

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



// following files need to be included
$this->load->view('PaytmKit/lib/config_paytm');
$this->load->view('PaytmKit/lib/encdec_paytm');

$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.
        $this->load->view('header');
        ?>




        <div class="container">
            <div class="col-md-4"></div>
            <div class="col-md-4">
                <div class="myform-container">

                    <div class="logo-container">
                        <a href="<?php echo base_url(); ?>">
                            <img src="<?php echo base_url(); ?>vendor/images/logo.png" alt="Rathorji" class="img-responsive" />
                        </a>
                    </div><br>

                    <h1>Hello <?php echo $this->session->userdata('username'); ?>,</h1>
                    <p>Payment successfully done, your transaction id is 
                        <?php echo $_POST["TXNID"]; ?>
                        <?php
                        $username = $this->session->userdata('username');
                        $Paytm->update_membership($username);
                        $tid = $_POST["TXNID"];
                        $Paytm->pay($username, $tid, "600", "TXN_SUCCESS");
                        ?>
                    </p>


                    <p class="text-center" style="margin-top: 25px;">
                        <a style="width: 100%" class="btn my-btn get-start" href="<?php echo base_url(); ?>" role="button">Jump into code</a>
                    </p>
                    <div class="clearfix"></div>
                </div>


            </div>
            <div class="col-md-4"></div>
        </div>



        <?php
        $this->load->view('footer');
    } else {
        $this->load->view('header');
        $this->load->view('payment-fail');
        $this->load->view('footer');
        // echo "<b>Transaction status is failure</b>" . "<br/>";
    }

    if (isset($_POST) && count($_POST) > 0) {
        foreach ($_POST as $paramName => $paramValue) {
            // echo "<br/>" . $paramName . " = " . $paramValue;

            /*
             * Checksum matched and following are the transaction details:
              Transaction status is success

              ORDERID = ORDS66131927
              MID = qwMCfj37320568057457
              TXNID = 20190216111212800110168599657504509
              TXNAMOUNT = 1.00
              PAYMENTMODE = PPI
              CURRENCY = INR
              TXNDATE = 2019-02-16 11:20:30.0
              STATUS = TXN_SUCCESS
              RESPCODE = 01
              RESPMSG = Txn Success
              GATEWAYNAME = WALLET
              BANKTXNID = 66998115273
              BANKNAME = WALLET
              CHECKSUMHASH = PhCW9y5OwBP9NpeXZGXkRlEJouQCGDmUK/wIF+eLVhTkLu25tIT3+7/lVa4GvnuphjzxWOU57+ZWpIKFgr1rHVyK1z4eWVbTE7Dn5AfVPVw=
             */
        }
    }
} else {
    echo "<b>Checksum mismatched.</b>";
    //Process transaction as suspicious.
}
?>

PaytmKit/ TxnStatus.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");

	$ORDER_ID = "";
	$requestParamList = array();
	$responseParamList = array();

	if (isset($_POST["ORDER_ID"]) && $_POST["ORDER_ID"] != "") {

		// In Test Page, we are taking parameters from POST request. In actual implementation these can be collected from session or DB. 
		$ORDER_ID = $_POST["ORDER_ID"];

		// Create an array having all required parameters for status query.
		$requestParamList = array("MID" => PAYTM_MERCHANT_MID , "ORDERID" => $ORDER_ID);  
		
		$StatusCheckSum = getChecksumFromArray($requestParamList,PAYTM_MERCHANT_KEY);
		
		$requestParamList['CHECKSUMHASH'] = $StatusCheckSum;

		// Call the PG's getTxnStatusNew() function for verifying the transaction status.
		$responseParamList = getTxnStatusNew($requestParamList);
	}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Transaction status query</title>
<meta name="GENERATOR" content="Evrsoft First Page">
</head>
<body>
	<h2>Transaction status query</h2>
	<form method="post" action="">
		<table border="1">
			<tbody>
				<tr>
					<td><label>ORDER_ID::*</label></td>
					<td><input id="ORDER_ID" tabindex="1" maxlength="20" size="20" name="ORDER_ID" autocomplete="off" value="<?php echo $ORDER_ID ?>">
					</td>
				</tr>
				<tr>
					<td></td>
					<td><input value="Status Query" type="submit"	onclick=""></td>
				</tr>
			</tbody>
		</table>
		<br/></br/>
		<?php
		if (isset($responseParamList) && count($responseParamList)>0 )
		{ 
		?>
		<h2>Response of status query:</h2>
		<table style="border: 1px solid nopadding" border="0">
			<tbody>
				<?php
					foreach($responseParamList as $paramName => $paramValue) {
				?>
				<tr >
					<td style="border: 1px solid"><label><?php echo $paramName?></label></td>
					<td style="border: 1px solid"><?php echo $paramValue?></td>
				</tr>
				<?php
					}
				?>
			</tbody>
		</table>
		<?php
		}
		?>
	</form>
</body>
</html>

PaytmKit/ TxnTest.php

<?php
header("Pragma: no-cache");
header("Cache-Control: no-cache");
header("Expires: 0");
?>
<!DOCTYPE html>
<html>
    <head>
        <title>Merchant Check Out Page</title>
        <meta name="GENERATOR" content="Evrsoft First Page">
    </head>
    <body>
        <h1>Merchant Check Out Page</h1>
        <pre>
        </pre>
    
    </body>
</html>


PaytmKit/lib/ config_paytm.php

you can replace PAYTM_MERCHANT_KEY, PAYTM_MERCHANT_MID and PAYTM_MERCHANT_WEBSITE which is provided by Paytm

<?php
/*
- 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', 'PROD'); // TEST
define('PAYTM_MERCHANT_KEY', '@TFfnNQEO'); //Change this constant's value with Merchant key received from Paytm.
define('PAYTM_MERCHANT_MID', 'qwMCfj3732'); //Change this constant's value with MID (Merchant ID) received from Paytm.
define('PAYTM_MERCHANT_WEBSITE', 'DEFAULT'); //Change this constant's value with Website name received from Paytm.

$PAYTM_STATUS_QUERY_NEW_URL='https://securegw-stage.paytm.in/merchant-status/getTxnStatus';
$PAYTM_TXN_URL='https://securegw-stage.paytm.in/theia/processTransaction';
if (PAYTM_ENVIRONMENT == 'PROD') {
	$PAYTM_STATUS_QUERY_NEW_URL='https://securegw.paytm.in/merchant-status/getTxnStatus';
	$PAYTM_TXN_URL='https://securegw.paytm.in/theia/processTransaction';
}

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);



PaytmKit/lib/ config_paytm.php

<?php

function encrypt_e($input, $ky) {
	$key   = html_entity_decode($ky);
	$iv = "@@@@&&&&####$$$$";
	$data = openssl_encrypt ( $input , "AES-128-CBC" , $key, 0, $iv );
	return $data;
}

function decrypt_e($crypt, $ky) {
	$key   = html_entity_decode($ky);
	$iv = "@@@@&&&&####$$$$";
	$data = openssl_decrypt ( $crypt , "AES-128-CBC" , $key, 0, $iv );
	return $data;
}

function generateSalt_e($length) {
	$random = "";
	srand((double) microtime() * 1000000);

	$data = "AbcDE123IJKLMN67QRSTUVWXYZ";
	$data .= "aBCdefghijklmn123opq45rs67tuv89wxyz";
	$data .= "0FGH45OP89";

	for ($i = 0; $i < $length; $i++) {
		$random .= substr($data, (rand() % (strlen($data))), 1);
	}

	return $random;
}

function checkString_e($value) {
	if ($value == 'null')
		$value = '';
	return $value;
}

function getChecksumFromArray($arrayList, $key, $sort=1) {
	if ($sort != 0) {
		ksort($arrayList);
	}
	$str = getArray2Str($arrayList);
	$salt = generateSalt_e(4);
	$finalString = $str . "|" . $salt;
	$hash = hash("sha256", $finalString);
	$hashString = $hash . $salt;
	$checksum = encrypt_e($hashString, $key);
	return $checksum;
}
function getChecksumFromString($str, $key) {
	
	$salt = generateSalt_e(4);
	$finalString = $str . "|" . $salt;
	$hash = hash("sha256", $finalString);
	$hashString = $hash . $salt;
	$checksum = encrypt_e($hashString, $key);
	return $checksum;
}

function verifychecksum_e($arrayList, $key, $checksumvalue) {
	$arrayList = removeCheckSumParam($arrayList);
	ksort($arrayList);
	$str = getArray2StrForVerify($arrayList);
	$paytm_hash = decrypt_e($checksumvalue, $key);
	$salt = substr($paytm_hash, -4);

	$finalString = $str . "|" . $salt;

	$website_hash = hash("sha256", $finalString);
	$website_hash .= $salt;

	$validFlag = "FALSE";
	if ($website_hash == $paytm_hash) {
		$validFlag = "TRUE";
	} else {
		$validFlag = "FALSE";
	}
	return $validFlag;
}

function verifychecksum_eFromStr($str, $key, $checksumvalue) {
	$paytm_hash = decrypt_e($checksumvalue, $key);
	$salt = substr($paytm_hash, -4);

	$finalString = $str . "|" . $salt;

	$website_hash = hash("sha256", $finalString);
	$website_hash .= $salt;

	$validFlag = "FALSE";
	if ($website_hash == $paytm_hash) {
		$validFlag = "TRUE";
	} else {
		$validFlag = "FALSE";
	}
	return $validFlag;
}

function getArray2Str($arrayList) {
	$findme   = 'REFUND';
	$findmepipe = '|';
	$paramStr = "";
	$flag = 1;	
	foreach ($arrayList as $key => $value) {
		$pos = strpos($value, $findme);
		$pospipe = strpos($value, $findmepipe);
		if ($pos !== false || $pospipe !== false) 
		{
			continue;
		}
		
		if ($flag) {
			$paramStr .= checkString_e($value);
			$flag = 0;
		} else {
			$paramStr .= "|" . checkString_e($value);
		}
	}
	return $paramStr;
}

function getArray2StrForVerify($arrayList) {
	$paramStr = "";
	$flag = 1;
	foreach ($arrayList as $key => $value) {
		if ($flag) {
			$paramStr .= checkString_e($value);
			$flag = 0;
		} else {
			$paramStr .= "|" . checkString_e($value);
		}
	}
	return $paramStr;
}

function redirect2PG($paramList, $key) {
	$hashString = getchecksumFromArray($paramList);
	$checksum = encrypt_e($hashString, $key);
}

function removeCheckSumParam($arrayList) {
	if (isset($arrayList["CHECKSUMHASH"])) {
		unset($arrayList["CHECKSUMHASH"]);
	}
	return $arrayList;
}

function getTxnStatus($requestParamList) {
	return callAPI(PAYTM_STATUS_QUERY_URL, $requestParamList);
}

function getTxnStatusNew($requestParamList) {
	return callNewAPI(PAYTM_STATUS_QUERY_NEW_URL, $requestParamList);
}

function initiateTxnRefund($requestParamList) {
	$CHECKSUM = getRefundChecksumFromArray($requestParamList,PAYTM_MERCHANT_KEY,0);
	$requestParamList["CHECKSUM"] = $CHECKSUM;
	return callAPI(PAYTM_REFUND_URL, $requestParamList);
}

function callAPI($apiURL, $requestParamList) {
	$jsonResponse = "";
	$responseParamList = array();
	$JsonData =json_encode($requestParamList);
	$postData = 'JsonData='.urlencode($JsonData);
	$ch = curl_init($apiURL);
	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
	curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);                                                                  
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
	curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
	curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
	curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                         
	'Content-Type: application/json', 
	'Content-Length: ' . strlen($postData))                                                                       
	);  
	$jsonResponse = curl_exec($ch);   
	$responseParamList = json_decode($jsonResponse,true);
	return $responseParamList;
}

function callNewAPI($apiURL, $requestParamList) {
	$jsonResponse = "";
	$responseParamList = array();
	$JsonData =json_encode($requestParamList);
	$postData = 'JsonData='.urlencode($JsonData);
	$ch = curl_init($apiURL);
	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
	curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);                                                                  
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
	curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
	curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
	curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                         
	'Content-Type: application/json', 
	'Content-Length: ' . strlen($postData))                                                                       
	);  
	$jsonResponse = curl_exec($ch);   
	$responseParamList = json_decode($jsonResponse,true);
	return $responseParamList;
}
function getRefundChecksumFromArray($arrayList, $key, $sort=1) {
	if ($sort != 0) {
		ksort($arrayList);
	}
	$str = getRefundArray2Str($arrayList);
	$salt = generateSalt_e(4);
	$finalString = $str . "|" . $salt;
	$hash = hash("sha256", $finalString);
	$hashString = $hash . $salt;
	$checksum = encrypt_e($hashString, $key);
	return $checksum;
}
function getRefundArray2Str($arrayList) {	
	$findmepipe = '|';
	$paramStr = "";
	$flag = 1;	
	foreach ($arrayList as $key => $value) {		
		$pospipe = strpos($value, $findmepipe);
		if ($pospipe !== false) 
		{
			continue;
		}
		
		if ($flag) {
			$paramStr .= checkString_e($value);
			$flag = 0;
		} else {
			$paramStr .= "|" . checkString_e($value);
		}
	}
	return $paramStr;
}
function callRefundAPI($refundApiURL, $requestParamList) {
	$jsonResponse = "";
	$responseParamList = array();
	$JsonData =json_encode($requestParamList);
	$postData = 'JsonData='.urlencode($JsonData);
	$ch = curl_init($apiURL);	
	curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
	curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
	curl_setopt($ch, CURLOPT_URL, $refundApiURL);
	curl_setopt($ch, CURLOPT_POST, true);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);  
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
	$headers = array();
	$headers[] = 'Content-Type: application/json';
	curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);  
	$jsonResponse = curl_exec($ch);   
	$responseParamList = json_decode($jsonResponse,true);
	return $responseParamList;
}



Important for security 

add price amount so people can not change price amount application/config/constants.php

//Custom defines
define('PAYTM_AMOUNT', 1);

Output:



it will redicrt you payment page







Are you facing problems in understanding this article?
You can watch the video. Watch it now