Course Content
Introduction to CodeIgniter
CodeIgniter is a powerful PHP framework built for developers who need a simple and elegant toolkit to create full-featured web applications.
0/3
MVC (Model-View-Controller)
MVC stands for Model-View-Controller. MVC is an application design model consisting of three interconnected parts. They include the model (data), the view (user interface), and the controller (processes that handle input).
0/6
Sessions
The Session class allows you to maintain a user’s "state" and track their activity while they browse your site.
0/1
URI Routing
There is a one-to-one relationship between a URL string and its corresponding controller class/method. The segments in a URI normally follow this pattern:
0/1
Forms and Input
Forms provide a way for users to interact with the application and submit data.
0/1
Composer
Composer is dependency manager in PHP. it allows you to declare the libraries your project depends on and it will manage (install/update) them for you.
0/1
Security
You can enable CSRF protection by modifying your application/config/config.php file
0/1
Working with Database
Like any other framework, we need to interact with the database very often and CodeIgniter makes this job easy for us. It provides a rich set of functionalities to interact with the database.
0/5
DataTable
DataTables is a table enhancing plug-in for the jQuery Javascript library that helps in adding sorting, paging, and filtering abilities to plain HTML tables with minimal effort. The main goal is to enhance the accessibility of data in normal HTML tables.
0/1
Spreadsheet
PhpSpreadsheet is a PHP library for reading and writing spreadsheet files. Importing Excel and CSV into MySQL help to save the user time and avoid repetitive work.
0/1
Payment Gateway
Razorpay and PayTM Payment Gateway
0/2
Chatbot
WhatsApp Chatbot and Telegram Chatbot
0/2
CodeIgniter 3
About Lesson

Paytm Payment Gateway enables users to accept payments from anyone, anywhere, from all channels and devices. It is the best Indian payment gateway that lets businesses collect customer payments via website, handheld devices like mobile and tablets, and social apps like WhatsApp, Facebook, or via email and SMS.

1. Create a checkout.php file in the applications/views/ directory.

<form method="post" 
    action="<?php echo base_url('pay'); ?>">
    <table border="1">
        <tbody>
            <tr>
                <th>S.No</th>
                <th>Label</th>
                <th>Value</th>
            </tr>
            <tr>
                <td>1</td>
                <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  " ORDS " . rand(10000,99999999)?>">
                </td>
            </tr>
            <tr>
                <td>2</td>
                <td>
                    <label>CUSTID ::*</label>
                </td>
                <td>
                    <input id="CUST_ID" tabindex="2" 
                    maxlength="12" size="12" name="CUST_ID" 
                    autocomplete="off" value="CUST001">
                </td>
            </tr>
            <tr>
                <td>3</td>
                <td>
                    <label>INDUSTRY_TYPE_ID ::*</label>
                </td>
                <td>
                    <input id="INDUSTRY_TYPE_ID" tabindex="4" 
                    maxlength="12" size="12" name="INDUSTRY_TYPE_ID" 
                    autocomplete="off" value="Retail">
                </td>
            </tr>
            <tr>
                <td>4</td>
                <td>
                    <label>Channel ::*</label>
                </td>
                <td>
                    <input id="CHANNEL_ID" tabindex="4" 
                    maxlength="12" size="12" name="CHANNEL_ID" 
                    autocomplete="off" value="WEB">
                </td>
            </tr>
            <tr>
                <td>5</td>
                <td>
                    <label>txnAmount*</label>
                </td>
                <td>
                    <input title="TXN_AMOUNT" tabindex="10" 
                    type="text" name="TXN_AMOUNT" value="1">
                </td>
            </tr>
            <tr>
                <td></td>
                <td></td>
                <td>
                    <input value="CheckOut" type="submit" onclick="">
                </td>
            </tr>
        </tbody>
    </table>* - Mandatory Fields
</form>

2. Create a redirect.php file in the applications/views/ directory.

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

3. Create a config_paytm.php file in the applications/config/ directory.

Use PAYTM_ENVIRONMENT as ‘PROD’ if you wanted to do transactions in a production environment else ‘TEST’ for doing transactions in a 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.
  • The above details will be different for the testing and production environment.
<?php

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

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

?>

4. Create a Checkout.php file in the applications/controllers/ directory.

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

class Checkout extends CI_Controller {

    public function __construct() {

        parent::__construct();

    }

    public function checkout() {

        $this->load->view('checkout');

    }

    public function pay() {
        $checkSum   = "";
        $paramList  = array();

        $ORDER_ID           = $this->input->post("order_id");
        $CUST_ID            = $this->input->post("user_id");
        $INDUSTRY_TYPE_ID   = $this->input->post("industry_type_id");
        $CHANNEL_ID         = $this->input->post("channel_id");
        $TXN_AMOUNT         = $this->input->post("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;
        $paramList["CALLBACK_URL"]      = base_url('response');

        //Here checksum string will return by getChecksumFromArray() function.
        $data['checkSum'] = getChecksumFromArray($paramList, PAYTM_MERCHANT_KEY);
        $data['paramList'] = $paramList;
        
        $this->load->view('redirect', $data);
    }

    public function response() {
        $paytmChecksum      = "";
        $paramList          = array();
        $isValidChecksum    = "FALSE";

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

        $isValidChecksum = verifychecksum_e($paramList, PAYTM_MERCHANT_KEY, 
        $paytmChecksum); //will return TRUE or FALSE string.

        if($isValidChecksum == "TRUE") {

            if ($_POST["STATUS"] == "TXN_SUCCESS") {
                echo "<b>Transaction status is success</b>" . "<br/>";
            } else {
                echo "<b>Transaction status is failure</b>" . "<br/>";
            }

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

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 a transaction, etc.

5. Create an encdec_paytm_helper.php file in the applications/helpers/ directory.

<?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;
}

?>