Archive

Posts Tagged ‘paypal’

PayPal IPN PHP sample code not working

January 14th, 2009

The sample code supplied by PayPal for using their Instant Payment Notification (IPN) system does not work for me.

A post in their forums has the solution that fixed my code. Boanerges provided the solution: instead of directly opening a socket using fsockopen (as in the sample), use cURL to make the call. mondunet isolated the problem to cookie handling: apparently the PayPal sandbox requires you to accept cookies, which is not something that the direct socket connection does.

Here is the working code:

// read the post from PayPal system and add 'cmd'
if($_SERVER['REQUEST_METHOD']!="POST") die("No data");
$req = 'cmd=_notify-validate';
foreach ($_POST as $key => $value) {
    $value = urlencode(stripslashes($value));
    $req .= "&$key=$value";
}

// post back to PayPal system to validate
$url=(!isset($_POST['test_ipn'])) ? 'https://www.paypal.com/cgi-bin/webscr' : 'https://www.sandbox.paypal.com/cgi-bin/webscr';

$curl_result = $curl_err = '';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded", "Content-Length: " . strlen($req)));
curl_setopt($ch, CURLOPT_HEADER , 0);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);

$curl_result = @curl_exec($ch);
$curl_err = curl_error($ch);
curl_close($ch);

//are we verified? If so, let's process the IPN
if (strpos($curl_result, "VERIFIED")!==false)
{
    //do your IPN stuff here
}

Aidan Findlater Impersonal , ,