2013-09-03 2 views
1

Я изучаю функцию IPN Paypal, которая необходима срочно на этой неделе.Paypal php github пример кода всегда ошибка?

и я получил код PHP образца из: https://github.com/paypal/ipn-code-samples

я могу реально получить ПРОВЕРЕНО сообщение от песочницы. но в строке кода кода 79, начиная с

if (curl_errno($ch) != 0) // cURL error 

, как представляется, ошибка журнала, независимо от того, какой ответ. и я нахожу $ res хранит полный ответный заголовок вместо «VERIFIED» или «INVALID».

Я не знаю, является ли это моей собственной проблемой или проблемой кода.

Я могу получить последнее слово в $ res, чтобы сделать мою работу по внедрению, но действительно хотел бы объяснить некоторые эксперты. Спасибо!

<?php 

// CONFIG: Enable debug mode. This means we'll log requests into 'ipn.log' in the same directory. 
// Especially useful if you encounter network errors or other intermittent problems with IPN (validation). 
// Set this to 0 once you go live or don't require logging. 
define("DEBUG", 1); 

// Set to 0 once you're ready to go live 
define("USE_SANDBOX", 1); 


// 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. 
$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"; 
} 

// Post IPN data back to PayPal to validate the IPN data is genuine 
// Without this step anyone can fake IPN data 

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

// CONFIG: Optional proxy configuration 
//curl_setopt($ch, CURLOPT_PROXY, $proxy); 
//curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1); 

// Set TCP timeout to 30 seconds 
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close')); 

// CONFIG: Please download 'cacert.pem' from "http://curl.haxx.se/docs/caextract.html" and set the directory path 
// of the certificate as shown below. Ensure the file is readable by the webserver. 
// This is mandatory for some environments. 
// $cert = "./cacert.pem"; 
//curl_setopt($ch, CURLOPT_CAINFO, $cert); 

$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) . "\r\n", 3, "./ipn.log"); 
    } 
    curl_close($ch); 

} else { 
     // Unexpected error occured. We were able to connect to PayPal, but we didn't get INVALID or VERIFIED back. 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\r\n", 3, "./ipn.log"); 
      error_log(date('[Y-m-d H:i e] '). "HTTP response of validation request:". $res ."\r\n", 3, "./ipn.log"); 
     } 
     curl_close($ch); 
} 

// 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 PayPal email 
    // check that payment_amount/payment_currency are correct 
    // process payment and mark item as paid. 

    // 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']; 

    if(DEBUG == true) { 
     error_log(date('[Y-m-d H:i e] '). "Verified IPN: $req \r\n", 3, "./ipn.log"); 
    } 
} 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 \r\n", 3, "./ipn.log"); 
    } 
} 

?> 
+0

Можете ли вы добавить образец того, что он регистрирует? Предполагая, что вы установили DEBUG в true, вы должны получить сообщение об ошибке в файле журнала, будет ли это успешным или нет, и контент должен быть полезен. – andrewsi

ответ

0

Пример Paypal немного неуклюжий. Do обрабатывают ошибку не так, как вы говорите, но также и то, как построить «эхо» из запроса не так эффективно.

Это моя версия. Есть несколько особенностей Codeigniter, но вы можете использовать его в качестве примера тем не менее:

public function ipn_callback() 
{ 
    $IPN_url = config_item('paypal_ipn_url'); 

    // -------------------------------------------------------------------------------- 
    // Read POST data directly from $_POST causes serialization 
    // issues with array data in POST. Reading raw POST data from input stream instead. 
    // -------------------------------------------------------------------------------- 

    $req = 'cmd=_notify-validate&' . file_get_contents("php://input"); 

    $ch = curl_init($IPN_url); 
    if ($ch == FALSE) 
    { 
     log_message('error', "Problems opening IPN url: " . $IPN_url); 
     return FALSE; 
    } 
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); 
    curl_setopt($ch, CURLOPT_PORT, config_item('paypal_ipn_port')); 
    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_HEADER, 1); 
    curl_setopt($ch, CURLINFO_HEADER_OUT, 1); 
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); 
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close')); 

    // CONFIG: Optional proxy configuration 
    //curl_setopt($ch, CURLOPT_PROXY, $proxy); 
    //curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1); 

    // CONFIG: Please download 'cacert.pem' from "http://curl.haxx.se/docs/caextract.html" and set the directory path 
    // of the certificate as shown below. Ensure the file is readable by the webserver. 
    // This is mandatory for some environments. 
    // $cert = "./cacert.pem"; 
    //curl_setopt($ch, CURLOPT_CAINFO, $cert); 

    $res = curl_exec($ch); 
    if ($res === FALSE) 
    { 
     log_message('error', "Can't connect to PayPal to validate IPN message: " . curl_error($ch) ); 
     curl_close($ch); 
     return; 
    } 

    // ------------------------------------------------------- 
    // Inspect IPN validation result and act accordingly 
    // ------------------------------------------------------- 

    if (strrpos($res, "VERIFIED") !== FALSE) 
    { 
     try 
     { 
      // call the tnx_type handler, format: $this->ipn_<txn_type>($args) 
      if (call_user_func_array(array($this, 'ipn_' . $_POST[ 'txn_type' ]), array($_POST)) === FALSE) 
      { 
       throw new Exception("unsupported txn_type"); 
      } 
     } 
     catch(Exception $e) 
     { 
      log_message('error', "Unhandled IPN: " . $e->getMessage()); 
      log_message('error', $req); 
     } 
    } 
    else if (strrpos($res, "INVALID") !== FALSE) 
    { 
     log_message('error', "Invalid IPN: $req"); 
    } 
    else 
    { 
     // ------------------------------------------------------------------------------- 
     // Unexpected error occured. We were able to connect to PayPal, but we didn't get 
     // INVALID or VERIFIED back. Log the entire HTTP 
     // ------------------------------------------------------------------------------- 

     log_message('error', "HTTP request of validation request:" . curl_getinfo($ch, CURLINFO_HEADER_OUT) . " for IPN payload: $req"); 
     log_message('error', "HTTP response of validation request: $res"); 
    } 
    curl_close($ch); 
} 
+0

Я также использовал strrpos. Однако есть ли вероятность, что $ res будет содержать строки «VERIFIED» или «INVALID» в другом полевом содержимом, которое сделает проверку правильной? Теперь я использую глупый способ обрезать $ res из последних 7 символов: if (strcmp ($ str, "ERIFIED") == 0) – horizon1711

Смежные вопросы