php - Paypal IPN 返回空响应 PHP

标签 php curl paypal paypal-sandbox

Paypal IPN 返回空响应。这是我的代码。

<?php

ini_set("log_errors", 1);
ini_set("error_log", "php-error.log");
/**
 *  PayPal IPN Listener
 *
 *  A class to listen for and handle Instant Payment Notifications (IPN) from
 *  the PayPal server.
 *
 *  Forked from the great Quixotix PayPal IPN script. This fork plans to
 *  fix the current issues with the original repo, as well as update the code
 *  for use according to PayPal's documentation, and today's standards.
 *
 *  @package    PHP-PayPal-IPN
 *  @link       https://github.com/WadeShuler/PHP-PayPal-IPN
 *  @forked     https://github.com/Quixotix/PHP-PayPal-IPN
 *  @author     Wade Shuler
 *  @copyright  Copyright (c) 2015, Wade Shuler
 *  @license    http://choosealicense.com/licenses/gpl-2.0/
 *  @version    2.5.2
 */
class IpnListener
{
    /**
     *  If true, the recommended cURL PHP library is used to send the post back
     *  to PayPal. If flase then fsockopen() is used. Default true.
     *
     *  @var boolean
     */
    public $use_curl = false;
    /**
     *  If true, cURL will use the CURLOPT_FOLLOWLOCATION to follow any
     *  "Location: ..." headers in the response.
     *
     *  @var boolean
     */
    public $follow_location = false;
    /**
     *  If true, the paypal sandbox URI www.sandbox.paypal.com is used for the
     *  post back. If false, the live URI www.paypal.com is used. Default false.
     *
     *  @var boolean
     */
    public $use_sandbox = false;
    /**
     *  The amount of time, in seconds, to wait for the PayPal server to respond
     *  before timing out. Default 30 seconds.
     *
     *  @var int
     */
    public $timeout = 30;
    /**
     * If true, enable SSL certification validation when using cURL
     *
     * @var boolean
     */
    public $verify_ssl = true;
    private $_errors = array();
    private $post_data;
    private $rawPostData;               // raw data from php://input
    private $post_uri = '';
    private $response_status = '';
    private $response = '';
    const PAYPAL_HOST = 'www.paypal.com';
    const SANDBOX_HOST = 'www.sandbox.paypal.com';
    /**
     *  Post Back Using cURL
     *
     *  Sends the post back to PayPal using the cURL library. Called by
     *  the processIpn() method if the use_curl property is true. Throws an
     *  exception if the post fails. Populates the response, response_status,
     *  and post_uri properties on success.
     *
     *  @todo add URL param so function is more dynamic
     *
     *  @param  string  The post data as a URL encoded string
     */
    protected function curlPost($encoded_data)
    {
        $uri = 'https://'.$this->getPaypalHost().'/cgi-bin/webscr';
        $this->post_uri = $uri;
        $ch = curl_init();
        if ($this->verify_ssl) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
            curl_setopt($ch, CURLOPT_CAINFO, dirname(dirname(__FILE__)) . '/cert/api_cert_chain.crt');
        }
        curl_setopt($ch, CURLOPT_URL, $uri);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $encoded_data);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, $this->follow_location);
        curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, true);
        $this->response = curl_exec($ch);
        $this->response_status = strval(curl_getinfo($ch, CURLINFO_HTTP_CODE));
        if ($this->response === false || $this->response_status == '0') {
            $errno = curl_errno($ch);
            $errstr = curl_error($ch);
            throw new Exception("cURL error: [$errno] $errstr");
        }
        return $this->response;
    }
    /**
     *  Post Back Using fsockopen()
     *
     *  Sends the post back to PayPal using the fsockopen() function. Called by
     *  the processIpn() method if the use_curl property is false. Throws an
     *  exception if the post fails. Populates the response, response_status,
     *  and post_uri properties on success.
     *
     *  @todo add URL param so function is more dynamic
     *
     *  @param  string  The post data as a URL encoded string
     */
    protected function fsockPost($encoded_data)
    {
        $uri =$this->getPaypalHost();
        $port = '443';
        $this->post_uri = $uri.'/cgi-bin/webscr';
        $fp = fsockopen($uri, $port, $errno, $errstr, $this->timeout);
        if (!$fp) {
            // fsockopen error
            throw new Exception("fsockopen error: [$errno] $errstr");
        }
        $header = "POST /cgi-bin/webscr HTTP/1.1\r\n";
        $header .= "Host: ".$this->getPaypalHost()."\r\n";
        $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
        $header .= "Content-Length: ".strlen($encoded_data)."\r\n";
        $header .= "Connection: Close\r\n\r\n";
        fputs($fp, $header.$encoded_data."\r\n\r\n");
        while(!feof($fp)) {
            if (empty($this->response)) {
                // extract HTTP status from first line
                $this->response .= $status = fgets($fp, 1024);
                $this->response_status = trim(substr($status, 9, 4));
            } else {
                $this->response .= fgets($fp, 1024);
            }
        }
        fclose($fp);
        return $this->response;
    }
    private function getPaypalHost()
    {
        return ($this->use_sandbox) ? self::SANDBOX_HOST : self::PAYPAL_HOST;
    }
    public function getErrors()
    {
        return $this->_errors;
    }
    private function addError($error)
    {
        $this->_errors[] .= $error;
    }
    public function getPostData()
    {
        return $this->post_data;
    }
    public function getRawPostData()
    {
        return $this->rawPostData;
    }
    /**
     *  Get POST URI
     *
     *  Returns the URI that was used to send the post back to PayPal. This can
     *  be useful for troubleshooting connection problems. The default URI
     *  would be "ssl://www.sandbox.paypal.com:443/cgi-bin/webscr"
     *
     *  @return string
     */
    public function getPostUri()
    {
        return $this->post_uri;
    }
    /**
     *  Get Response
     *
     *  Returns the entire response from PayPal as a string including all the
     *  HTTP headers.
     *
     *  @return string
     */
    public function getResponse()
    {
        return $this->response;
    }
    /**
     *  Get Response Status
     *
     *  Returns the HTTP response status code from PayPal. This should be "200"
     *  if the post back was successful.
     *
     *  @return string
     */
    public function getResponseStatus()
    {
        return $this->response_status;
    }
    /**
     *  Get Text Report
     *
     *  Returns a report of the IPN transaction in plain text format. This is
     *  useful in emails to order processors and system administrators. Override
     *  this method in your own class to customize the report.
     *
     *  @return string
     */
    public function getTextReport()
    {
        $r = '';
        // date and POST url
        for ($i=0; $i<80; $i++) { $r .= '-'; }
        $r .= "\n[".date('m/d/Y g:i A').'] - '.$this->getPostUri();
        if ($this->use_curl) {
            $r .= " (curl)\n";
        } else {
            $r .= " (fsockopen)\n";
        }
        // HTTP Response
        for ($i=0; $i<80; $i++) { $r .= '-'; }
        $r .= "\n{$this->getResponse()}\n";
        // POST vars
        for ($i=0; $i<80; $i++) { $r .= '-'; }
        $r .= "\n";
        foreach ($this->post_data as $key => $value) {
            $r .= str_pad($key, 25)."$value\n";
        }
        $r .= "\n\n";
        return $r;
    }
    /**
     *  Process IPN
     *
     *  Handles the IPN post back to PayPal and parsing the response. Call this
     *  method from your IPN listener script. Returns true if the response came
     *  back as "VERIFIED", false if the response came back "INVALID", and
     *  throws an exception if there is an error.
     *
     *  @param array
     *
     *  @return boolean
     */
    public function processIpn($post_data=null)
    {
        try
        {
            $this->requirePostMethod();     // processIpn() should check itself if data is POST
            // Read POST data
            // reading posted data directly from $_POST causes serialization
            // issues with array data in POST. Reading raw POST data from input stream instead.
            if ($post_data === null) {
                $raw_post_data = file_get_contents('php://input');
            } else {
                $raw_post_data = $post_data;
            }
            $this->rawPostData = $raw_post_data;                            // set raw post data for Class use
            // if post_data is php input stream, make it an array.
            if ( ! is_array($raw_post_data) ) {
                $raw_post_array = explode('&', $raw_post_data);
                $this->post_data = $raw_post_array;                             // use post array because it's same as $_POST
            } else {
                $this->post_data = $raw_post_data;                              // use post array because it's same as $_POST
            }
            $myPost = array();
            if (isset($raw_post_array)) {
                foreach ($raw_post_array as $keyval) {
                    $keyval = explode('=', $keyval);
                    if (count($keyval) == 2) {
                        $myPost[$keyval[0]] = urldecode($keyval[1]);
                    }
                }
            }
            // read the post from PayPal system and add 'cmd'
            $req = 'cmd=_notify-validate';
            foreach ($myPost as $key => $value) {
                if (function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc() == 1) {
                    $value = urlencode(stripslashes($value));
                } else {
                    $value = urlencode($value);
                }
                $req .= "&$key=$value";
            }

            //XXX Debug log
            $file = fopen('lastresponse.log', 'w');
            fwrite($file, $req);
            fclose($file);

            if ($this->use_curl) {
                $res = $this->curlPost($req);
            } else {
                $res = $this->fsockPost($req);
            }
            if (strpos($res, '200') === false) {
                throw new Exception("Invalid response status: " . $res);
            }
            // Split response headers and payload, a better way for strcmp
            $tokens = explode("\r\n\r\n", trim($res));
            $res = trim(end($tokens));
            if (strpos ($res, "VERIFIED") !== false) {
                return true;
            } else if (strpos ($res, "INVALID") !== false) {
                return false;
            } else {
                throw new Exception("Unexpected response from PayPal: " . $res);
            }
        } catch (Exception $e) {
            $this->addError($e->getMessage());
            return false;
        }
        return false;
    }
    /**
     *  Require Post Method
     *
     *  Throws an exception and sets a HTTP 405 response header if the request
     *  method was not POST.
     */
    public function requirePostMethod()
    {
        // require POST requests
        if ($_SERVER['REQUEST_METHOD'] && $_SERVER['REQUEST_METHOD'] != 'POST') {
            header('Allow: POST', true, 405);
            throw new Exception("Invalid HTTP request method.");
        }
    }
}

$file = fopen('lastrequest.log', 'w');
fwrite($file, file_get_contents('php://input'));
fclose($file);

$listener = new IpnListener();
$listener->use_sandbox = true;
$listener->use_curl = false;
header('HTTP/1.1 200 OK');

if ($verified = $listener->processIpn())
{
    // Valid IPN
    /*
        1. Check that $_POST['payment_status'] is "Completed"
        2. Check that $_POST['txn_id'] has not been previously processed
        3. Check that $_POST['receiver_email'] is your Primary PayPal email
        4. Check that $_POST['payment_amount'] and $_POST['payment_currency'] are correct
    */
    $transactionRawData = $listener->getRawPostData();      // raw data from PHP input stream
    $transactionData = $listener->getPostData();            // POST data array
    // Feel free to modify path and filename. Make SURE THE DIRECTORY IS WRITEABLE!
    // For security reasons, you should use a path above/outside of your webroot
    file_put_contents('ipn_success.log', print_r($transactionData, true) . PHP_EOL, LOCK_EX | FILE_APPEND);
} else {
    // Invalid IPN
    $errors = $listener->getErrors();
    // Feel free to modify path and filename. Make SURE THE DIRECTORY IS WRITEABLE!
    // For security reasons, you should use a path above/outside of your webroot
    file_put_contents('ipn_errors.log', print_r($errors, true) . PHP_EOL, LOCK_EX | FILE_APPEND);
    echo print_r($errors, true);
}

file_put_contents("verified.log", $verified ? "VERIFIED" : "INVALID");
?>

我试过检查多个 IPN,但都没有用。因此,我决定使用它来记录所有内容。 最后请求.log:

cmd=_s-xclick&hosted_button_id=L9CJDZARMVPHA

lastresponse.log:

cmd=_notify-validate&cmd=_s-xclick&hosted_button_id=L9CJDZARMVPHA

已验证.log:

INVALID

ipn_errors.log:

Array
(
    [0] => Invalid response status: 
)

我试过使用 curl 和 fsock,但结果总是一样。

最佳答案

我遇到了同样的问题,因为 PayPal 的 POST 消息有问题。 我正在使用 POSTMAN 检查此问题,并从文档示例中复制示例 PayPal 消息。我使用 POSTMAN 发送此消息 - 效果很简单,服务器接收真实的 POST 消息和脚本处理这个完美。我不知道为什么 PayPal 在通过 POST 发送消息时会出现此错误。

关于php - Paypal IPN 返回空响应 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45030417/

相关文章:

php - 正则表达式验证用户名

javascript - 将整个表行数据提取到 javascript 变量中

php - 使用 JSON 和 cURL 通过 PHP 发布到 Dreamfactory API

PHP stream_socket_client 连接失败

paypal - 如何避免使用 Paypal 处理信用卡

php - 在 Laravel 中将多个字段输入合并为单个值

php - 为什么键盘和字母在 NetBeans 中不匹配?

c++ - 在 C++ 中使用 cURL 和多线程

php - 沙盒 Paypal 发票 API,未发送电子邮件

forms - 我可以像使用 PayPal 一样发布到 Authorize.net 吗?