Fixing stuff and maybe other things.

Using Sandbox always fails with PayPal IPN (PHP)

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 (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://', 443, $errno, $errstr, 30);

The problem

As near as I can tell, the problem is that the IPN responses are being sent from, even though you want</> to — have been told by PayPal itself — to work with while developing.

The fix

Here it is. See line 2.

$header = "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Host:\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, you also need to set the response header correctly, or there will be a mismatch and sad, sad failure.

Hope this helps!

Posted under: Fixing Stuff, Web Design


#1 by Khodor Hammoud on 09.16.15 at 2:00 pm

Man, you are a life saver!!

#2 by Manish Patel on 09.22.15 at 5:44 am

Ohh WOW, You saved my life. After spending lots of time i found this solution and its works!!!. Thanks a lots

#3 by Newaytech on 01.25.16 at 6:30 am

Respect! You spotted something that has thrown an error in a WooCommerce plugin – great work…

Leave a Comment