Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/233.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php PayPal IPN始终返回“0”;“无效”; 我的问题_Php_Paypal_Paypal Ipn_Paypal Sandbox - Fatal编程技术网

Php PayPal IPN始终返回“0”;“无效”; 我的问题

Php PayPal IPN始终返回“0”;“无效”; 我的问题,php,paypal,paypal-ipn,paypal-sandbox,Php,Paypal,Paypal Ipn,Paypal Sandbox,我在PHP中设置了一个IPN侦听器,但在使用PayPal的IPN模拟器进行测试时,它总是返回INAVLID 我知道这是一个常见问题,但我花了整整一个周末阅读了50多个类似的问题并尝试了它们的解决方案,但没有一个对我有效 注意:我必须使用fsock,我的服务器不支持cURL 我试过的 确保我的服务器正在将请求发送到www.sandbox.paypal.com,而不是www.paypal.com 确保我的服务器使用SSL和端口443 确保主机标题不丢失 确保我的响应与PayPal的请求相同,前缀为

我在PHP中设置了一个IPN侦听器,但在使用PayPal的IPN模拟器进行测试时,它总是返回
INAVLID

我知道这是一个常见问题,但我花了整整一个周末阅读了50多个类似的问题并尝试了它们的解决方案,但没有一个对我有效

注意:我必须使用fsock,我的服务器不支持cURL

我试过的
  • 确保我的服务器正在将请求发送到
    www.sandbox.paypal.com
    ,而不是
    www.paypal.com

  • 确保我的服务器使用SSL和端口443

  • 确保主机标题不丢失

  • 确保我的响应与PayPal的请求相同,前缀为
    cmd=\u notify-validate&

  • 确保我的服务器正确解析
    已验证的
    /
    无效的
    响应(PayPal的新系统发送
    7\r\n无效的\r\n0
    ,而不仅仅是
    无效的

我的代码 IPN侦听器类 我的服务器的响应
IPN模拟器使用沙盒环境,但您的IPN侦听器类设置为
public$use\u Sandbox=false
,这意味着您处于实时环境中,这可能是导致您的回复总是变得
无效的原因。我在这个问题上花了将近2天的时间,我想我会与大家分享对我有用的东西,希望它能帮助其他一些面临同样问题的人

问题 PayPal IPN模拟器始终提供无效的IPN响应

解决方案
模拟时,将模拟器字段中的
付款日期更改为
NULL
,如果设置正确,一切都应该开始工作。

默认情况下,类将其设置为
false
,但我的实际IPN侦听器(请参见第二个代码块)调用
$listener->use\u sandbox=true在创建侦听器之后。您为什么要将代码拆分为类和实际侦听器?你能试试这段代码吗,看看它是否适合你?遗憾的是,我不能使用这段代码,因为它使用cURL,而我的服务器只支持fsock。我之所以使用这个类,是因为它似乎是最新的IPN侦听器实现,而且不需要cURL。你解决了这个问题吗?我也有同样的问题,无法找到解决办法。@kokoseq遗憾的是,即使是PayPal支持也无法找到问题的原因。很高兴知道。我再也没有服务器了(所以我无法测试它是否真的有效),我很久以前就放弃了整个PayPal的事情(这个问题已经9个月了),但我只是想假设这会修复它,并将您的答案标记为解决方案。希望有同样问题的人能从中受益。删除日期的解决方案并不能解决这个问题。
<?php
/**
 *  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 = true;
    /**
     *  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 = 'ssl://'.$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.");
        }
    }
}
<?php

ini_set("log_errors", 1);
ini_set("error_log", "php-error.log");

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

require_once $_SERVER['DOCUMENT_ROOT'] . '/_includes/ipnlistener.php';

$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);
}

file_put_contents("verified.log", $verified ? "VERIFIED" : "INVALID");
payment_type=instant&payment_date=Sun%20Dec%2006%202015%2020%3A05%3A21%20GMT%2B0100%20%28Mitteleurop%C3%A4ische%20Zeit%29&payment_status=Completed&address_status=confirmed&payer_status=verified&first_name=John&last_name=Smith&payer_email=buyer%40paypalsandbox.com&payer_id=TESTBUYERID01&address_name=John%20Smith&address_country=United%20States&address_country_code=US&address_zip=95131&address_state=CA&address_city=San%20Jose&address_street=123%20any%20street&business=seller%40paypalsandbox.com&receiver_email=seller%40paypalsandbox.com&receiver_id=seller%40paypalsandbox.com&residence_country=US&item_name1=something&item_number1=AK-1234&tax=2.02&mc_currency=USD&mc_fee=0.44&mc_gross=12.34&mc_gross1=12.34&mc_handling=2.06&mc_handling1=1.67&mc_shipping=3.02&mc_shipping1=1.02&txn_type=cart&txn_id=936522821&notify_version=2.1&custom=xyz123&invoice=abc1234&test_ipn=1&verify_sign=AFcWxV21C7fd0v3bYYYRCpSSRl31A61b6KnaHJWRwuKxRGWvWo2Bos20
cmd=_notify-validate&payment_type=instant&payment_date=Sun+Dec+06+2015+20%3A05%3A21+GMT%2B0100+%28Mitteleurop%C3%A4ische+Zeit%29&payment_status=Completed&address_status=confirmed&payer_status=verified&first_name=John&last_name=Smith&payer_email=buyer%40paypalsandbox.com&payer_id=TESTBUYERID01&address_name=John+Smith&address_country=United+States&address_country_code=US&address_zip=95131&address_state=CA&address_city=San+Jose&address_street=123+any+street&business=seller%40paypalsandbox.com&receiver_email=seller%40paypalsandbox.com&receiver_id=seller%40paypalsandbox.com&residence_country=US&item_name1=something&item_number1=AK-1234&tax=2.02&mc_currency=USD&mc_fee=0.44&mc_gross=12.34&mc_gross1=12.34&mc_handling=2.06&mc_handling1=1.67&mc_shipping=3.02&mc_shipping1=1.02&txn_type=cart&txn_id=936522821&notify_version=2.1&custom=xyz123&invoice=abc1234&test_ipn=1&verify_sign=AFcWxV21C7fd0v3bYYYRCpSSRl31A61b6KnaHJWRwuKxRGWvWo2Bos20