HTTP 1.1 PayPal IPN Example PHP Code
PayPal recently announced that they're going to "discontinue support for HTTP 1.0 protocol starting February 1, 2013." Today I ran into some problems implementing these changes. It turns out that the VERIFIED response code is now followed by a \r\n. So, the previous if (strcmp($res, "VERIFIED") == 0) { code no longer works by itself. I was able to solve this by trimming off the \r\n using $res = trim($res);. I've posted some example code here in case anyone else is having trouble making their old IPN scripts work with PayPal's new requirements.
View PHP code
<?php
//read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';
foreach ($_POST as $key => $value) {
$value = urlencode(stripslashes($value));
$req .= "&$key=$value";
}
//post back to PayPal system to validate (replaces old headers)
$header = "POST /cgi-bin/webscr HTTP/1.1\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Host: www.paypal.com\r\n";
$header .= "Connection: close\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
$fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30);
//
//error connecting to paypal
if (!$fp) {
//
}
//successful connection
if ($fp) {
fputs ($fp, $header . $req);
while (!feof($fp)) {
$res = fgets ($fp, 1024);
$res = trim($res); //NEW & IMPORTANT
if (strcmp($res, "VERIFIED") == 0) {
//insert order into database
}
if (strcmp ($res, "INVALID") == 0) {
//insert into DB in a table for bad payments for you to process later
}
}
fclose($fp);
}
?>
Categories
· Mobile (1) · Projects (61) · Tutorials (14) · PHP (14) · jQuery (5) · MySQL (4)
View by date
· View All · June 2013 · March 2013 · February 2013 · October 2012 · September 2012 · August 2012 · July 2012 · May 2012 · March 2012 · February 2012 · January 2012 · December 2011 · November 2011 · October 2011 · September 2011 · July 2011 · June 2011 · May 2011 · April 2011 · March 2011 · February 2011 · January 2011 · December 2010 · November 2010 · October 2010 · September 2010 · July 2010 · May 2010 · April 2010 · February 2010 · January 2010 · November 2009 · August 2009 · July 2009