How to use Paytm Checkout or Payment method using PHP

 

In this tutorial, we have explained Paytm Payment Gateway Integration in PHP programming language. In today scenario Paytm is the most popular and trusted mobile wallet system. As per the Economic time’s survey Paytm reached approx 200 million registered users. Yes, that is a huge number.

After demonetization in India, Paytm become more popular. Now, most of the users pay Bills and transfer money via the Paytm service. It’s very easy to use and of course very fast.

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

?>

<!DOCTYPE html>
<html lang="en">
<!------ Include the below in your HEAD tag ---------->
<?php
include "include/head.php";
?>
<!------ Include the above in your HEAD tag ---------->
<body class="jumbotron">

  <!------ Include the below in your NAV tag ---------->
  <?php
  include "include/nav.php";
  ?>
  <!------ Include the above in your NAV tag ---------->

<?php
if($isValidChecksum == "TRUE") {

        if ($_POST["STATUS"] == "TXN_SUCCESS")
         { // if success
        
            echo '<div class="jumbotron text-center">
                    <i class="fas fa-check-circle" style="font-size: 78px;color:#4bc14e;"></i>
                      <h1>Thank You for your purchase!</h1>
                      <small style="padding:10px;background:#ddd;color:#7f7f7f;border-radius:5px;">Transation# '.$_POST["TXNID"].'</small>
                      <a href="kart.php" class="btn btn-success"><i class="fas fa-arrow-circle-left" ></i> Back</a>
                    </div>';


?>
                    <div class="container-fluid">
                      <div class="row ">
                        <div class="col-md-4"></div>
                        <div class="col-md-4">
                          <h4>Your transation status has been successfully processed.</h4>

                          <ul class="list-group">
                            
                                <?php
                                    $i = 0;

                                  if (isset($_POST) && count($_POST)>0 )
                                  {
                                    foreach($_POST as $paramName => $paramValue) {
                                    $i++;

                                       if($i !==3 && $i !==6 && $i !==8 && $i !==10 && $i !==12 && $i !==14) // hidden array values (3=>TXNID,6=>CURRENCYINR,8=>STATUS,10=>RESPMSG,12=>BANKTXNID)
                                       {
                                        echo '<li class="list-group-item">
                                                  <small>(Array no. '.$i.')</small>
                                                  <strong>'.$paramName.'</strong>
                                                  <span class="badge">'.$paramValue.'</span>
                                              </li>';

                                        continue;
                                       }
                                        

                                    }
                                  }
                                  

                                ?>


                        </ul>
                        </div>
                        
                      </div>
                    </div>


<?php        
        }
        else {
        //if failure

           echo '<div class="jumbotron text-center">
                <i class="fas fa-times-circle text-danger" style="font-size: 78px;"></i>
                  <h1>Transaction status failure!</h1>
                   <a href="kart.php" class="btn btn-success"><i class="fas fa-arrow-circle-left" ></i> Back</a>
                </div>';
?>

        <div class="container-fluid">
                      <div class="row ">
                     
                        <div class="col-md-8" style="margin-left: 300px;">
                          <h4>Your transation status has been failed.</br>
                            Paytm Responce code:
                           <a href="https://developer.paytm.com/assets/Transaction%20response%20codes%20and%20messages.pdf" target="_blank">PDF</a> </h4></br>
                        

                          <ul class="list-group">
                            <?php
                                 
                                   

                                  if (isset($_POST) && count($_POST)>0 )
                                  {
                                            echo '<li class="list-group-item">
                                                  <strong>RESPCODE</strong>
                                                  <span class="badge">'.$_POST['RESPCODE'].'</span>
                                              </li>';

                                    echo '<li class="list-group-item">
                                                  <strong>RESPMSG</strong>
                                                  <span class="badge">'.$_POST['RESPMSG'].'</span>
                                              </li>';
                                }
                                ?>


                        </ul>
                        </div>
                        
                      </div>
                    </div>


<?php
        }
?>

 


<?php
}
else {
       //if checksum not match
 
           echo '<div class="jumbotron text-center">
                <i class="fas fa-times-circle text-danger" style="font-size: 78px;"></i>
                  <h1>Checksum mismatched.!</h1>
                     <small style="padding:10px;background:#ddd;color:#7f7f7f;border-radius:5px;">Process transaction is suspicious. Someone altered the transaction details.</small>
                      <a href="kart.php" class="btn btn-success"><i class="fas fa-arrow-circle-left" ></i> Back</a>
                </div>';
}

?>

 

</body>
</html>

 

 

 

 

Source code for Refund

Refund.php

<!-- Head tag start here-->
<?php

include "include/head.php";

?>
<!-- Head tag end here-->

<?php
/**
* import checksum generation utility
* You can get this utility from https://developer.paytm.com/docs/checksum/
*/
require_once("lib/config_paytm.php");
require_once("lib/encdec_paytm.php");


if(isset($_POST['submit']))
{
      
      
    /* initialize an array */
    $paytmParams = array();
    
    /* body parameters */
    $paytmParams["body"] = array(
    
        /* Find your MID in your Paytm Dashboard at https://dashboard.paytm.com/next/apikeys */
        "mid" => PAYTM_MERCHANT_MID,
    
        /* This has fixed value for refund transaction */
        "txnType" => "REFUND",
    
        /* Enter your order id for which refund needs to be initiated */
        "orderId" => $_POST['Order_id'],
    
        /* Enter transaction id received from Paytm for respective successful order */
        "txnId" => $_POST['tnx_id'],
    
        /* Enter numeric or alphanumeric unique refund id */
        "refId" => $_POST['ref_id'],
    
        /* Enter amount that needs to be refunded, this must be numeric */
        "refundAmount" => $_POST['ref_amt'],
    );
    
    /**
    * Generate checksum by parameters we have in body
    * Find your Merchant Key in your Paytm Dashboard at https://dashboard.paytm.com/next/apikeys
    */
    $checksum = getChecksumFromString(json_encode($paytmParams["body"], JSON_UNESCAPED_SLASHES), PAYTM_MERCHANT_KEY);
    
    /* head parameters */
    $paytmParams["head"] = array(
    
        /* This is used when you have two different merchant keys. In case you have only one please put - C11 */
        "clientId"    => "C11",
    
        /* put generated checksum value here */
        "signature"    => $checksum
    );
    
    /* prepare JSON string for request */
    $post_data = json_encode($paytmParams, JSON_UNESCAPED_SLASHES);
    
    /* for Staging */
    $url = "https://securegw-stage.paytm.in/refund/apply";
    
    /* for Production */
    // $url = "https://securegw.paytm.in/refund/apply";


    function curl_request($url,$post_data)
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
        $response = curl_exec($ch);
        return $response;
    }
      

        $output= curl_request($url,$post_data); //function calling
        $json = json_decode($output);
        $base_path = $json->body->resultInfo;
      
}


curl_close($ch);
?>
<pre><strong>RAW DATA:</strong> <?php echo (isset($output)) ? var_dump($output) : 'NULL'; ?></pre>

<body>
    <!-- nav tag start here-->
   <?php

    include "include/nav.php";
    
    ?>
    <!-- nav tag end here-->
    
  <div class="container">
       <table class="table table-striped">
          <tbody>
             <tr>
                 
                 <?php
                      if(isset($output) && $output !=='')
                      {
                          
                          if($base_path->resultStatus == 'TXN_SUCCESS')
                          {
                              echo '<div class="alert alert-success" role="alert">';
                              echo  '<i class="fas fa-check-circle" ></i> '.$base_path->resultCode.' : '.$base_path->resultStatus.' : '.$base_path->resultMsg;    
                              echo  '</div>';
                          }
                         else if($base_path->resultStatus == 'PENDING')
                          {
                              echo '<div class="alert alert-warning" role="alert">';
                              echo  '<i class="fas fa-clock" ></i> '.$base_path->resultCode.' : '.$base_path->resultStatus.' : '.$base_path->resultMsg;
                              echo  '</div>';
                          }
                          
                          else
                          {
                              echo '<div class="alert alert-danger" role="alert">';
                              echo  '<i class="fas fa-times-circle" ></i> '.$base_path->resultCode.' : '.$base_path->resultStatus.' : '.$base_path->resultMsg;   
                              echo  '</div>';
                          }
                      }
                 ?>
                 
                
                
                <td colspan="1">
                    <H1>Refund (<a href="https://developer.paytm.com/docs/refund-api" target="_blank">Refund API</a>)</H1>
                    <small><i class="fas fa-info-circle"></i> <strong>GET Refund Detail & status:</strong> <a href="search.php" target="_blank">Here</a></small></br>
                    <small><i class="fas fa-info-circle"></i> <strong>Refund Responce Codes:</strong> <a href="https://developer.paytm.com/docs/refund-api/?ref=refunds#RespCode" target="_blank">Here</a></small></br>
                    <small><i class="fas fa-info-circle"></i> <strong>Side Note:</strong> You can only initiate refund amount upto 6 times on a single transaction.</small>
                   <form class="well form-horizontal" method="post">
                      <fieldset>
                         <div class="form-group">
                            <label class="col-md-3 control-label">Order ID</label>
                            <div class="col-md-9 inputGroupContainer">
                               <div class="input-group"><span class="input-group-addon">
                                   <i class="fas fa-id-card-alt"></i></span>
                                   <input  placeholder="ORDSxxxxxxx" class="form-control" required="true" name="Order_id" type="text"></div>
                            </div>
                         </div>
                         <div class="form-group">
                            <label class="col-md-3 control-label">TNX ID</label>
                            <div class="col-md-9 inputGroupContainer">
                               <div class="input-group"><span class="input-group-addon">
                                   <i class="fas fa-id-card-alt"></i></span>
                                   <input  placeholder="Ex: 202005071112128001101681xxxxx530187" class="form-control" required="true" name="tnx_id" type="text">
                                  </div>
                            </div>
                         </div>
                       
                         
                          <div class="form-group">
                            <label class="col-md-3 control-label">Refund ID (Randomly generated)</label>
                            <div class="col-md-9 inputGroupContainer">
                             <div class="input-group"><span class="input-group-addon">
                                   <i class="fas fa-id-card-alt"></i></span>
                                   <input placeholder="Random ID" class="form-control" required="true" name="ref_id" value="<?php echo  "REFID" . rand(10000,99999999)?>" type="text">
                                  </div>
                            </div>
                         </div>
                         
                           <div class="form-group">
                            <label class="col-md-3 control-label">Refund Amount</label>
                            <div class="col-md-9 inputGroupContainer">
                              <div class="input-group"><span class="input-group-addon">
                                   <i class="fas fa-rupee-sign"></i></span>
                                   <input  placeholder="0.00" class="form-control" required="true" name="ref_amt" type="text" >
                                  </div>
                            </div>
                         </div>
                        
                           <div class="form-group">
                            <label class="col-md-3 control-label"></label>
                            <div class="col-md-9 inputGroupContainer">
                              <button type="submit" class="btn btn-success" name="submit">Initiate Refund</button>
                            </div>
                         </div>
                     
                        
                      </fieldset>
                   </form>
                </td>
               
             </tr>
          </tbody>
       </table>
    </div>
   
</body>

 

 

 

 

Source code for search

Search.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>
<!------ Include the below in your HEAD tag ---------->
<?php
include "include/head.php";
?>
<!------ Include the above in your HEAD tag ---------->
<body>

<div class="container search-table" style="margin-top:40px;padding: 30px;border-radius: 5px;">

    <!------ Include the below in your NAV tag ---------->
    <?php
    include "include/nav.php";
    ?>
    <!------ Include the above in your NAV tag ---------->

    <form method="post" action="">
            <div class="search-box">
                <div class="row">
                    <div class="col-md-3">
                        <h4>Transaction status query</h4>
                    </div>
                    <div class="col-md-7">
                        <input type="text"  id="ORDER_ID"  name="ORDER_ID" class="form-control" placeholder="Enter ORDER_ID" value="<?php echo $ORDER_ID ?>">
                        
                    </div>
                     <div class="col-md-2">
                        
                        <input value="Search" class="btn btn-success" type="submit"    onclick="">
                    </div>
                </div>
            </div>
    <?php
        if (isset($responseParamList) && count($responseParamList)>0 )
        {
        ?>    
            <div class="search-list">
                <h3>Response of status query:</h3>
                <table class="table" id="myTable">
                    <thead>
                        <tr>
                            <th>ATTRIBUTE</th>
                            <th>STATUS</th>
                        </tr>
                    </thead>
                    <tbody>
                    
                       <?php
                            foreach($responseParamList as $paramName => $paramValue) {
                        ?>
                        
                    <tr >
                        <td><?php echo $paramName?></td>
                        <td><?php echo $paramValue?></td>
                    </tr>
                           <?php
                                }
                            ?>

                    
                    </tbody>
                </table>

            </div>

        <?php
        }
        ?>
        </form>
      
        </div>
</body>
</html>

 

 

Click on the below link to download the source code
How to use Paytm Checkout or Payment method using PHP
 

 

 

For more clarity watch the video

 

 

 

 

 
 

 

 

 


Please Share this course

It Looks like you have completed your course!! We have created Online series based on the above content. You can give a test and check your skill.




Be a Part of CollegeSpike by giving your precious comment here and help us in improving our content.