PayPal IPN错误请求400错误

use*_*375 21 php paypal paypal-ipn

使用PayPal IPN,我不断收到错误400.

我一直在让脚本向我发送电子邮件,$res以查看响应是什么,在while (!feof($fp)) {}循环内部.我总是得到错误:HTTP/1.0 400 Bad Request

我总得回来:

HTTP/1.0 400 Bad Request
?Connection: close
Server: BigIP
Content-Length: 19
?Invalid Host Header
Run Code Online (Sandbox Code Playgroud)

此后的最后一行只是空白.这是我的代码,我尝试过更改大量的东西,但没有任何作用.

$req = 'cmd=_notify-validate';
foreach ($_POST as $key => $value) {
$value = urlencode(stripslashes($value));
$value = preg_replace('/(.*[^%^0^D])(%0A)(.*)/i','${1}%0D%0A${3}', $value);// IPN fix
$req .= "&$key=$value";
}

// post back to PayPal system to validate
$header = "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";

$fp = fsockopen('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30);

if (!$fp) {
// HTTP ERROR
} else {
   fputs($fp, $header . $req);
   while (!feof($fp)) {
       $res = fgets ($fp, 1024);
       if (strcmp ($res, "VERIFIED") == 0) {
           //ADD TO DB
       } else if (strcmp ($res, "INVALID") == 0) {
           // PAYMENT INVALID & INVESTIGATE MANUALY!
           // E-mail admin or alert user
       }
   }
   fclose ($fp);
}
Run Code Online (Sandbox Code Playgroud)

我添加了一行,这是发送之前的标题:

 Host: www.sandbox.paypal.com
 POST /cgi-bin/webscr HTTP/1.0
 Content-Type: application/x-www-form-urlencoded
 Content-Length: 1096
Run Code Online (Sandbox Code Playgroud)

Mic*_*ton 44

由于您自己打开套接字,而不是使用curl等HTTP库,因此需要设置正确的HTTP协议版本并在POST行下方自己添加HTTP Host标头.

$header = "POST /cgi-bin/webscr HTTP/1.1\r\n";
$header .= "Host: www.sandbox.paypal.com\r\n";
Run Code Online (Sandbox Code Playgroud)

  • 您还应该将"HTTP/1.0"更改为"HTTP/1.1". (3认同)

小智 28

我遇到了同样的问题,这些是必要的变化.上面的一些答案并没有解决所有问题.

标题的新格式:

$header = "POST /cgi-bin/webscr HTTP/1.1\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Host: www.sandbox.paypal.com\r\n";  // www.paypal.com for a live site
$header .= "Content-Length: " . strlen($req) . "\r\n";
$header .= "Connection: close\r\n\r\n";
Run Code Online (Sandbox Code Playgroud)

请注意最后一行的额外一组\ r \n.此外,字符串比较不再有效,因为在服务器的响应中插入了换行符,因此请更改:

if (strcmp ($res, "VERIFIED") == 0) 
Run Code Online (Sandbox Code Playgroud)

对此:

if (stripos($res, "VERIFIED") !== false)  // do the same for the check for INVALID
Run Code Online (Sandbox Code Playgroud)

  • 这是截至2013年10月的正确答案,因为我尝试了其他答案但没有奏效.我的PayPal-IPN代码基于这个网站 - > https://developer.paypal.com/webapps/developer/docs/classic/ipn/gs_IPN/并在上面添加此代码使其在沙盒中运行! (4认同)