简体   繁体   English

支付成功完成后,Paypal IPN 发送无效响应

[英]Paypal IPN sends invalid response after successful payment completion

First thing first, Language: PHP Framework: Code Igniter首先,语言:PHP 框架:Code Igniter

This is the first time I'm implementing PayPal payment in my website so that users can pay from their PayPal accounts to the owner.这是我第一次在我的网站上实施 PayPal 付款,以便用户可以从他们的 PayPal 帐户向所有者付款。 Obviously.明显地。

Tutorial I followed for implementing PayPal payment is here .我遵循的实现 PayPal 付款的教程在这里 And for implementing IPN listener, I used this code.为了实现 IPN 侦听器,我使用了这段代码。 I wrote IPN listener in core php and it's a standalone file (no relation with codeigniter framework or website).我在核心 php 中编写了 IPN 侦听器,它是一个独立文件(与 codeigniter 框架或网站无关)。 A cron job makes this file run 24x7. cron 作业使该文件 24x7 运行。 I thought that's necessary but not quite sure.我认为这是必要的,但不太确定。 So IPN listener listens every time and whenever PayPal sends an IPN, it takes the data from POST and checks the verification.因此,IPN 侦听器每次都会侦听,每当 PayPal 发送 IPN 时,它都会从 POST 中获取数据并检查验证。 If it is verified, it write the POST data to database and log a file accordingly.如果验证通过,它将 POST 数据写入数据库并相应地记录一个文件。

This whole things was already a mess and I think I made it worse.整个事情已经一团糟,我想我把事情弄得更糟了。

My IPN listener is:我的 IPN 侦听器是:

<?php
require_once 'Query.php';
define("DEBUG", 1);

define("USE_SANDBOX", 1);
define("LOG_FILE", "./ipn.log");
$raw_post_data = str_replace('=utf-8', '=UTF-8', 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';

foreach ($myPost as $key => $value) 
{
        $value = urlencode(stripslashes($value));
    $req .= "&$key=$value";
}
if(USE_SANDBOX == true) {
    $paypal_url = "https://www.sandbox.paypal.com/cgi-bin/webscr";
} else {
    $paypal_url = "https://www.paypal.com/cgi-bin/webscr";
}
$ch = curl_init($paypal_url);
if ($ch == FALSE) {
    return FALSE;
}
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);
if(DEBUG == true) {
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLINFO_HEADER_OUT, 1);
}

curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));
$res = curl_exec($ch);
if (curl_errno($ch) != 0) // cURL error
    {
    if(DEBUG == true) { 
        error_log(date('[Y-m-d H:i e] '). "Can't connect to PayPal to validate IPN message: " . curl_error($ch) . PHP_EOL, 3, LOG_FILE);
    }
    curl_close($ch);
    exit;
} else {
        // Log the entire HTTP response if debug is switched on.
        if(DEBUG == true) {
            error_log(date('[Y-m-d H:i e] '). "HTTP request of validation request:". curl_getinfo($ch, CURLINFO_HEADER_OUT) ." for IPN payload: $req" . PHP_EOL, 3, LOG_FILE);
            error_log(date('[Y-m-d H:i e] '). "HTTP response of validation request: $res" . PHP_EOL, 3, LOG_FILE);
        }
        curl_close($ch);
}
// Inspect IPN validation result and act accordingly
// Split response headers and payload, a better way for strcmp
$tokens = explode("\r\n\r\n", trim($res));
$res = trim(end($tokens));


if (strcmp ($res, "VERIFIED") == 0) {

        $user_id = $_POST['custom'];
        $product_id = $_POST["item_number"];
        $txn_id = $_POST["txn_id"];
        $payment_gross = $_POST["mc_gross"];
        $currency_code = $_POST["mc_currency"];
        $payer_email = $_POST["payer_email"];
        $payment_status = $_POST["payment_status"];     


       $qry2="INSERT INTO payments(user_id,product_id,txn_id,payment_gross,currency_code,payer_email,payment_status) VALUES(".$user_id.",".$product_id.",'".$txn_id."',".$payment_gross.",'".$currency_code."','".$payer_email."','".$payment_status."')"   ;
      setData($qry2);   



    if(DEBUG == true) {
        error_log(date('[Y-m-d H:i e] '). "Verified IPN: $req ". PHP_EOL, 3, LOG_FILE);
    }
} else if (strcmp ($res, "INVALID") == 0) {
    // log for manual investigation
    // Add business logic here which deals with invalid IPN messages
    if(DEBUG == true) {
        error_log(date('[Y-m-d H:i e] '). "Invalid IPN: $req" . PHP_EOL, 3, LOG_FILE);
    }
}
?>

What I'm trying to say here is , if the condition if (strcmp ($res, "VERIFIED") == 0) is true, then only database write operation occurs and then I write to a log file using this error_log(date('[Ymd H:ie] '). "Verified IPN: $req ". PHP_EOL, 3, LOG_FILE);我在这里想说的是,如果条件if (strcmp ($res, "VERIFIED") == 0)为真,则只发生数据库写入操作,然后我使用此error_log(date('[Ymd H:ie] '). "Verified IPN: $req ". PHP_EOL, 3, LOG_FILE);

I checked my log file and try to do a search for Verified IPN but couldn't find anything.我检查了我的日志文件并尝试搜索Verified IPN但找不到任何内容。 Here is my IPN log.这是我的 IPN 日志。

[2016-03-07 05:41 UTC] HTTP request of validation request:POST /cgi-bin/webscr HTTP/1.1
Host: www.sandbox.paypal.com
Accept: */*
Connection: Close
Content-Length: 20
Content-Type: application/x-www-form-urlencoded

 for IPN payload: cmd=_notify-validate
[2016-03-07 05:41 UTC] HTTP response of validation request: HTTP/1.1 200 OK
Date: Mon, 07 Mar 2016 05:41:03 GMT
Server: Apache
X-Frame-Options: SAMEORIGIN
Set-Cookie: c9MWDuvPtT9GIMyPc3jwol1VSlO=WKlHKpJ3laas07Yu1WCXQPNlPGNpVTmx79in33FVjVu-1QcqQ1BKO2BLcO-ltHCgRNg4BYmHLqdIeaKPMYLdWqa1qP3eqTtCdlN-erDGl_NuifHufy7yejBynYZJS7W8xkoFUHBVW5eQocb6f3uGTwoVGpYBHeWXRejcU1o37sflJyynvgzkWMzHuvsG7pS9t19ZcqfrldHnv8pYpTXlBa4UeWbyuEVWiyuTVhBDE_UlA1L7E-Ho8J-rui0BFKqOHVsalakqcz9xP1XbyfIjb2hLrtpDDFmkqNqTs2ibxlGO-EjNhcJG1boI06ISlT4Dg0ZfGPlthPobrKZ0aS59OCOTaGOYReArBWqdDZXWq0tDwI8uIJwMaFT9w0fproQ5167v1nWS6QIZYnXmeZCO40Ss93NQW2OTeLRaKx-1e92aGSL3uxSq_YdE5Dm; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: cookie_check=yes; expires=Thu, 05-Mar-2026 05:41:03 GMT; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: navcmd=_notify-validate; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: navlns=0.0; expires=Wed, 07-Mar-2018 05:41:03 GMT; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: Apache=10.72.108.11.1457329263101875; path=/; expires=Wed, 28-Feb-46 05:41:03 GMT
Vary: Accept-Encoding,User-Agent
Connection: close
HTTP_X_PP_AZ_LOCATOR: sandbox.slc
Paypal-Debug-Id: d4da8be813fa0
Set-Cookie: X-PP-SILOVER=name%3DSANDBOX3.WEB.1%26silo_version%3D1880%26app%3Dappdispatcher%26TIME%3D1863638358; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: X-PP-SILOVER=; Expires=Thu, 01 Jan 1970 00:00:01 GMT
Strict-Transport-Security: max-age=14400
Transfer-Encoding: chunked
Content-Type: text/html; charset=UTF-8

INVALID
[2016-03-07 05:41 UTC] Invalid IPN: cmd=_notify-validate
[2016-03-07 05:42 UTC] HTTP request of validation request:POST /cgi-bin/webscr HTTP/1.1
Host: www.sandbox.paypal.com
Accept: */*
Connection: Close
Content-Length: 20
Content-Type: application/x-www-form-urlencoded

 for IPN payload: cmd=_notify-validate
[2016-03-07 05:42 UTC] HTTP response of validation request: HTTP/1.1 200 OK
Date: Mon, 07 Mar 2016 05:42:02 GMT
Server: Apache
X-Frame-Options: SAMEORIGIN
Set-Cookie: c9MWDuvPtT9GIMyPc3jwol1VSlO=f8rnnKoWpS27ajK43K_vGgiHMCbyL0kxcaLbl_qXj8X0JLk-LbcHgcR3owKzLqj_MJu_uo7CX7WOoie45aYro6IcO7wJJlXCvHm90MzDnGfwXjHYddOtovs9ZRpPcmiQ2o7Rxw6UhyVsaQ3stNXCFJ2RXouWssYRY8YTDST6VyVJWdtPzSIe24BebKqH2B1jbPOt_VJ1xhLRb_fmVpR6CB4ScN9fhgNdkyueDqEfp3o-xbT-VzHbfuTdSR3p2vvKKAVFBOs7ooDFmIylSOkxNkrBhvR2UwkGcpOo9HOBYWpqkfn2TlLBW6W1PpKSGnzY5M8TxaA-a1HtkKVMQ6TN4vyc46B7Ekps0ZLO3vtt9arFvvscgRMxOPGcQvwsGYrGHQv4Vyv_m47hrRRojf-yBdmebyhugsUKYSBjUSPiFDi5Ozg2inODpq0o0vC; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: cookie_check=yes; expires=Thu, 05-Mar-2026 05:42:03 GMT; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: navcmd=_notify-validate; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: navlns=0.0; expires=Wed, 07-Mar-2018 05:42:03 GMT; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: Apache=10.72.108.11.1457329322876295; path=/; expires=Wed, 28-Feb-46 05:42:02 GMT
Vary: Accept-Encoding,User-Agent
Connection: close
HTTP_X_PP_AZ_LOCATOR: sandbox.slc
Paypal-Debug-Id: ec94240d19c4
Set-Cookie: X-PP-SILOVER=name%3DSANDBOX3.WEB.1%26silo_version%3D1880%26app%3Dappdispatcher%26TIME%3D2853494102; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: X-PP-SILOVER=; Expires=Thu, 01 Jan 1970 00:00:01 GMT
Strict-Transport-Security: max-age=14400
Transfer-Encoding: chunked
Content-Type: text/html; charset=UTF-8

INVALID
[2016-03-07 05:42 UTC] Invalid IPN: cmd=_notify-validate
[2016-03-07 05:43 UTC] HTTP request of validation request:POST /cgi-bin/webscr HTTP/1.1
Host: www.sandbox.paypal.com
Accept: */*
Connection: Close
Content-Length: 20
Content-Type: application/x-www-form-urlencoded

 for IPN payload: cmd=_notify-validate
[2016-03-07 05:43 UTC] HTTP response of validation request: HTTP/1.1 200 OK
Date: Mon, 07 Mar 2016 05:43:02 GMT
Server: Apache
X-Frame-Options: SAMEORIGIN
Set-Cookie: c9MWDuvPtT9GIMyPc3jwol1VSlO=qFIftmj81M9XVbnGK-_ZFd_plIa-_hITqhkt7tHsSgU2hJnYg1P7b2xqdRFTOWeXIJnXWMBBwbAOFwF1azF07vQ_StCVY9SfONsm83OIv3S8WCTk9ekaXS6owbCFW4qVLtyDKxaKfNkLU576_BYmAFXULVJ3pAkLeGFUkzNC9kjY5ouHRKu3bzO7eSHrRpgQHnBQdoI6NcTHh697bQfeGAfFYpMIXDbYHEiSpaKm22v0j7hS4A_nntlaxbwrrRoZtZmTuoJdQNKF3wS26pJJkM4zYWpdY8xP21vISCk9sAAQjIOZCspps1tTjsXhDI4nYUZeJNjqG8xshBqB_lFweeqCQQC17MEivchn19F32ojFh--lfsp3cZA9YY34RBjxL1TnY-owkzw9n3qHpn-tnVP6--DgtJ-H3AqF0Q6QS3gCFam3tlNd5TEi9z0; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: cookie_check=yes; expires=Thu, 05-Mar-2026 05:43:03 GMT; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: navcmd=_notify-validate; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: navlns=0.0; expires=Wed, 07-Mar-2018 05:43:03 GMT; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: Apache=10.72.108.11.1457329382840458; path=/; expires=Wed, 28-Feb-46 05:43:02 GMT
Vary: Accept-Encoding,User-Agent
Connection: close
HTTP_X_PP_AZ_LOCATOR: sandbox.slc
Paypal-Debug-Id: 8ad4234c9398
Set-Cookie: X-PP-SILOVER=name%3DSANDBOX3.WEB.1%26silo_version%3D1880%26app%3Dappdispatcher%26TIME%3D3860127062; domain=.paypal.com; path=/; Secure; HttpOnly
Set-Cookie: X-PP-SILOVER=; Expires=Thu, 01 Jan 1970 00:00:01 GMT
Strict-Transport-Security: max-age=14400
Transfer-Encoding: chunked
Content-Type: text/html; charset=UTF-8

INVALID
[2016-03-07 05:43 UTC] Invalid IPN: cmd=_notify-validate

There's nothing like ' Verified ' in it and log file has ' INVALID ' in it that means没有像“ Verified ”这样的东西,日志文件中有“ INVALID ”,这意味着

error_log(date('[Y-m-d H:i e] '). "Invalid IPN: $req" . PHP_EOL, 3, LOG_FILE);

this function gets executed.这个函数被执行。 BUT DATA IS WRITTEN INTO DATABASE ALSO.但数据也写入数据库。

I don't what's wrong here.我不知道这里有什么问题。 Can anyone point out the mistakes?任何人都可以指出错误吗? Should I take any additional security measures?我应该采取任何额外的安全措施吗? Thanks.谢谢。 Gracias.格拉西亚斯。

public function success()
            {
                if(isset($_GET['tx']))
                {
                    $tx = $_GET['tx'];
                    $result=$this->verifyWithPayPal($tx);

                   // $this->load->view('success',$result);
                }
            } 
public function verifyWithPayPal($tx)
            {
               // $tx = $_REQUEST['tx'];     
                $token = $this->config->item('authtokan');   
                $paypal_url = $this->config->item('posturl').'?cmd=_notify-synch&tx='. $tx.'&at='.$token;

                $curl= curl_init($paypal_url);
                $data=array(
                           "cmd"=>"_notify-synch",
                           "tx"=>$tx,
                           "at"=>$token
                       );
                $data_string=json_encode($data);
                curl_setopt($curl,CURLOPT_HEADER, 0);
                curl_setopt($curl,CURLOPT_POST, 1);
                curl_setopt($curl,CURLOPT_POSTFIELDS,$data_string);
                curl_setopt($curl,CURLOPT_SSL_VERIFYPEER, 0);
                curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
                $headers= array(
                    'Content-Type:application/x-www-form-urlencoded',
                    'Host: www.sandbox.paypal.com',
                    'Connection: close'
                );
                curl_setopt($curl,CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_1_1);
                curl_setopt($curl,CURLOPT_HTTPHEADER, $headers);
                $response= curl_exec($curl);

                $lines= explode("\n", $response);

                $keyarray = array();
                if(strcmp($lines[0],"SUCCESS")==0){
                    for($i=1;$i<count($lines)-1; $i++){
                        list($key,$val)=explode("=",$lines[$i]);
                        $keyarray[urldecode($key)]=urldecode($val);
                    }

                    $this->getListProducts($keyarray); 
                }  

            }      

public function getListProducts($result)
            {
             $i=1;
            $data = array();

        //        echo "<pre>";
        //        print_r($result);
        //        echo "</pre>";

                foreach($result as $key => $value)
                {
                    if(0===strpos($key,'item_number')){
                        $product = array(
                            'first_name'           => $result['first_name'],
                            'last_name'            => $result['last_name'],
                            'receiver_email'       => $result['receiver_email'],
                            'txn_type'             => $result['txn_type'], 
                            'txn_id'               => $result['txn_id'],
                            'payment_date'         => $result['payment_date'],
                            'payer_id'             => $result['payer_id'],                   
                            'payer_email'          => $result['payer_email'],
                            'address_street'       => $result['address_street'],
                            'address_zip'          => $result['address_zip'],
                            'address_status'       => $result['address_status'],
                            'address_country_code' => $result['address_country_code'],
                            'address_name'         => $result['address_name'],
                            'address_country'      => $result['address_country'],
                            'address_city'         => $result['address_city'],
                            'address_state'        => $result['address_state'],  
                            'receiver_id'          => $result['receiver_id'],
                            'receiver_email'       => $result['receiver_email'],
                            'item_number'          => $result['item_number1'],
                            'item_name'            => $result['item_name1'],
                            'quantity'             => $result['quantity1'],
                            'mc_currency'          => $result['mc_currency'],
                            'mc_fee'               => $result['mc_fee'],
                            'mc_gross'             => $result['mc_gross_1'],
                            'payment_gross'        => $result['payment_gross']                
                        );

                $this->load->model('mdl_order');
                $this->mdl_order->insert_record($product);  
             //   echo "alert<script>successfully Transaction</script>";
                if(isset($product)){
                        //echo 'hello';                       
                        $time=$this->session->userdata('last_time');
                       // echo $time;
                        //$data=array( $time=$this->session->userdata('last_time'));
                        $this->load->model('mdl_order');
                        $this->mdl_order->update($time);
                        echo "success update";

                }
//                redirect('manage_order'); 
                $this->load->view('success',$product);
                }
            }      
            return $data;  
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM