Monday, 3 February 2014

CCAvenue Latest Integration


Steps to Integration:

1. Download the integration kit available in ASP, JSP, PHP and ASP.net.

2. Here you would get 3 files:
 
Data:
The starting page which collects billing details as it would be on your application.

SubmitData or checkout: The confirmation page which displays the data entered in Data page. This page submits the data to CCAvenue Server. This page generates checksum and the encrypted request using the library /jar supplied and WorkingKey.

ResponseHandler  or redirecturl :  The return URL submitted to CCAvenue, this is where CCAvenue will return the control with the transaction status and related information. This page decrypts the response and verifies the CheckSum using the library/jar supplied.
In the “Data” and “submitData”  page you will see a Form with following parameters. You need to pass corresponding values to these parameters.

Merchant_Id: This ID is generated for you at the time of activation of your account.
You can get your CCAvenue Merchant Id/User Id at "Generate Working Key" section of  "Settings & Options" Tab.

Order_Id: A Unique alphanumeric ID generated by you to uniquely identify the order..

Amount: is the total amount of the transaction (greater than 1) in INR, without a currency symbol or other non-numeric character only decimals are allowed.              For eg :1000.00   (DO NOT SEND Rs. 1,000.00)

Redirect_Url: Once the customer on your website has finished authenticating the transaction he is returned back to your website. The URL to which the customer returns back is called the Redirect URL. Once the authorization process has been completed the customer will be redirected to this URL to which we pass return values namely the AuthDesc parameter indicating the status of the transaction along with all of the parameters mentioned below.

Checksum: This refers to a random numeric string generated using a mathematical algorithm (a complex quadratic equation) to ensure that data is not tampered along the way. The way it works is lets say a message has to be sent from A to B. A and B both mutually agree on a Key that only both of them possess. A checksum is generated by a mathematical function using the message and the Key as input. This checksum is then sent along with the message to B. B then recalculates this checksum using the Key and the same algorithm. If the checksum that B calculates is different from the checksum that A passed then the data was tampered along the way.
Note: This key also known as the Working Key is a 32 bit alphanumeric key is assigned to each merchant. Please note that you have to generate this key by logging in to your CCAvenue merchant account and using the "Generate Key" function at the "Settings & Options" menu. Please note that the working key is a vital security data and should not be shared with or exposed to anyone. CCAvenue strongly recommends changing of working key periodically (preferably monthly).

Encryption /Decryption:  Refer the respective integration documents for the encryption and decryption logic.

The Billing details of the customer have to be mandatorily sent via the below mentioned parameters. Please note this has to be authentic data else the transaction would be rejected by the risk team.

billing_cust_name                        
billing_cust_address           
billing_cust_country                     
billing_cust_tel                                      
billing_cust_email

Merchant_param: This is an optional parameter you can send any values of your choice.

payType: This is an optional parameter you can send to identify the payment option selected by customer on your website. The value of this parameter should match identifiers of one of the CCAvenue payment options that have already been assigned to you. If this parameter is passed that payment option will be displayed to the customer as pre-selected on CCAvenue billing page.

billingPageHeading: This is an optional parameter in which you can send the custom heading details for the billing page. The value in this parameter if non-empty, will be displayed on CCAvenue billing page just below the order number and amount.


·          Params marked in  *  are mandatory.

List of parameters
Data Length
Input/Output
Merchant_Id *
50
I & O 
Order_Id *
15
I & O 
Amount *
9
I & O 
Redirect_Url *
200
I & O 
Checksum*
10
I & O 
billing_cust_name *
50
 I & O 
billing_cust_address *
200
 I & O 
billing_cust_country *
50
 I & O 
billing_cust_tel *
50
 I & O 
billing_cust_email*
50
 I & O 
billing_cust_state *
30
 I & O 
billing_cust_city  *
30
 I & O 
billing_zip_code*
10
 I & O 
billing_cust_notes
50
 I & O 
delivery_cust_name
50
 I & O 
delivery_cust_address
200
 I & O 
delivery_cust_country
50
 I & O 
delivery_cust_tel
50
 I & O 
delivery_cust_state
30
 I & O 
delivery_cust_city
30
 I & O 
delivery_zip_code
10
 I & O 
Merchant_Param
100
I & O 
AuthDesc
10
Only O
nb_order_no
20
Only O
nb_bid (Bank Reference No)
20
Only O
card_category(Debit card / Credit Card/ Netbanking)
20
Only O
bank_name(ICICI/ AXIS/ SBI etc.)
20
Only O
payType (If you wish to preselect the payment option, kindly drop a mail to service@ccavenue.com for the bank short codes)
10
Only I
billingPageHeading (optional custom heading)
100
Only I



4. Once all the above integration steps are taken care of and you are ready to go live/test,
-Please login to your CCAvenue account
-Go to "Settings & Options"
-Click the "Generate Working Key"
Here, choose the "activate" option & click submit.

Please Note: The deactivate option will be checked by default. This means that the authorization status of an order will not be available to you in real-time, but only by an order mail & at the "View Pending Orders".You could chose to activate/de-activate this real-time authorization feature anytime by logging in to your CCAvenue account.

Once activated, you can test the integration with the gateway by placing an order using a LIVE card number for a nominal amount.(Rs.10).


<!--
This is the sample Checkout Page php script. It can be directly used for integration with CCAvenue if your application is developed in PHP. You need to simply change the variables to match your variables as well as insert routines (if any) for handling a successful or unsuccessful transaction.
-->


<html>
<head>
<title> Checkout</title>
</head>
<body>
<center>
<?php include('adler32.php')?>
<?php include('Aes.php')?>
<?php 

error_reporting(0);
$merchant_id=$_POST['Merchant_Id'];  // Merchant id(also User_Id) 
$amount=$_POST['Amount'];            // your script should substitute the amount here in the quotes provided here

$order_id=$_POST['Order_Id'];        //your script should substitute the order description here in the quotes provided here
$url=$_POST['Redirect_Url'];         //your redirect URL where your customer will be redirected after authorisation from CCAvenue
$billing_cust_name=$_POST['billing_cust_name'];

$billing_cust_address=$_POST['billing_cust_address'];
$billing_cust_country=$_POST['billing_cust_country'];
$billing_cust_state=$_POST['billing_cust_state'];

$billing_city=$_POST['billing_city'];
$billing_zip=$_POST['billing_zip'];
$billing_cust_tel=$_POST['billing_cust_tel'];

$billing_cust_email=$_POST['billing_cust_email'];
$delivery_cust_name=$_POST['delivery_cust_name'];

$delivery_cust_address=$_POST['delivery_cust_address'];
$delivery_cust_country=$_POST['delivery_cust_country'];

$delivery_cust_state=$_POST['delivery_cust_state'];
$delivery_city=$_POST['delivery_city'];

$delivery_zip=$_POST['delivery_zip'];
$delivery_cust_tel=$_POST['delivery_cust_tel'];
$delivery_cust_notes=$_POST['delivery_cust_notes'];


$working_key=''; //Put in the 32 bit alphanumeric key in the quotes provided here.


$checksum=getchecksum($merchant_id,$amount,$order_id,$url,$working_key); // Method to generate checksum

$merchant_data= 'Merchant_Id='.$merchant_id.'&Amount='.$amount.'&Order_Id='.$order_id.'&Redirect_Url='.$url.'&billing_cust_name='.$billing_cust_name.'&billing_cust_address='.$billing_cust_address.'&billing_cust_country='.$billing_cust_country.'&billing_cust_state='.$billing_cust_state.'&billing_cust_city='.$billing_city.'&billing_zip_code='.$billing_zip.'&billing_cust_tel='.$billing_cust_tel.'&billing_cust_email='.$billing_cust_email.'&delivery_cust_name='.$delivery_cust_name.'&delivery_cust_address='.$delivery_cust_address.'&delivery_cust_country='.$delivery_cust_country.'&delivery_cust_state='.$delivery_cust_state.'&delivery_cust_city='.$delivery_city.'&delivery_zip_code='.$delivery_zip.'&delivery_cust_tel='.$delivery_cust_tel.'&billing_cust_notes='.$delivery_cust_notes.'&Checksum='.$checksum  ;

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

?>

<form method="post" name="redirect" action="http://www.ccavenue.com/shopzone/cc_details.jsp"> 
<?php
echo "<input type=hidden name=encRequest value=$encrypted_data>";
echo "<input type=hidden name=Merchant_Id value=$merchant_id>";

?>
</form>

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

adler32.php file
<?php 
 
error_reporting(0);
function getchecksum($MerchantId,$Amount,$OrderId ,$URL,$WorkingKey)
{
$str ="$MerchantId|$OrderId|$Amount|$URL|$WorkingKey";
$adler = 1;
$adler = adler32($adler,$str);
return $adler;
}

function genchecksum($str)
{
$adler = 1;
$adler = adler32($adler,$str);
return $adler;
}

function verifyChecksum($getCheck, $avnChecksum)
{
$verify=false;
if($getCheck==$avnChecksum) $verify=true;
return $verify;
}

function adler32($adler , $str)
{
$BASE =  65521 ;
$s1 = $adler & 0xffff ;
$s2 = ($adler >> 16) & 0xffff;
for($i = 0 ; $i < strlen($str) ; $i++)
{
$s1 = ($s1 + Ord($str[$i])) % $BASE ;
$s2 = ($s2 + $s1) % $BASE ;
}
return leftshift($s2 , 16) + $s1;
}

function leftshift($str , $num)
{

$str = DecBin($str);

for( $i = 0 ; $i < (64 - strlen($str)) ; $i++)
$str = "0".$str ;

for($i = 0 ; $i < $num ; $i++) 
{
$str = $str."0";
$str = substr($str , 1 ) ;
//echo "str : $str <BR>";
}
return cdec($str) ;
}

function cdec($num)
{
$dec=0;
for ($n = 0 ; $n < strlen($num) ; $n++)
{
  $temp = $num[$n] ;
  $dec =  $dec + $temp*pow(2 , strlen($num) - $n - 1);
}

return $dec;

}?>

Aes.php file

 
<?php
/*
This is an AES Encryption and Decryption Code (128 Bit) in PHP which is compatible with PHP 4 & PHP 5. 
In order to use the encrypt and decrypt methods a string and same key is required.

encrypt method: returns the encypted text.
decrypt mehtod: returns the plain text after decrypting.
*/

error_reporting(0);

function encrypt($plainText,$key)
{
$secretKey = hextobin(md5($key));
$initVector = pack("C*", 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f);
/* Open module and Create IV (Intialization Vector) */
  $openMode = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '','cbc', '');
  $blockSize = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, 'cbc');
$plainPad = pkcs5_pad($plainText, $blockSize);
 
/* Initialize encryption handle */
  if (mcrypt_generic_init($openMode, $secretKey, $initVector) != -1) 
{
     /* Encrypt data */
     $encryptedText = mcrypt_generic($openMode, $plainPad);
           mcrypt_generic_deinit($openMode);
     
return bin2hex($encryptedText);
}

function decrypt($encryptedText,$key)
{
$secretKey = 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);

  /* Open module, and create IV */
  $openMode = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '','cbc', '');


mcrypt_generic_init($openMode, $secretKey, $initVector);
$decryptedText = mdecrypt_generic($openMode, $encryptedText);

// Drop nulls from end of string
$decryptedText = rtrim($decryptedText, "\0");

// Returns "Decrypted string: some text here"

mcrypt_generic_deinit($openMode);
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; 
     } 
?>
redirecturl.php file

<?php include('Aes.php')?>
<?php include('adler32.php')?>
<?php /*This is the sample RedirectURL PHP Page. It can be directly used for integration with CCAvenue if your application is developed in PHP. You need to simply change the variables to match your variables as well as insert routines for handling a successful or unsuccessful transaction.
return values i.e the parameters below are passed as POST parameters by CCAvenue server 
*/
//---------------------------------------------------------------------------------------------------------------------------------//

error_reporting(0);
$workingKey=''; //Working Key should be provided here.
$encResponse=$_POST["encResponse"]; //This is the response sent by the CCAvenue Server

$rcvdString=decrypt($encResponse,$workingKey); //AES Decryption used as per the specified working key.
$AuthDesc="";
$MerchantId="";
$OrderId="";
$Amount=0;
$Checksum=0;
$veriChecksum=false;

$decryptValues=explode('&', $rcvdString);
$dataSize=sizeof($decryptValues);
//******************************    Messages based on Checksum & AuthDesc   **********************************//
echo "<center>";

for($i = 0; $i < $dataSize; $i++) 
{
$information=explode('=',$decryptValues[$i]);
if($i==0) $MerchantId=$information[1];
if($i==1) $OrderId=$information[1];
if($i==2) $Amount=$information[1];
if($i==3) $AuthDesc=$information[1];
if($i==4) $Checksum=$information[1];
}

$rcvdString=$MerchantId.'|'.$OrderId.'|'.$Amount.'|'.$AuthDesc.'|'.$workingKey;
$veriChecksum=verifyChecksum(genchecksum($rcvdString), $Checksum);

if($veriChecksum==TRUE && $AuthDesc==="Y")
{
echo "<br>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.";
//Here you need to put in the routines for a successful 
//transaction such as sending an email to customer,
//setting database status, informing logistics etc etc
}
else if($veriChecksum==TRUE && $AuthDesc==="B")
{
echo "<br>Thank you for shopping with us.We will keep you posted regarding the status of your order through e-mail";
//Here you need to put in the routines/e-mail for a  "Batch Processing" order
//This is only if payment for this transaction has been made by an American Express Card
//since American Express authorisation status is available only after 5-6 hours by mail from ccavenue and at the "View Pending Orders"
}
else if($veriChecksum==TRUE && $AuthDesc==="N")
{
echo "<br>Thank you for shopping with us.However,the transaction has been declined.";
//Here you need to put in the routines for a failed
//transaction such as sending an email to customer
//setting database status etc etc
}
else
{
echo "<br>Security Error. Illegal access detected";
//Here you need to simply ignore this and dont need
//to perform any operation in this condition
}
echo "<br><br>";
//************************************  DISPLAYING DATA RCVD ******************************************//

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

No comments:

Post a Comment