CCAvenue Payment Gateway Integration in PHP
Tags: webdev, php, paymentgateway, ccavenue
Published: 2023-05-07 07:32:18

Hi friends, in this tutorial you will learn how to do the CCAvenue payment gateway integration in PHP. CCAvenue is one of India's top payment gateways, including multiple payment options such as 200+ Mastercard, visa, Rupay, Netbanking, Wallet payments, UPI payments, etc., along with multi-currency options. 

This payment gateway is very fast, simple, and secure and sends the invoice as soon as the payment is done by the merchants. As we all know that we need some keys and credentials provided by the gateway provider while integrating payment gateways.

Also, read, Integrate Instamojo payment gateway in PHP step by step

Test and Production Environment

In every payment gateway, there have to be two types of environments. One is for testing and another is for the production environment as shown below

CCAvenue Test URL:  https://test.ccavenue.com

CCAvenue Production URL:  https://secure.ccavenue.com

## Required steps for CCAvenue payment gateway integration in PHP

Step 1:- Go to the CCAvenue website and sign up for a Merchant account here as shown in the below screenshot.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/upk055yrlml1g94nbzdh.png)

Now, provide your business details and bank details, and KYC to proceed and you will receive an email for account details.

Step 2:- Now, log in to your CCAvenue Merchant account and click on web integration kit under the resources tab.

Step 3:- On the left side, click on download integration kits and download the PHP kit as shown below.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/efjgp6z9z1a5si4kgy87.png)

Step 4:- Now, unzip the downloaded file and you will see three types of kits as given below

. CUSTOM_CHECKOUT_FORM_KIT
. IFRAME_KIT
. NON_SEAMLESS_KIT

We will go with the IFRAME_KIT.

Step 5:- Now, put this IFRAME_KIT folder inside the root directory of your local server which means WAMP, XAMPP, etc.

Step 6:- Get the API keys from the settings tab in your Merchant dashboard as shown below.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f14ujis6lsk5wjtmtafi.png)

Step 7:- Open the dataFrom.htm file and modify it as given below.

```
<html>
<head>
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
<script>
	window.onload = function() {
		var d = new Date().getTime();
		document.getElementById("tid").value = d;
	};
</script>
</head>
<body>
	<form method="post" name="customerData" action="ccavRequestHandler.php">
		<h3 class="text-center">CC Avenue Payment Gateway Integration in PHP</h3>
		<!-- <table width="40%" height="100" border='1' align="center"><caption><font size="4" color="blue"><b>Integration Kit</b></font></caption></table> -->
		<div class="container">
			<div class="row">
				<div class="col-sm-12">
					<table class="table table-bordered">
						<tr class="bg-dark text-white">
							<td colspan="2"> Payment Details</td>
						</tr>
						<tr style="display: none;">
							<td>TID	:</td><td><input type="text" class="form-control form-control-sm" name="tid" id="tid" readonly /></td>
						</tr>
						<tr style="display: none;">
							<td>Merchant Id	:</td><td><input type="text" class="form-control form-control-sm" name="merchant_id" value="your merchant id"/></td>
						</tr>
						<tr style="display: none;">
							<td>Order Id	:</td><td><input type="text" class="form-control form-control-sm" name="order_id" value="123654789"/></td>
						</tr>
						<tr>
							<td>Amount	:</td><td><input type="text" class="form-control form-control-sm" name="amount" value="1.00"/></td>
						</tr>
						<tr style="display: none;">
							<td>Currency	:</td><td><input type="text" class="form-control form-control-sm" name="currency" value="INR"/></td>
						</tr>
						<tr style="display: none;">
							<td>Redirect URL	:</td><td><input type="text" class="form-control form-control-sm" name="redirect_url" value="http://localhost/myprojects/ccavenue/IFRAME_KIT/ccavResponseHandler.php"/></td>
						</tr>
					 	<tr style="display: none;">
					 		<td>Cancel URL	:</td><td><input type="text" class="form-control form-control-sm" name="cancel_url" value="http://localhost/IFrame_PHP_kit/ccavResponseHandler.php"/></td>
					 	</tr>
					 	<tr style="display: none;">
							<td>Language	:</td><td><input type="text" class="form-control form-control-sm" name="language" value="EN"/></td>
						</tr>
				     	<tr>
				     		<td colspan="2" class="fw-bold">Billing information(optional):</td>
				     	</tr>
				        <tr>
				        	<td>Billing Name	:</td><td><input type="text" class="form-control form-control-sm" name="billing_name" value="Charli"/></td>
				        </tr>
				        <tr>
				        	<td>Billing Address	:</td><td><input type="text" class="form-control form-control-sm" name="billing_address" value="Room no 1101, near Railway station Ambad"/></td>
				        </tr>
				        <tr>
				        	<td>Billing City	:</td><td><input type="text" class="form-control form-control-sm" name="billing_city" value="Indore"/></td>
				        </tr>
				        <tr>
				        	<td>Billing State	:</td><td><input type="text" class="form-control form-control-sm" name="billing_state" value="MP"/></td>
				        </tr>
				        <tr>
				        	<td>Billing Zip	:</td><td><input type="text" class="form-control form-control-sm" name="billing_zip" value="425001"/></td>
				        </tr>
				        <tr>
				        	<td>Billing Country	:</td><td><input type="text" class="form-control form-control-sm" name="billing_country" value="India"/></td>
				        </tr>
				        <tr>
				        	<td>Phone Number	:</td><td><input type="text" class="form-control form-control-sm" name="billing_tel" value="9876543210"/></td>
				        </tr>
				        <tr>
				        	<td>Email	:</td><td><input type="text" class="form-control form-control-sm" name="billing_email" value="test@test.com"/></td>
				        </tr>
				        <tr style="display: none;">
				        	<td>Integration Type	:</td><td><input type="text" class="form-control form-control-sm" name="integration_type" value="iframe_normal"/></td>
				        </tr>
				        <tr>
				        	<td></td><td><INPUT TYPE="submit" class="btn btn-dark btn-sm" value="CheckOut"></td>
				        </tr>
		      		</table>
				</div>
			</div>
		</div>
    </form>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js"></script>
</body>
</html>
```
In the above file, put the merchant id received from the API keys section. Please note that your access code and working key should be different for testing purposes and the merchant id will be the same. For the test environment, you should send an email to the support team of CCAvenue at support@ccavenue.com to activate the test environment. 

After the activation, you will be able to use the CCAvenue testing payment gateway interface. If you run the above file in your local server then you will see the output on the browser as given below.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m2vrik9uzlh95ftt4exi.png)

Step 8:- Now, open the ccavRequestHandler.php and put the access code, working key, and merchant data shared by CCAvenue, and change the production URL as given below.

$production_url='https://test.ccavenue.com/transaction/transaction.do?command=initiateTransaction&encRequest='.$encrypted_data.'&access_code='.$access_code;

Step 9:- Open ccavResponseHandler.php and put in the working key you received from CCAvenue as shown below.

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

	error_reporting(0);
	
	$workingKey='working key';		//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);
	echo "<center>";
	for($i = 0; $i < $dataSize; $i++) 
	{
		$information=explode('=',$decryptValues[$i]);
		
		if($i==3)	$order_status=$information[1];

	}

	if($order_status==="Success")
	{
		echo "<br><b>Thank you for shopping with us. Your credit card has been charged and your transaction is successful. We will be shipping your order to you soon.<a href='http://localhost/myprojects/ccavenue/IFRAME_KIT/dataFrom.htm'>Back To Order Page</a></b>";
		
	}
	else if($order_status==="Aborted")
	{
		echo "<br><b>Thank you for shopping with us.We will keep you posted regarding the status of your order through e-mail</b>";
	
	}
	else if($order_status==="Failure")
	{
		echo "<br><b>Thank you for shopping with us.However,the transaction has been declined.</b>";
	}
	else
	{
		echo "<br><b>Security Error. Illegal access detected</b>";
	
	}

	echo "<br><br>";

	//print_r($dataSize);

	 echo "<table cellspacing=4 cellpadding=4>";
	 for($i = 0; $i < $dataSize; $i++) 
	 {
	 	$information=explode('=',$decryptValues[$i]);
	     	echo '<tr><td>'.$information[0].'</td><td>'.$information[1].'</td></tr>';
	 }

	 echo "</table><br>";
	 echo "</center>";
?>
```
Step 10:- Please do not forget to include the Crypto.php file in both the ccavRequestHandler.php and ccavResponseHandler.php as included because it encrypts the payment request sent to the bank and returns the response from the bank with the help of the decrypt() function. The Crypto.php file contains the below functions.

```
<?php
/*
* @param1 : Plain String
* @param2 : Working key provided by CCAvenue
* @return : Decrypted String
*/
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;
}

/*
* @param1 : Encrypted String
* @param2 : Working key provided by CCAvenue
* @return : Plain String
*/
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;
}

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; 
  } 
?>
```
Step 11:- After submission of consumer checkout, as shown above in step 7, you will see the CCAvenue payment interface as given below.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mpcjysxuuo6brw77l9g6.png)

Now, select any of the payment methods and make payment and you will see the payment response as given below.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6oq39q7diy8slnn6un2y.png)
Step 12:- Now, click on return to merchant site as shown in the above screenshot and you will see the response as given below.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7bn08yrou61kvhspd5im.png)

Finally, the integration is done.

Also read, Razorpay payment gateway integration in PHP

Now, if you want to save the transaction details in the MySQL database then follow the below steps.

Establish the database connection as given below.
**dbconnect.php**

```
<?php
$servername='localhost';
$username="root";
$password="";
try
{
	$con=new PDO("mysql:host=$servername;dbname=php_db",$username,$password);
	$con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
	//echo 'connected';
}
catch(PDOException $e)
{
	echo '<br>'.$e->getMessage();
}
?>
```
Create a table in your MySQL database as given below.

DDL information of the table

CREATE TABLE IF NOT EXISTS ccavenue_transaction_details (
id int NOT NULL AUTO_INCREMENT,
order_id varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
tracking_id varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
bank_ref_no varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
order_status varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
failure_message varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
payment_mode varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
status_message varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
currency text COLLATE utf8mb4_unicode_ci NOT NULL,
amount varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
billing_tel varchar(20) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
billing_email varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
transaction_date varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

Open the ccavResponseHandler.php and modify the file as given below.

```
<?php include('Crypto.php')?>
<?php include ('dbconnect.php');?>
<?php
	error_reporting(0);

	$workingKey='working key';		//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]);
		if($i==3)	$order_status=$information[1];
		if($i==0)	$order_id=$information[1];
		if($i==1)	$tracking_id=$information[1];
		if($i==2)	$bank_ref_no=$information[1];
		if($i==4)	$failure_message=$information[1];
		if($i==5)	$payment_mode=$information[1];
		if($i==8)	$status_message=$information[1];
		if($i==9)	$currency=$information[1];
		if($i==10)	$amount=$information[1];
		if($i==17)	$billing_tel=$information[1];
		if($i==18)	$billing_email=$information[1];
		if($i==40)	$transaction_date=$information[1];

	}

	if($order_status==="Success")
	{
		echo "<br><b>Thank you for shopping with us. Your credit card has been charged and your transaction is successful. We will be shipping your order to you soon.<a href='http://localhost/myprojects/ccavenue/IFRAME_KIT/dataFrom.htm'>Back To Order Page</a></b>";

		//insert data into mysql database
		 $sql = "INSERT INTO ccavenue_transaction_details(order_id,tracking_id,bank_ref_no,order_status,failure_message,payment_mode,status_message,currency,amount,billing_tel,billing_email,transaction_date) values('$order_id','$tracking_id','$bank_ref_no','$order_status','$failure_message','$payment_mode','$status_message','$currency','$amount','$billing_tel','$billing_email','$transaction_date')";
		 $stmt = $con->prepare($sql);
		 $stmt->execute();
		
	}
	else if($order_status==="Aborted")
	{
		echo "<br><b>Thank you for shopping with us.We will keep you posted regarding the status of your order through e-mail</b>";
	
	}
	else if($order_status==="Failure")
	{
		echo "<br><b>Thank you for shopping with us.However,the transaction has been declined.</b>";
	}
	else
	{
		echo "<br><b>Security Error. Illegal access detected</b>";
	
	}

	echo "<br><br>";
?>

```
In the above file, you have noticed that if the order status is a success then you can insert the transaction-related data such as order id, tracking id, bank ref number and payment mode, etc. in your database.

Conclusion:- I hope this tutorial will help you to understand the concept. If there is any doubt then please leave a comment below.