Thursday, 7 April 2016

Paypal IPN Validation in PHP

Paypal IPN Validation in PHP

Question: How to IPN? How to set IPN in Paypal?
http://www.web-technology-experts-notes.in/2016/03/instant-payment-notification-paypal.html


Question: Why we need to validate the IPN?
To make sure, all data sent in our server is from Paypal.


Question: What are benefits of validating the IPN?
  1. Protect our transaction from SPAM OR robots OR from hackers.
  2. Protect from dmmmy entires in our database.
  3. If protection is ON, We will always sure for transaction record in database.



Question: What does paypal do with valiation?
It will validate all the data, sent to paypal.


Question: What is name of parameter which is send to paypal for validation?
cmd.
For Example:
cmd=_notify-validate



Question: What does paypal return if validation failed?
INVALID


Question: How does paypal return, if validation passed?
VERIFIED


Question: How to validate IPN Response in Sandbox Mode?
$ipnData=$_POST;
$ipnData['cmd']='_notify-validate';
$verify= file_get_contents('https://www.sandbox.paypal.com/cgi-bin/webscr', false, stream_context_create(array(
            'http' => array(
                'header'  => "Content-type: application/x-www-form-urlencoded\r\nUser-Agent: MyAPP 1.0\r\n",
                'method'  => 'POST',
                'content' => http_build_query($ipnData)
            )
        )));  
if($verify=='VERIFIED'){
/** Your data is valid and it is return from paypal */

}



Question: How to validate Paypal IPN Response in LIVE Mode ?
$ipnData=$_POST;
$ipnData['cmd']='_notify-validate';
$verify= file_get_contents('https://www.paypal.com/cgi-bin/webscr', false, stream_context_create(array(
            'http' => array(
                'header'  => "Content-type: application/x-www-form-urlencoded\r\nUser-Agent: MyAPP 1.0\r\n",
                'method'  => 'POST',
                'content' => http_build_query($ipnData)
            )
        )));  
if($verify=='VERIFIED'){
/** Your data is valid and it is return from paypal */

}


Question: How to validate IPN Validate with curl?
$ipnData=$_POST;
$ipnData['cmd']='_notify-validate';

$validateURL='https://www.paypal.com/cgi-bin/webscr';//for paypal
//$validateURL='https://www.sandbox.paypal.com/cgi-bin/webscr'; //for sandbox paypal
   
$ch = curl_init($validateURL);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($ipnData));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
if ( !($verify = curl_exec($ch)) ) {          
 curl_close($ch);
 die('Some Error');
}
curl_close($ch); 
var_dump($verify );//IF VERIFIED, then validate