【问题标题】:Sample php code to integrate PayPal IPN用于集成 PayPal IPN 的示例 php 代码
【发布时间】:2012-12-10 12:14:02
【问题描述】:

有谁知道如何将我网站上的 PayPal IPN 与 PHP 集成?收到付款后,我需要在我的数据库中插入一条记录。但我在 PayPal 开发者网站上几乎找不到这方面的示例代码。

【问题讨论】:

    标签: php paypal paypal-ipn


    【解决方案1】:

    这里是来自 PayPal 开发者网站的 IPN 的 php 示例代码。我已经通过此代码末尾的注释标记了数据库 INSERT 的确切位置:

    <?php
     
    // STEP 1: Read POST data
     
    // reading posted data from directly from $_POST causes serialization 
    // issues with array data in POST
    // reading raw POST data from input stream instead. 
    $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)
         $myPost[$keyval[0]] = urldecode($keyval[1]);
    }
    // read the post from PayPal system and add 'cmd'
    $req = 'cmd=_notify-validate';
    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";
    }
     
     
    // STEP 2: Post IPN data back to paypal to validate
     
    $ch = curl_init('https://ipnpb.paypal.com/cgi-bin/webscr');
    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_SSL_VERIFYPEER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
    curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
     
    // In wamp like environments that do not come bundled with root authority certificates,
    // please download 'cacert.pem' from "http://curl.haxx.se/docs/caextract.html" and set the directory path 
    // of the certificate as shown below.
    // curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . '/cacert.pem');
    if( !($res = curl_exec($ch)) ) {
        // error_log("Got " . curl_error($ch) . " when processing IPN data");
        curl_close($ch);
        exit;
    }
    curl_close($ch);
     
     
    // STEP 3: Inspect IPN validation result and act accordingly
     
    if (strcmp ($res, "VERIFIED") == 0) {
        // check whether the payment_status is Completed
        // check that txn_id has not been previously processed
        // check that receiver_email is your Primary PayPal email
        // check that payment_amount/payment_currency are correct
        // process payment
     
        // assign posted variables to local variables
        $item_name = $_POST['item_name'];
        $item_number = $_POST['item_number'];
        $payment_status = $_POST['payment_status'];
        $payment_amount = $_POST['mc_gross'];
        $payment_currency = $_POST['mc_currency'];
        $txn_id = $_POST['txn_id'];
        $receiver_email = $_POST['receiver_email'];
        $payer_email = $_POST['payer_email'];
    
        // <---- HERE you can do your INSERT to the database
    
    } else if (strcmp ($res, "INVALID") == 0) {
        // log for manual investigation
    }
    ?>
    

    【讨论】:

    • 使用沙盒时得到$res = INVALID正常吗? (developer.paypal.com/webapps/developer/applications/…)
    • @PaulFournel 不! AFAIK 沙箱不应返回 $res 的 INVALID
    • @Arash Milani Thx 对于答案,我使用另一个 php 脚本解决了这个问题。关键是调用不同的 url,但不是使用 Curl。是$fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30); 我会努力让你的脚本也能正常工作,也许会更好。
    • @PaulFournel 很高兴听到您解决了这个问题。在上面的示例中,您使用 curl 可能会遇到 SSL 错误。如果是这种情况,请检查此页面以获取修复 http://arashmilani.com/post?id=21
    • 为什么链接到 x.com
    【解决方案2】:

    Paypal 发布了一个 Github 存储库,其中包含 IPN 侦听器的示例代码。我强烈建议根据您的首选语言检查和测试这些内容。

    您可以查看 Github 回购:https://github.com/paypal/ipn-code-samples

    您可以在下面找到 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;
            }
        }
    }
    

    还有 IPN 监听器示例:

    <?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");
    

    【讨论】:

    • 我们需要样本来处理 IPN(if ($verified) {} 中的代码)
    • 请注意,PHP 7.4+ (?) 已弃用上述示例代码中的“get_magic_qoutes_gpc”。请参阅此处进行修复:github.com/paypal/ipn-code-samples/issues/160。 GitHub 库中的代码尚未针对此错误进行更新。
    最近更新 更多