无法理解使用贝宝IPN的正确方法

时间:2019-01-26 19:00:05

标签: php paypal paypal-ipn

正如标题所述,我不了解如何使用IPN。

此页 https://developer.paypal.com/docs/classic/ipn/integration-guide/IPNImplementation/ 说我需要实现我的IPN侦听器,并且它们提供了示例。 这是PHP的示例:

IPN.php

<?php
class PaypalIPN
{
    /** @var bool Indicates if the sandbox endpoint is used. */
    private $use_sandbox = false;
    /** @var bool Indicates if the local certificates are used. */
    private $use_local_certs = true;
    /** Production Postback URL */
    const VERIFY_URI = 'https://ipnpb.paypal.com/cgi-bin/webscr';
    /** Sandbox Postback URL */
    const SANDBOX_VERIFY_URI = 'https://ipnpb.sandbox.paypal.com/cgi-bin/webscr';
    /** Response from PayPal indicating validation was successful */
    const VALID = 'VERIFIED';
    /** Response from PayPal indicating validation failed */
    const INVALID = 'INVALID';
    /**
     * Sets the IPN verification to sandbox mode (for use when testing,
     * should not be enabled in production).
     * @return void
     */
    public function useSandbox()
    {
        $this->use_sandbox = true;
    }
    /**
     * Sets curl to use php curl's built in certs (may be required in some
     * environments).
     * @return void
     */
    public function usePHPCerts()
    {
        $this->use_local_certs = false;
    }
    /**
     * Determine endpoint to post the verification data to.
     *
     * @return string
     */
    public function getPaypalUri()
    {
        if ($this->use_sandbox) {
            return self::SANDBOX_VERIFY_URI;
        } else {
            return self::VERIFY_URI;
        }
    }
    /**
     * Verification Function
     * Sends the incoming post data back to PayPal using the cURL library.
     *
     * @return bool
     * @throws Exception
     */
    public function verifyIPN()
    {
        if ( ! count($_POST)) {
            throw new Exception("Missing POST Data");
        }
        $raw_post_data = file_get_contents('php://input');
        $raw_post_array = explode('&', $raw_post_data);
        $myPost = array();
        foreach ($raw_post_array as $keyval) {
            $keyval = explode('=', $keyval);
            if (count($keyval) == 2) {
                // Since we do not want the plus in the datetime string to be encoded to a space, we manually encode it.
                if ($keyval[0] === 'payment_date') {
                    if (substr_count($keyval[1], '+') === 1) {
                        $keyval[1] = str_replace('+', '%2B', $keyval[1]);
                    }
                }
                $myPost[$keyval[0]] = urldecode($keyval[1]);
            }
        }
        // Build the body of the verification post request, adding the _notify-validate command.
        $req = 'cmd=_notify-validate';
        $get_magic_quotes_exists = false;
        if (function_exists('get_magic_quotes_gpc')) {
            $get_magic_quotes_exists = true;
        }
        foreach ($myPost as $key => $value) {
            if ($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1) {
                $value = urlencode(stripslashes($value));
            } else {
                $value = urlencode($value);
            }
            $req .= "&$key=$value";
        }
        // Post the data back to PayPal, using curl. Throw exceptions if errors occur.
        $ch = curl_init($this->getPaypalUri());
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
        curl_setopt($ch, CURLOPT_SSLVERSION, 6);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        // This is often required if the server is missing a global cert bundle, or is using an outdated one.
        if ($this->use_local_certs) {
            curl_setopt($ch, CURLOPT_CAINFO, __DIR__ . "/cert/cacert.pem");
        }
        curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'User-Agent: PHP-IPN-Verification-Script',
            'Connection: Close',
        ));
        $res = curl_exec($ch);
        if ( ! ($res)) {
            $errno = curl_errno($ch);
            $errstr = curl_error($ch);
            curl_close($ch);
            throw new Exception("cURL error: [$errno] $errstr");
        }
        $info = curl_getinfo($ch);
        $http_code = $info['http_code'];
        if ($http_code != 200) {
            throw new Exception("PayPal responded with http code $http_code");
        }
        curl_close($ch);
        // Check if PayPal verifies the IPN data, and if so, return true.
        if ($res == self::VALID) {
            return true;
        } else {
            return false;
        }
    }
}
?>

他们还提供了一个示例:

Example.php

<?php 
namespace Listener;
require('PaypalIPN.php');
use PaypalIPN;
$ipn = new PaypalIPN();
// Use the sandbox endpoint during testing.
$ipn->useSandbox();
$verified = $ipn->verifyIPN();
if ($verified) {
    /*
     * Process IPN
     * A list of variables is available here:
     * https://developer.paypal.com/webapps/developer/docs/classic/ipn/integration-guide/IPNandPDTVariables/
     */
}
// Reply with an empty 200 response to indicate to paypal the IPN was received correctly.
header("HTTP/1.1 200 OK");
?>

我正在尝试做的事情:

我将在页面上有Paypal按钮,以使用户可以购买基于订阅的软件(1/3/6/12个月)。 (他们不订阅,只支付1/3/6/12个月所需的钱)。 付款后,我需要自动执行更新数据库上的订阅到期日期的过程。

我的问题:

  1. 我不需要编辑什么,是否应该将IPN.php上传到提供的服务器上?
  2. 它是否安全?
  3. 我应在哪里将通知URL(在Paypal的IPN设置上)指向IPN.php或我编辑的Example.php版本?
  4. 除此之外,还有什么提示吗?

我想澄清的是,我已经阅读了贝宝指南上的内容,但迷失了太多信息。

1 个答案:

答案 0 :(得分:1)

1)您显示的代码正在定义一个类,因此您可以启动连接实例,并在其中定义不同的变量。所以你不应该改变它。您应该将其上传到服务器并相应地使用它。

2)嗯……这是一个广泛的问题。像...锁子甲安全吗?对于用剑攻击您的人来说是安全的:是的。对于向您投掷核武器的人来说是安全的:不。而且,这还取决于您如何使用锁子甲。

但是,如果我应该尝试回答我认为您在问的问题:

该脚本可以安全地连接到PayPal。因此,您需要在制作的解决方案中确保脚本和API密钥不被盗用/滥用;这样人们就可以通过您的解决方案访问PayPal,执行您不希望他们做的事情。

3),然后根据documentation that you linked to

  

完成侦听器后,将其推送到您的站点并在帐户设置中指定侦听器URL或通知URL。有关更多信息,请参见IPN Setup

...我必须承认我以前没有使用过。但是,看来here是在您的网站和Paypal之间传递通知的一种方式。因此,我假设这是一条路径,贝宝会检查以获取通知,该通知将显示出来,嗯……某处(?)。很抱歉在这一点上含糊其辞。

4)我的技巧是,看看是否有已经集成了解决方案(框架等)。如果是我,我想我会使用Laravel或WordPress,但这只是因为我有信心使用这些工具。但是两者都带有解决方案(LaravelWordPress),这些解决方案由(希望)知道自己在做什么的人维护。因此,如果PayPal附带了新的API,而现在不赞成使用的API,则不必重新从文档开始。但是要了解一个框架需要花费很多时间(只是要注意)。

但是-一切都取决于您要制作的内容。因此,这是TL; DR版本的第四点:使用框架。