PHP Paypal IPN:交易未确认

Posted

技术标签:

【中文标题】PHP Paypal IPN:交易未确认【英文标题】:PHP Paypal IPN: transaction not confirmed 【发布时间】:2011-12-18 05:04:48 【问题描述】:

我正在为自定义数字电子商务创建 IPN,但我遇到了一个问题: 一切正常的文件,我在我的数据库中创建了一个“待付款”,其 ID 称为 PID(付款 ID),用户转到贝宝页面,付款完成后贝宝在 IPN 侦听器上与我联系,检查是否支付完成并启用用户购买的所有媒体。

我使用 micah carrick php 类成功创建了一个 IPN (http://www.micahcarrick.com/php-paypal-ipn-integration-class.html) 一切正常,除了 我总是得到 pendign 付款状态,我无法得到确认。

我目前正在贝宝沙箱中测试它,我创建了 2 个买家和一个卖家,并且我已经为每个人启用了“付款审查”。

我也尝试了不同的方法,但我总是得到相同的结果。

代码: file_put_contents('ipn.log',"\n>IPN\n",FILE_APPEND);

//Check the Payment ID,i pass it to the IPN by GET
if(!isset($_GET['pid'])|| !is_numeric($_GET['pid']))
     file_put_contents('ipn.log',"\n!!!IPN:INVALID PID(".$_GET['pid'].")!!!\n",FILE_APPEND);
     exit('PID INVALIDO!');




//Logging errors
ini_set('log_errors', true);
ini_set('error_log', dirname(__FILE__).'/ipn_errors.log');

// instantiate the IpnListener class  
require('ipnlistener.php');
$listener = new IpnListener();      


//Use the sandbox instead of going "live"
$listener->use_sandbox = true;


//validate the request

try 
   $listener->requirePostMethod();
   $verified = $listener->processIpn();
 
catch (Exception $e) 
   error_log($e->getMessage());
   exit(0);



//Just for debug
file_put_contents('ipn.log',"\n###IPN:verifying...###\n",FILE_APPEND); 


if($verified)//the payment is verified                                                                           
        file_put_contents('ipn.log',"\n###IPN:transaction verified(confirmed=".$_POST['payment_status'].")###\n".$listener->getTextReport(),FILE_APPEND); 
        /*
        Once you have a verified IPN you need to do a few more checks on the POST
        fields--typically against data you stored in your database during when the
        end user made a purchase (such as in the "success" page on a web payments
        standard button). The fields PayPal recommends checking are:
        1. Check the $_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
        Since implementations on this varies, I will leave these checks out of this
        example and just send an email using the getTextReport() method to get all
        of the details about the IPN.
        */  
        if($_POST['payment_status']=="Completed")
                //--check if the price is right and enable the user media--
                confirm_payment($_GET['pid'],$_POST['payment_amount']);
                file_put_contents('ipn.log',"\n###IPN:Transaction completed###\n".$listener->getTextReport(),FILE_APPEND);    
                                                                                

 

else 
/*
An Invalid IPN *may* be caused by a fraudulent transaction attempt. It's
a good idea to have a developer or sys admin manually investigate any
invalid IPN.
*/

   file_put_contents('ipn.log',"\n###IPN:ERROR###\n".$listener->getTextReport(),FILE_APPEND);    


我创建的调试日志总是这样

> IPN ##IPN:verifying...### ##IPN:transaction encrypted(confirmed=Pending)

【问题讨论】:

【参考方案1】:

禁用付款审核。付款审核将始终将它们置于待处理状态。 这实际上就是重点。能够使用否定测试和付款审查来测试“否定”场景以验证您的错误处理。

【讨论】:

你是对的,我遵循了相反的指南;无论如何,没有人指定您必须创建一个“买家”帐户并将其电子邮件用作目的地(而不是您的 dev.paypal 电子邮件)。支付的价格也是 $_POST['mc_gross'] 而不是 cmets 中所说的 $_POST['payment_amount']。【参考方案2】:

我不熟悉您使用的课​​程,但这是我在所有工作中一直用于 PP IPN 的课程,它就像一种魅力,也许有一天我会制作自己的面向对象的方式,但现在这似乎可以解决问题,我希望它可以帮助你。 (只是为了让你走上正轨,我使用相同的文件来接收和传出 PP 的消息)

$sandbox="sandbox.";
$paypal_email="seller_XXXXX_biz@twbooster.com";

$item_id = "1XN12PJ";
$cost = "22.30";
$item_name = 'My Item';
$return_url = "http://www.example.com/return";
$cancel_url = "http://www.example.com/cancel";
$notify_url = "http://www.example.com/notify";

function check_txnid($tnxid)
    global $link;
    $sql = mysql_query("SELECT * FROM `payments_pending` WHERE `txnid` = '$tnxid'", $link);     
    return mysql_num_rows($sql)==0;


function check_price($price, $id)
    $sql = mysql_query("SELECT `cost` FROM `orders` WHERE `id` = '$id'");
    if (mysql_numrows($sql) != 0) 
        $row = mysql_fetch_array($sql);
        $num = (float) $row['cost'];
        if($num - $price == 0)
            return true;
        
    
    return false;


if (!isset($_POST["txn_id"]) && !isset($_POST["txn_type"]))    // Request TO Paypal
    // Firstly Append paypal account to querystring
    $querystring .= "?business=".urlencode($paypal_email)."&";  

    // Append amount& currency (£) to quersytring so it cannot be edited in html
    $querystring .= "lc=CA&";
    $querystring .= "currency_code=CAD&";
    $querystring .= "item_number=".$item_id."&";

    //The item name and amount can be brought in dynamically by querying the $_POST['item_number'] variable.
    $querystring .= "item_name=".urlencode($item_name)."&";
    $querystring .= "amount=".$cost."&";

    //loop for posted values and append to querystring
    foreach($_POST as $key => $value)
        $value = urlencode(stripslashes($value));
        $querystring .= "$key=$value&";
    

    // Append paypal configs
    $querystring .= "return=".urlencode(stripslashes($return_url))."&";
    $querystring .= "cancel_return=".urlencode(stripslashes($cancel_url))."&";
    $querystring .= "notify_url=".urlencode($notify_url);

    // Append querystring with custom field
    //$querystring .= "&custom=".USERID;

    // Redirect to paypal IPN
    header('location:https://www.'.$sandbox.'paypal.com/cgi-bin/webscr'.$querystring);
    exit();
else      // Response FROM Paypal
    // read the post from PayPal system and add 'cmd'
    $req = 'cmd=_notify-validate';
    foreach ($_POST as $key => $value) 
        $req .= "&$key=$value";
    

    // assign posted variables to local variables
    $data                       = array();
    $data['item_name']          = $_POST['item_name'];
    $data['item_number']        = $_POST['item_number'];
    $data['payment_status']     = $_POST['payment_status'];
    $data['payment_amount']     = $_POST['mc_gross'];
    $data['payment_currency']   = $_POST['mc_currency'];
    $data['txn_id']             = $_POST['txn_id'];
    $data['receiver_email']     = $_POST['receiver_email'];
    $data['payer_email']        = $_POST['payer_email'];
    $data['custom']             = $_POST['custom'];

    // post back to PayPal system to validate
    $header = "POST /cgi-bin/webscr HTTP/1.0\r\n";
    $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
    $header .= "Content-Length: " . strlen($req) . "\r\n\r\n";

    $fp = fsockopen ('ssl://www.'.$sandbox.'paypal.com', 443, $errno, $errstr, 30);
    if(!$fp)
        // HTTP ERROR : Do something to notify you
    
    else   
        fputs($fp, $header.$req);

        $res = "";
        while (!feof($fp))
            $res .= fgets($fp, 1024);
        

        if(strpos($res, "VERIFIED")!==false)
            // Validate payment (Check unique txnid & correct price)
            $valid_txnid = check_txnid($data['txn_id']);
            // $valid_price = check_price($data['payment_amount'], $data['item_number']);

            $valid_price = check_price($data['payment_amount'], $_POST['item_number']);
            // PAYMENT VALIDATED & VERIFIED!
            if($valid_txnid && $valid_price)
                $orderid = updatePayments($data);
                if($orderid)
                    // Payment has been made & successfully inserted into the Database

                else
                    // Error inserting into DB
                
            
            else                   
                // Payment made but data has been changed  : Do something to notify you
                                   
        
        else
            if(strpos($res, "VERIFIED")!==false)
                // PAYMENT INVALID & INVESTIGATE MANUALY!  : Do something to notify you
            
        
        fclose($fp);
       

【讨论】:

您不要检查交易状态是否已完成,因此恶意用户可以尝试使用未完成但已验证的付款来解锁某些媒体。至少 paypal 是这样说的:“因为 IPN 消息可以在交易进程的各个阶段发送,所以在启用商品发货或允许下载数字媒体之前,请确保交易的支付状态是‘完成’。”cms.paypal.com/us/cgi-bin/… 我认为这可以解决问题:if(strpos($res, "VERIFIED")!==false) VERIFIED 意味着 COMPLETED 不? (我可能错了,但我的脚本是基于其中一个贝宝教程:cms.paypal.com/cms_content/CA/en_US/files/developer/…) 不,这不正确。 VERIFIED 仅表示 IPN 消息是真实的,但它没有说明交易状态。

以上是关于PHP Paypal IPN:交易未确认的主要内容,如果未能解决你的问题,请参考以下文章

Paypal IPN自定义确认邮件

您如何将 Paypal IPN 确认连接到用户?

您是不是需要使用 IPN 和快速结帐来确认 PayPal 付款?

未使用发票 API 接收 PayPal IPN

Paypal IPN:如果我的听众在收到 IPN 后没有发回确认,会发生啥?

Paypal IPN 获得空白确认(应为“已验证”或“无效”)