我正在使用这个类
<?php
class paypalIPN {
//sandbox:
private $paypal_url = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
//live site:
//private $paypal_url = 'https://www.paypal.com/cgi-bin/webscr';
private $data = null;
public function __construct()
{
$this->data = new stdClass;
}
public function isa_dispute()
{
//is it some sort of dispute.
return $this->data->txn_type == "new_case";
}
public function validate()
{
// parse the paypal URL
$response = "";
$url_parsed = parse_url($this->paypal_url);
// generate the post string from the _POST vars aswell as load the
// _POST vars into an arry so we can play with them from the calling
// script.
$post_string = '';
foreach ($_POST as $field=>$value) {
$this->data->$field = $value;
$post_string .= $field.'='.urlencode(stripslashes($value)).'&';
}
$post_string.="cmd=_notify-validate"; // append ipn command
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->paypal_url);
//curl_setopt($ch, CURLOPT_VERBOSE, 1);
//keep the peer and server verification on, recommended
//(can switch off if getting errors, turn to false)
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
$response = curl_exec($ch);
if (curl_errno($ch))
{
die("Curl Error: " . curl_errno($ch) . ": " . curl_error($ch));
}
curl_close($ch);
return $response;
if (preg_match("/VERIFIED/", $response))
{
// Valid IPN transaction.
return $this->data;
}
else
{
return false;
}
}
}
我记得在这种模式下:
public function get_ipn()
{
$ipn = new paypalIPN();
$result = $ipn->validate();
$logger = new Log('/error.log');
$logger->write(print_r($result));
}
但我只获得“已验证”或“1”(没有或使用 print_r 函数)。
我也尝试直接返回原始 curl 响应
return $response;
或
return $this->response;
或者还有
return $this->parse_string;
但每次我只收到“1”或“已验证”......
非常感谢
最佳答案
Paypal IPN 通知作为发布数据进入您的脚本。您可以看到,在该类中,代码使用超全局 $_POST
来引用此传入数据。您可以直接使用发布的数据,而不是使用该类。
危险在于它可能不是来自 Paypal。
您在此处显示的脚本正在执行回发验证——也就是说,它正在获取您认为 Paypal 发布给您的信息,并将其立即返回给他们;你问他们,“这是真的吗?”。 Paypal 正在验证,是的,这些信息来自他们。您在该代码中看到的 $response
变量仅包含来自 Paypal 的确认信息。
在您的代码中,当您调用 $result = $ipn->validate();
时,有趣的数据是验证器返回的行 return $this->data ;
(同样的数据还在$_POST
中)。根据您的代码,它将位于变量 $result
中。这就是您想要使用的,它有交易数据,它是 IPN 通知。同样,来自类内部的 $response
值只是来自 Paypal 的无趣点头,让您知道您将要使用的数据是真实的。
附带说明一下,这个类有点困惑而且不太灵活。教程代码?一些建议:最好将数据注入(inject)验证方法而不是直接读取 $_POST
:
<?php
...
public function validate($data)
{
...
foreach ($data as $field=>$value) {
...
}
...
}
//use
$result = $ipn->validate($_POST);
?>
此外,如果 curl 请求有问题,您的验证器将调用 die
。它可能应该返回 false,或者更好的是仍然抛出一个您可以使用 try...catch
处理的异常。您不希望您的整个过程仅仅因为 Paypal 速度慢并且请求超时就吐出带有神秘错误代码的白屏。处理错误,不要死
。最后,与验证器一样,您应该将 url 注入(inject)构造函数而不是将其硬编码到类中。这样您就可以从外部在实时和沙箱之间切换,而不用修改类文件。
关于php - Paypal IPN : how get the POSTs from this class?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19846961/