Warning: This post assumes you’re already familiar with IPN, and you’re just having trouble, well, troubleshooting it.
Okay, let’s say you’re setting yourself up with PayPal IPN. You’ve set up a PHP listener not unlike this one. You’re all set, right? Ready to test it out with PayPay’s IPN Simulator! Yeah!
Except it fails. It always fails. Why?
To try and figure it out, I set up a file named paypal.txt and told my listener to write the results to that file. Like so:
// These two lines are just landmarks so you can see where I am:
while (!feof($fp)) {
$response = fgets ($fp, 1024);
// Here's the actual logging code:
$file = 'paypal.txt';
$current = file_get_contents($file);
$current .= PHP_EOL."DAMN !fp";
file_put_contents($file, $current);
Okay? And after hours of troubleshooting, this is the only thing I would get:
HTTP/1.0 400 Bad Request
Server: BigIP
Connection: close
Content-Length: 19
Invalid Host header
Nice, huh? Super helpful. Well, as it turns out, the problem is that the example code I linked to above, and variations of it I’ve found all over the webs only work for live IPN responses. Meaning anything from www.sandbox.paypal.com (like PayPal itself tells you to use) will fail. EVEN IF YOU CHANGED IT to use Sandbox like so: (This is line 15 of the above-linked example code)
$fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30);
The problem
As near as I can tell, the problem is that the IPN responses are being sent from paypal.com, even though you want</> to — have been told by PayPal itself — to work with sandbox.paypal.com while developing.
The fix
Here it is. See line 2.
$header = "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Host: www.sandbox.paypal.com\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($postback) . "\r\n\r\n";
Done. Problem should be solved. To sum up, it’s not enough simply to set the fsockopen()
to use sandbox.paypal.com, you also need to set the response header correctly, or there will be a mismatch and sad, sad failure.
Hope this helps!
3 replies
Man, you are a life saver!!
Ohh WOW, You saved my life. After spending lots of time i found this solution and its works!!!. Thanks a lots
Respect! You spotted something that has thrown an error in a WooCommerce plugin – great work…