Integrate CC Avenue Payment Gateway in PHP Step by Step | Updated 2022

CCavenue payment gateway php

Loading

CCAvenue is the most popular payment gateway in India. As the eCommerce is picking momentum and growing at exponential rate, it is high time you think about setting up a shopping cart. If you are based out of India then CCAvenue is one among the best choice

Introduction about CCAvenue payment gateway

The CCAvenue is known as Common Service Provider. Master Merchant allows authorized Sub Merchants to accept payment from their customers. The Master Merchant has to be authorized with CCAvenue to make a commercial web application to process payment.

Advantages of using CCAvenue payment gateway

There are many advantages of using this payment gateway method.

  • It is one of the secured payment gateway which promises a protected payment cycle with your application.
  • CCAvenue supports most of the eBusinesses regardless of its size.
  • This type of payment gateway provides high level SSL encryption other security certifications.
  • It promises secured link between customers, CCAvenue payment gateway, application, financial mediates during the payment flow.

Download CCAvenue payment gateway integration kit

The CCAvenue payment gateway integration kit is client library provided by CCAvenue. This integration kit is available for mobile and web application.

CCAvenue provides the integration kit for many programming environment PHP, Python, ASP.Net and more.

By logging in with the approved Merchant account we can see the menu navigation in the header to see the integration kit downloads. After login, navigate through Resources > Web Integration Kit > Download Integration Kit > Download PHP to get the integration kit for the PHP.

When you download the integration kit from the CCAvenue merchant dashboard, it contains request response payment handler files. The integration kit is also contains Crypto.php with the collection of functions to to encrypt decrypt merchant data.

How to get the CCAvenue Merchant ID, Access Code and Working Key

Fore implementing CCAvenue payment gateway integration, the merchant id, access code and the working key are the prime information to be passed with the payment request. For getting these code and keys you need to have CCAvenue Merchant account.

Once we logged in with CCAvenue by using Merchant account, we can see the dashboard with menu options access the resources and keys.

By navigating via Settings > API keys  the CCavenue API keys page will be shown. This page will display the Merchant Id, Access Code and Working key.

The list of Access Code and Working keys are shown for the corresponding registered URLs. So, we need to copy the right secret keys and use them in the right origin to send payment request.

Payment gateway PHP example integration with a website

In this section, we are going to see an example for integrating CCavenue payment gateway in an PHP application.

Configure the Merchant id, Access Code and Working key with your PHP application. In this example, I have created config.php file to contain these security keys used for payment initiation and processing.

In the PHP payment integration kit downloaded from the CCAvenue resources has the ccavRequestHandler.php, ccavResponseHandler.php, Crypto.php and a test file which contains the sample payment form with required inputs.

CCAvenue Payment Form HTML

A standard payment form has to be submitted for initiating the payment request. This form will contain inputs with merchant id, language, amount, currency and more payment details. It also contains customer’s billing information with name and address.

The following HTML shows the sample payment form used in this PHP CCAvenue payment gateway integration example. The form action is pointed to the PHP endpoint ccavRequestHandler.php to which the payment details will be posted.

    <html lang="en">
    <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <title>My Payment Gateway</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css">
    <body class="wsmenucontainer">
    <div class="container">
    <!-- Content Row -->
<?php $merchant_id = "Merchant ID" ?>
    <div class="row">
    <div class="">
    <div class="">
    <div class="col-md-9 col-sm-12 tour-paricular">
    <div class="particular-box" style="padding:13px;">
    <h2 class="heading_bottom">Payment Gateway CC Avenue</h2>
    <form method="post" name="customerData" action="ccavRequestHandler.php">
    <table width="100%" height="100">
    <tr>
    <td colspan="2"> Compulsory information</td>
    </tr>
    <tr>
    <td>TID	:</td><td><input type="text" name="tid" id="tid" value="<?php echo(rand(11111,99999)); ?>" readonly /></td>
    </tr>
    <tr>
    <td>Order Id :</td><td><input type="text" name="order_id" id="order_id" value="<?php echo(rand(11111,99999)); ?>" readonly/></td>
    </tr>
    <tr class="hidden">
    <td>Merchant Id	:</td><td><input hidden type="text" name="merchant_id" value="<?php echo $merchant_id ?>"/></td>
    </tr>
    <tr>
    <td>Amount:</td><td><input type="text" name="amount" placeholder="Enter Amount" required></td>
    </tr>
    <tr>
    <td>Currency:</td>
    <td> 
    <select name="currency">
    <option value="INR">Indian Rupees</option>
    <option value="USD">US Dollar</option>
    <option value="AUD">Australian Dollar</option>
    <option value="GBP">Pound Sterling</option>
    </select>
    </td>
    </tr>
    <br>
    <tr class="hidden">
    <td>Redirect URL	:</td><td><input type="text" name="redirect_url" value="http://localhost/ccavenue/ccavResponseHandler.php"/></td>
    </tr>
    <tr class="hidden">
    <td>Cancel URL	:</td><td><input type="text" name="cancel_url" value="http://localhost/ccavenue/ccavResponseHandler.php"/></td>
    </tr>
    <tr class="hidden">
    <td>Language	:</td><td><input type="text" name="language" value="EN"/></td>
    </tr>
    <tr>
    <td colspan="2">Billing Information</td>
    </tr>
    <tr>
    <td>Billing Name	:</td><td><input type="text" name="billing_name" placeholder="Mention your name" required></td>
    </tr>
    <tr>
    <td>Billing Address	:</td><td><input type="text" name="billing_address" placeholder="Mention your address"/></td>
    </tr>
    <tr>
    <td>Billing City	:</td><td><input type="text" name="billing_city" placeholder="Mention city name" /></td>
    </tr>
    <tr>
    <td>Billing State	:</td><td><input type="text" name="billing_state" Placeholder="Mention state name" /></td>
    </tr>
    <tr>
    <td>Billing Zip	:</td><td><input type="text" name="billing_zip" placeholder="Mention Zipcode" /></td>
    </tr>
    <tr>
    <td>Billing Country	:</td><td><input type="text" name="billing_country" placeholder="Mention country name"></td>
    </tr>
    <tr>
    <td>Billing Tel	:</td><td><input type="phone" name="billing_tel" placeholder="Mention contact number" required></td>
    </tr>
    <tr>
    <td>Billing Email	:</td><td><input type="email" name="billing_email" placeholder="Mention your email id" required></td>
    </tr>
    <tr>
    <td></td><td><INPUT TYPE="submit" class="btn btn-primary" value="PROCEED"></td>
    </tr>
    </table>
    </form>
    </div>
    </div>
    <!-- /.col-lg-8 -->
    <div class="clearfix"></div>
    </div>
    </div>
    </div>
    </div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.min.js"></script>
    </body>
    </html>

ccavRequestHandler.php

In this file, it receives the payment data posted via the HTML form. The posted data are are encrypted in this file. The working key taken from the CCAvenue Merchant dashboard is used as the encryption key.

After encrypting these form input the encrypted details are concatenated and sent to the CCAvenue server with the access code.

The following script shows how it is going to be implemented in the ccavRequestHandler.php file. This code points the CCAvenue test environment for testing the payment flow initially.

<html>
<head>
<title> Non-Seamless-kit</title>
</head>
<body>

<?php include('Crypto.php')?>
<?php

	error_reporting(0);

	$merchant_data='2';
	$working_key='';//Shared by CCAVENUES
	$access_code='';//Shared by CCAVENUES

	foreach ($_POST as $key => $value){
		$merchant_data.=$key.'='.$value.'&';
	}

	$encrypted_data=encrypt($merchant_data,$working_key); // Method for encrypting the data.

?>
<form method="post" name="redirect" action="https://test.ccavenue.com/transaction/transaction.do?command=initiateTransaction">
<?php
echo "<input type=hidden name=encRequest value=$encrypted_data>";
echo "<input type=hidden name=access_code value=$access_code>";
?>
</form>

<script language='javascript'>document.redirect.submit();</script>
</body>
</html>

Crypto.php

This file contains the functions to encrypt or decrypt the payment information posted via the HTML form. It also includes util functions for padding and conversion.

<?php

	error_reporting(0);

	function encrypt($plainText,$key)
	{
		$key = hextobin(md5($key));
		$initVector = pack("C*", 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f);
		$openMode = openssl_encrypt($plainText, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $initVector);
		$encryptedText = bin2hex($openMode);
		return $encryptedText;
	}

	function decrypt($encryptedText,$key)
	{
		$key = hextobin(md5($key));
		$initVector = pack("C*", 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f);
		$encryptedText = hextobin($encryptedText);
		$decryptedText = openssl_decrypt($encryptedText, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $initVector);
		return $decryptedText;
	}
	//*********** Padding Function *********************

	 function pkcs5_pad ($plainText, $blockSize)
	{
	    $pad = $blockSize - (strlen($plainText) % $blockSize);
	    return $plainText . str_repeat(chr($pad), $pad);
	}

	//********** Hexadecimal to Binary function for php 4.0 version ********

	function hextobin($hexString) 
   	 { 
        	$length = strlen($hexString); 
        	$binString="";   
        	$count=0; 
        	while($count<$length) 
        	{       
        	    $subString =substr($hexString,$count,2);           
        	    $packedString = pack("H*",$subString); 
        	    if ($count==0)
		    {
				$binString=$packedString;
		    } 
        	    
		    else 
		    {
				$binString.=$packedString;
		    } 
        	    
		    $count+=2; 
        	} 
  	        return $binString; 
    	  } 
?>

ccavResponseHandler.php

This file contains the functions which handle the responses back coming after the payment successfull, suppose we need to grap the payment details and store into our database then we need ccavResponseHandler.php

<!doctype html>
<html class="no-js" lang="">
<body>
    <div class="container">
    <div class="row">
</div><div class="col-md-6 col-sm-6 col-lg-6 col-6 text-center col-md-offset-3">
<?php include('Crypto.php')?>
<?php

	error_reporting(0);
	
	$workingKey='';		//Working Key should be provided here.
	$encResponse=$_POST["encResp"];			//This is the response sent by the CCAvenue Server
	$rcvdString=decrypt($encResponse,$workingKey);		//Crypto Decryption used as per the specified working key.
	$order_status="";
	$decryptValues=explode('&', $rcvdString);
	$dataSize=sizeof($decryptValues);

	for($i = 0; $i < $dataSize; $i++) 
	{
        $information = explode ( '=', $decryptValues [$i] );
        $responseMap [$information [0]] = $information [1];  
	}

    $order_status = $responseMap ['order_status'];
    
	if($order_status=="Success")
	{
		echo "<br>Your Payment is Successfull. We will contact you soon with your request on mail <br> <a class='btn btn-success' href='http://localhost/ccavenue/'>Back to Home</a>";
		
	}
	else if($order_status=="Aborted")
	{
		echo "<br> Your Payment has Been Aborted <br> <a class='btn btn-primary' href='http://localhost/ccavenue/'>Retry</a> || <a class='btn btn-success' href='http://localhost/ccavenue/'>Switch to Main Page</a>";
	
	}
	else if($order_status==="Failure")
	{
		echo "<br>The transaction has been declined. <br> <a class='btn btn-success' href='http://localhost/ccavenue/'>Back to Home</a>";
	}
	else
	{
		echo "<br>Thank you for the payment. Your transaction is successful. <br> <a class='btn btn-success' href='http://localhost/ccavenue/'>Back to Home</a>";
	
	}

$order_id = $responseMap ['order_id'];
$tracking_id = $responseMap ['tracking_id'];
$bank_ref_no = $responseMap ['bank_ref_no'];
$order_status = $responseMap ['order_status'];
$payment_mode = $responseMap ['payment_mode'];
$card_name = $responseMap ['card_name'];
$status_code = $responseMap ['status_code'];
$status_message = $responseMap ['status_message'];
$currency = $responseMap ['currency'];
$amount = $responseMap ['amount'];
$billing_name = $responseMap ['billing_name'];
$billing_address = $responseMap ['billing_address'];
$billing_city = $responseMap ['billing_city'];
$billing_state = $responseMap ['billing_state'];
$billing_zip = $responseMap ['billing_zip'];
$billing_country = $responseMap ['billing_country'];
$billing_tel = $responseMap ['billing_tel'];
$billing_email = $responseMap ['billing_email'];
$trans_date = $responseMap ['trans_date'];
$token_eligibility = $responseMap ['token_eligibility'];
$response_code = $responseMap ['response_code'];



echo"<table class='table'>
  <thead>
    <tr>
      <th>Order ID</th>
      <th> $order_id </th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>Tracking ID</th>
      <td>$tracking_id</td>
    </tr>
    <tr>
      <th>Bank Ref N.o</th>
      <td>$bank_ref_no</td>
    </tr>
    <tr>
      <th>Order Status</th>
      <td>$order_status</td>
    </tr>
        <tr>
      <th>Payment Mode</th>
      <td>$payment_mode</td>
    </tr>
        <tr>
      <th>Card Name</th>
      <td>$card_name</td>
    </tr>
        <tr>
      <th>Status Code</th>
      <td>$status_code</td>
    </tr>
        <tr>
      <th>Status Message</th>
      <td>$status_message</td>
    </tr>
        <tr>
      <th>Total Amount</th>
      <td>$amount / $currency </td>
    </tr>
        <tr>
      <th>Name & Address </th>
      <td>$billing_name | $billing_address, $billing_city, $billing_state, $billing_zip, $billing_country </td>
    </tr>
        </tr>

        <tr>
      <th>Contact Details</th>
      <td>$billing_tel / $billing_email</td>
    </tr>
            <tr>
      <th>Transaction Date</th>
      <td>$trans_date</td>
    </tr>
            <tr>
      <th>Token Eligibility</th>
      <td>$token_eligibility</td>
    </tr>
        <tr>
      <th>Response Code</th>
      <td>$response_code</td>
    </tr>
    
  </tbody>
</table>"
	
?>
<button class="btn btn-warning" onclick="window.print()">Print this page</button>   
<br><hr>

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dash";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO payments (order_id, tracking_id, bank_ref_no, order_status, payment_mode, card_name, status_code, status_message, currency, billing_name, billing_address, billing_city, billing_state, billing_zip, billing_country, billing_tel, billing_email, trans_date, token_eligibility, response_code, amount)
VALUES ('$order_id','$tracking_id','$bank_ref_no','$order_status','$payment_mode','$card_name','$status_code','$status_message','$currency','$billing_name','$billing_address','$billing_city','$billing_state','$billing_zip','$billing_country','$billing_tel','$billing_email','$trans_date','$token_eligibility','$response_code','$amount')";

if ($conn->query($sql) === TRUE) {
  echo "New record created successfully";
} else {
  echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
<br><hr>
</div>
</div></div>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap-theme.min.css">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"></script>
</body>
</html

CCAvenue test environment

Once this payment gateway integration is completed, the code must be tested in the sandbox environment. CCAvenue provides a test environment to test the payment flow before put the application in production.

In the CCAvenue test environment the payment transactions will not be processed. This is the sandbox mode of testing the payment request and response flow.

The example code in this article targets the test environment URL in the payment form action attribute.

Go Live

After testing the CCAvenue payment gateway integration with the PHP application, you can go live by moving it to the production.

For going live and use the CCAvenue secure production environment, the https://test.ccavenue.com target should be replaced with https://secure.ccavenue.com.

About Post Author