2013-10-15 31 views
0

我最近更新了我的IPN腳本以獲得新的1.1版本。它的工作原理和支付過程都經過了,但它正在多次運行我的成功代碼(插入db,發送電子郵件)。例如我做了一次測試購買,我的訂單經歷了22次,我收到了22封電子郵件?!?Paypal IPN 1.1 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") !== false) { 

      //insert into db and send an email goes here 

     } 

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

    fclose($fp); 
} 
+0

只是一點點最佳實踐格式,你可能會自己看到問題。 –

+0

好吧...它看起來格式化我現在(我縮進})。雖然 –

+0

它仍然不能看到問題它必須是循環運行的while()循環,但我不明白爲什麼它會多次運行?這是大多數人使用的相同代碼 –

回答

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超過file_get_contents。