Paypal IPN 1.1 php脚本似乎循环了好几次

时间:2013-10-15 19:49:32

标签: loops paypal paypal-ipn

我最近更新了新版1.1的IPN脚本。它工作和付款通过,但它运行我的成功代码(插入数据库,发送电子邮件)多次。例如我做了测试购买,我的订单经历了22次,我收到了22封电子邮件?!?

这是我的确切代码(实际的数据库和邮件代码是直接的 - 根本没有循环):

//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") !== false) {

            //insert into db and send an email goes here

        }

        if (strcmp ($res, "INVALID" ) == 0) {   }
    }

    fclose($fp);
}

1 个答案:

答案 0 :(得分:0)

我就是这样做的:

$arrRequestVars=$_POST;

$cx=stream_context_create(
    array(
        "http"=>array(
            "method"=>"POST",
            "header"=>"Content-type: application/x-www-form-urlencoded",
            "content"=>"cmd=_notify-validate&".http_build_query($arrRequestVars),
        ),
        "tls"=>array(
            "allow_self_signed"=>false,
        ),
        "ssl"=>array(
            "allow_self_signed"=>false,
        ),
    )
);
$strPayPalVerifyResponse=file_get_contents("https://".PAYPAL_API_HOSTNAME."/cgi-bin/webscr", false, $cx);
if(is_string($strPayPalVerifyResponse))
{
    $_arrParts=explode(" ", $http_response_header[0]);
    $nHTTPResponseCode=(int)$_arrParts[1];
    if($nHTTPResponseCode!==200)
        throw new Exception("Failed to verify wether request originated from PayPal. HTTP response code: ".$nHTTPResponseCode);

    if(trim($strPayPalVerifyResponse)=="INVALID")
        throw new Exception("PayPal did not recognize/validate the incoming IPN request. If the request was valid then mark as paid manually.");
    else if(trim($strPayPalVerifyResponse)!="VERIFIED")
        throw new Exception("Failed to verify wether request originated from PayPal. PayPal response: ".$strPayPalVerifyResponse);
}
else
    throw new Exception("Failed to verify wether request originated from PayPal.");

这是尽可能少的依赖项示例。我推荐cURL over file_get_contents。