Showing posts with label Payment gateway. Show all posts
Showing posts with label Payment gateway. Show all posts

Monday, 14 April 2014

Paypal Payments  Using cURL


Pre-requisites:
-cURL
-Paypal Account with API keys and such

vendors/paypal/Paypal.php

<?php /***********************************************************
This File Sets Up Calls to Paypal by arranging url information.
***********************************************************/
class Paypal{
    
    function 
__construct(){
        
    }
    
    function 
DoDirectPayment($paymentInfo=array()){
        
/**
         * Get required parameters from the web form for the request
         */
        
$paymentType =urlencode('Sale');
        
$firstName =urlencode($paymentInfo['Member']['first_name']);
        
$lastName =urlencode($paymentInfo['Member']['last_name']);
        
$creditCardType =urlencode($paymentInfo['CreditCard']['credit_type']);
        
$creditCardNumber urlencode($paymentInfo['CreditCard']['card_number']);
        
$expDateMonth =urlencode($paymentInfo['CreditCard']['expiration_month']);
        
$padDateMonth str_pad($expDateMonth2'0'STR_PAD_LEFT);
        
$expDateYear =urlencode($paymentInfo['CreditCard']['expiration_year']);
        
$cvv2Number urlencode($paymentInfo['CreditCard']['cv_code']);
        
$address1 urlencode($paymentInfo['Member']['billing_address']);
        
$address2 urlencode($paymentInfo['Member']['billing_address2']);
        
$country urlencode($paymentInfo['Member']['billing_country']);
        
$city urlencode($paymentInfo['Member']['billing_city']);
        
$state =urlencode($paymentInfo['Member']['billing_state']);
        
$zip urlencode($paymentInfo['Member']['billing_zip']);
        
        
$amount urlencode($paymentInfo['Order']['theTotal']);
        
$currencyCode="USD";
        
$paymentType=urlencode('Sale');
        
        
$ip=$_SERVER['REMOTE_ADDR'];
        
        
/* Construct the request string that will be sent to PayPal.
           The variable $nvpstr contains all the variables and is a
           name value pair string with & as a delimiter */
        
$nvpstr="&PAYMENTACTION=Sale&IPADDRESS=$ip&AMT=$amount&CREDITCARDTYPE=$creditCardType&ACCT=$creditCardNumber&EXPDATE=".$padDateMonth.$expDateYear."&CVV2=$cvv2Number&FIRSTNAME=$firstName&LASTNAME=$lastName&STREET=$address1&STREET2=$address2&CITYNAME=$city&STATEORPROVINCE=$state".
        
"&POSTALCODE=$zip&COUNTRY=$country&CURRENCYCODE=$currencyCode";
        
        
/* Make the API call to PayPal, using API signature.
           The API response is stored in an associative array called $resArray */
        
$resArray=$this->hash_call("doDirectPayment",$nvpstr);
        
        
/* Display the API response back to the browser.
           If the response from PayPal was a success, display the response parameters'
           If the response was an error, display the errors received using APIError.php.
           */
        
        
return $resArray;
        
//Contains 'TRANSACTIONID,AMT,AVSCODE,CVV2MATCH, Or Error Codes'
    
}

    function 
SetExpressCheckout($paymentInfo=array()){
        
$amount urlencode($paymentInfo['Order']['theTotal']);
        
$paymentType=urlencode('Sale');
        
$currencyCode=urlencode('USD');
        
        
$returnURL =urlencode($paymentInfo['Order']['returnUrl']);
        
$cancelURL =urlencode($paymentInfo['Order']['cancelUrl']);

        
$nvpstr='&AMT='.$amount.'&PAYMENTACTION='.$paymentType.'&CURRENCYCODE='.$currencyCode.'&RETURNURL='.$returnURL.'&CANCELURL='.$cancelURL;
        
$resArray=$this->hash_call("SetExpressCheckout",$nvpstr);
        return 
$resArray;
    }
    
    function 
GetExpressCheckoutDetails($token){
        
$nvpstr='&TOKEN='.$token;
        
$resArray=$this->hash_call("GetExpressCheckoutDetails",$nvpstr);
        return 
$resArray;
    }
    
    function 
DoExpressCheckoutPayment($paymentInfo=array()){
        
$paymentType='Sale';
        
$currencyCode='USD';
        
$serverName $_SERVER['SERVER_NAME'];
        
$nvpstr='&TOKEN='.urlencode($paymentInfo['TOKEN']).'&PAYERID='.urlencode($paymentInfo['PAYERID']).'&PAYMENTACTION='.urlencode($paymentType).'&AMT='.urlencode($paymentInfo['ORDERTOTAL']).'&CURRENCYCODE='.urlencode($currencyCode).'&IPADDRESS='.urlencode($serverName); 
        
$resArray=$this->hash_call("DoExpressCheckoutPayment",$nvpstr);
        return 
$resArray;
    }
    
    function 
APIError($errorNo,$errorMsg,$resArray){
        
$resArray['Error']['Number']=$errorNo;
        
$resArray['Error']['Number']=$errorMsg;
        return 
$resArray;
    }
    
    function 
hash_call($methodName,$nvpStr)
    {
        require_once 
'constants.php';
        
        
$API_UserName=API_USERNAME;
        
$API_Password=API_PASSWORD;
        
$API_Signature=API_SIGNATURE;
        
$API_Endpoint =API_ENDPOINT;
        
$version=VERSION;
        
        
//setting the curl parameters.
        
$ch curl_init();
        
curl_setopt($chCURLOPT_URL,$API_Endpoint);
        
curl_setopt($chCURLOPT_VERBOSE1);
    
        
//turning off the server and peer verification(TrustManager Concept).
        
curl_setopt($chCURLOPT_SSL_VERIFYPEERFALSE);
        
curl_setopt($chCURLOPT_SSL_VERIFYHOSTFALSE);
    
        
curl_setopt($chCURLOPT_RETURNTRANSFER,1);
        
curl_setopt($chCURLOPT_POST1);
        
//if USE_PROXY constant set to TRUE in Constants.php, then only proxy will be enabled.
        //Set proxy name to PROXY_HOST and port number to PROXY_PORT in constants.php 
        
        
if(USE_PROXY)
            
curl_setopt ($chCURLOPT_PROXYPROXY_HOST.":".PROXY_PORT); 
    
        
//NVPRequest for submitting to server
        
$nvpreq="METHOD=".urlencode($methodName)."&VERSION=".urlencode($version)."&PWD=".urlencode($API_Password)."&USER=".urlencode($API_UserName)."&SIGNATURE=".urlencode($API_Signature).$nvpStr;
    
        
//setting the nvpreq as POST FIELD to curl
        
curl_setopt($ch,CURLOPT_POSTFIELDS,$nvpreq);
    
        
//getting response from server
        
$response curl_exec($ch);
    
        
//convrting NVPResponse to an Associative Array
        
$nvpResArray=$this->deformatNVP($response);
        
$nvpReqArray=$this->deformatNVP($nvpreq);
    
        if (
curl_errno($ch))
            
$nvpResArray $this->APIError(curl_errno($ch),curl_error($ch),$nvpResArray);
        else 
            
curl_close($ch);
    
        return 
$nvpResArray;
    }
    
    
/** This function will take NVPString and convert it to an Associative Array and it will decode the response.
      * It is usefull to search for a particular key and displaying arrays.
      * @nvpstr is NVPString.
      * @nvpArray is Associative Array.
      */
    
    
function deformatNVP($nvpstr)
    {
    
        
$intial=0;
         
$nvpArray = array();
    
    
        while(
strlen($nvpstr)){
            
//postion of Key
            
$keyposstrpos($nvpstr,'=');
            
//position of value
            
$valuepos strpos($nvpstr,'&') ? strpos($nvpstr,'&'): strlen($nvpstr);
    
            
/*getting the Key and Value values and storing in a Associative Array*/
            
$keyval=substr($nvpstr,$intial,$keypos);
            
$valval=substr($nvpstr,$keypos+1,$valuepos-$keypos-1);
            
//decoding the respose
            
$nvpArray[urldecode($keyval)] =urldecode$valval);
            
$nvpstr=substr($nvpstr,$valuepos+1,strlen($nvpstr));
         }
        return 
$nvpArray;
    }
}
?>

vendors/paypal/constants.php

<?php /****************************************************
constants.php

This is the configuration file for the samples.This file
defines the parameters needed to make an API call.
****************************************************/

/**
# API user: The user that is identified as making the call. you can
# also use your own API username that you created on PayPal’s sandbox
# or the PayPal live site
*/
define('API_USERNAME''YOUR USERNAME HERE');
/**
# API_password: The password associated with the API user
# If you are using your own API username, enter the API password that
# was generated by PayPal below
# IMPORTANT - HAVING YOUR API PASSWORD INCLUDED IN THE MANNER IS NOT
# SECURE, AND ITS ONLY BEING SHOWN THIS WAY FOR TESTING PURPOSES
*/
define('API_PASSWORD''YOU PASS HERE');
/**
# API_Signature:The Signature associated with the API user. which is generated by paypal.
*/
define('API_SIGNATURE''YOU SIG HERE');
/**
# Endpoint: this is the server URL which you have to connect for submitting your API request.
*/
define('API_ENDPOINT''https://api-3t.paypal.com/nvp'); /**
USE_PROXY: Set this variable to TRUE to route all the API requests through proxy.
like define('USE_PROXY',TRUE);
*/
define('USE_PROXY',FALSE); /**
PROXY_HOST: Set the host name or the IP address of proxy server.
PROXY_PORT: Set proxy port.

PROXY_HOST and PROXY_PORT will be read only if USE_PROXY is set to TRUE
*/
define('PROXY_HOST''127.0.0.1'); define('PROXY_PORT''808');
/* Define the PayPal URL. This is the URL that the buyer is
   first sent to to authorize payment with their paypal account
   change the URL depending if you are testing on the sandbox
   or going to the live PayPal site
   For the sandbox, the URL is
   https://www.sandbox.paypal.com/webscr&cmd=_express-checkout&token=
   For the live site, the URL is
   https://www.paypal.com/webscr&cmd=_express-checkout&token=
   */
define('PAYPAL_URL''https://www.paypal.com/webscr&cmd=_express-checkout&token=');
/**
# Version: this is the API version in the request.
# It is a mandatory parameter for each API request.
# The only supported value at this time is 2.3
*/
define('VERSION''3.0');
?>

components/paypal.php

Component Class:

<?php  <?php  /**
 * Paypal Direct Payment API Component class file.
 */
App::import('Vendor','paypal' ,array('file'=>'paypal/Paypal.php'));
class 
PaypalComponent extends Object{
    
    function 
processPayment($paymentInfo,$function){
        
$paypal = new Paypal();
        if (
$function=="DoDirectPayment")
            return 
$paypal->DoDirectPayment($paymentInfo);
        elseif (
$function=="SetExpressCheckout")
            return 
$paypal->SetExpressCheckout($paymentInfo);
        elseif (
$function=="GetExpressCheckoutDetails")
            return 
$paypal->GetExpressCheckoutDetails($paymentInfo);
        elseif (
$function=="DoExpressCheckoutPayment")
            return 
$paypal->DoExpressCheckoutPayment($paymentInfo);
        else
            return 
"Function Does Not Exist!";
    }
}
?> ?>

sample direct payment controller function:

Controller Class:

<?php  function processPayment(){
     
$paymentInfo = array('Member'=>
                           array(
                               
'first_name'=>'name_here',
                               
'last_name'=>'lastName_here',
                               
'billing_address'=>'address_here',
                               
'billing_address2'=>'address2_here',
                               
'billing_country'=>'country_here',
                               
'billing_city'=>'city_here',
                               
'billing_state'=>'state_here',
                               
'billing_zip'=>'zip_here'
                           
),
                          
'CreditCard'=>
                           array(
                               
'card_number'=>'number_here',
                               
'expiration_month'=>'month_here',
                               
'expiration_year'=>'year_here',
                               
'cv_code'=>'code_here'
                           
),
                          
'Order'=>
                          array(
'theTotal'=>1.00)
                    );

   
/*
    * On Success, $result contains [AMT] [CURRENCYCODE] [AVSCODE] [CVV2MATCH] 
    * [TRANSACTIONID] [TIMESTAMP] [CORRELATIONID] [ACK] [VERSION] [BUILD]
    * 
    * On Fail, $ result contains [AMT] [CURRENCYCODE] [TIMESTAMP] [CORRELATIONID] 
    * [ACK] [VERSION] [BUILD] [L_ERRORCODE0] [L_SHORTMESSAGE0] [L_LONGMESSAGE0] 
    * [L_SEVERITYCODE0] 
    * 
    * Success or Failure is best tested using [ACK].
    * ACK will either be "Success" or "Failure"
    */
 
    
$result $this->Paypal->processPayment($paymentInfo,"DoDirectPayment");
    
$ack strtoupper($result["ACK"]);
                
    if(
$ack!="SUCCESS")
        
$error $result['L_LONGMESSAGE0'];
    else{
        
/* successful do something here! */
    
}
}
?>

Express Checkout Controller Example

Controller Class:

<?php  function _get($var) {
    return isset(
$this->params['url'][$var])? $this->params['url'][$var]: null;
}
    
function 
expressCheckout($step=1){
    
$this->Ssl->force();
    
$this->set('step',$step);
    
//first get a token
    
if ($step==1){
        
// set
        
$paymentInfo['Order']['theTotal']= .01;
        
$paymentInfo['Order']['returnUrl']= "https://fullPathHere/orders/expressCheckout/2/";
        
$paymentInfo['Order']['cancelUrl']= "https://fullPathToCancelUrl";
            
        
// call paypal
        
$result $this->Paypal->processPayment($paymentInfo,"SetExpressCheckout");
        
$ack strtoupper($result["ACK"]);
        
//Detect Errors
        
if($ack!="SUCCESS")
            
$error $result['L_LONGMESSAGE0'];
        else {
            
// send user to paypal
            
$token urldecode($result["TOKEN"]);
            
$payPalURL PAYPAL_URL.$token;
            
$this->redirect($payPalURL);
        }
    }
    
//next have the user confirm
    
elseif($step==2){
        
//we now have the payer id and token, using the token we should get the shipping address
        //of the payer. Compile all the info into the session then set for the view.
        //Add the order total also
        
$result $this->Paypal->processPayment($this->_get('token'),"GetExpressCheckoutDetails");
        
$result['PAYERID'] = $this->_get('PayerID');
        
$result['TOKEN'] = $this->_get('token');
        
$result['ORDERTOTAL'] = .01;
        
$ack strtoupper($result["ACK"]);
        
//Detect errors
        
if($ack!="SUCCESS"){
            
$error $result['L_LONGMESSAGE0'];
            
$this->set('error',$error);
        }
        else {
            
$this->set('result',$this->Session->read('result'));
            
$this->Session->write('result',$result);
            
/*
             * Result at this point contains the below fields. This will be the result passed 
             * in Step 3. I used a session, but I suppose one could just use a hidden field
             * in the view:[TOKEN] [TIMESTAMP] [CORRELATIONID] [ACK] [VERSION] [BUILD] [EMAIL] [PAYERID]
             * [PAYERSTATUS]  [FIRSTNAME][LASTNAME] [COUNTRYCODE] [SHIPTONAME] [SHIPTOSTREET]
             * [SHIPTOCITY] [SHIPTOSTATE] [SHIPTOZIP] [SHIPTOCOUNTRYCODE] [SHIPTOCOUNTRYNAME]
             * [ADDRESSSTATUS] [ORDERTOTAL]
             */
        
}
    }
    
//show the confirmation
    
elseif($step==3){
        
$result $this->Paypal->processPayment($this->Session->read('result'),"DoExpressCheckoutPayment");
    
//Detect errors
        
$ack strtoupper($result["ACK"]);
        if(
$ack!="SUCCESS"){
            
$error $result['L_LONGMESSAGE0'];
            
$this->set('error',$error);
        }
        else {
            
$this->set('result',$this->Session->read('result'));
        }
    }
}
?>

Express Checkout View: express_checkout.ctp

View Template:


<?php 
    
if (!isset($error)){
        if (
$step==2){
            echo 
$form->create('Order',array('type' => 'post''action' => 'expressCheckout/3''id' => 'OrderExpressCheckoutConfirmation')); 
            
//all shipping info contained in $result display it here and ask user to confirm.
            //echo pr($result);
            
echo $form->end('Confirm Payment'); 
        }
        if (
$step==3){
            
//show confirmation once again all information is contained in $result or $error
            
echo '<h2>Congrats</h2>';
        }
    }
    else
        echo 
$error;
?> 

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