Paypal IPN Script release with feof and fgets
I have been having problems with my IPL Paypal script listener for a couple of days. For those of you who are not familiar with Paypal's IPN system, basically Paypal sends your script a message about the transaction you send back with a few bits added. If Paypal gets a correct answer, it will reply "VERIFIED", and if not, it will say "INVALID".
I originally thought the problem I was facing was with the fsockopen command: $ fp = fsockopen ('ssl: //sandbox.paypal.com', 443, $ errno, $ errstr, 30); However, having reduced all of my code to a large chunk of this exact line, it seems to be connected fine. The problem is with the "feof" and "fgets" commands. The script just hangs and I don't know why. I essentially copied the code suggested on the Paynal IPN Listener website, so I assumed it would work! If you could help me understand why feof or fgets are causing it to stall, then your help would be much appreciated.
Here's the complete script:
$postback = 'cmd=_notify-validate'; //doesn't matter what these include for now
$header='abc';
//Script has been activated, create debug
$filename = 'debug/debug1_script.txt';
$filehandle=fopen($filename, 'w');
fwrite($filehandle,$postback);
fclose($filehandle);
$fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30);//open the connection
//no connection, create debug file
if(!$fp){
$filename = 'debug/debug2_fpfail.txt';
$filehandle=fopen($filename, 'w');
fwrite($filehandle, $errstr.'('.$errno.')');
fclose($filehandle);
die();
}
//post data back
fputs($fp, $header . $postback);
//create debug file
$filename = 'debug/debug3_postback.txt';
$filehandle=fopen($filename, 'w');
fwrite($filehandle, $header.$postback);
fclose($filehandle);
//script hangs with either of the two following lines included
while(!feof($fp)){
$res=fgets($fp,1024);
}
Thank you very much in advance!
source to share
If anyone else has the same problem, CURL seems to be the recommended choice for IPN via PayPal.
Check out the sample code on Github at: https://github.com/paypal/ipn-code-samples/blob/master/paypal_ipn.php
source to share
The connection to paypal from your socket $fp
must be http POST. feof()
hangs because paypal never hears the full HTTP request, so it never sends anything - it just keeps listening until you give up.
You need some extra stuff (variables $header
and ready-made $req
) in the sample code on this PayPal IPN page .
I would rewrite this to use CURL, if possible, instead of raw sockets, so that you don't have to format the full HTTP request and read the raw HTTP response.
source to share