2015-10-28 2 views
0

Когда у меня есть клиент, заказ Paypal, первый заказ проходит через штраф. Если они размещают другой заказ сразу же он даст эту ошибку:Ошибка PHP Paypal, когда клиент отправляет второй заказ на экспресс-проверку API

A successful transaction has already been completed for this token.

Любые идеи, как я могу очистить это так, что они могут поставить еще один заказ немедленно?

getExpressCheckout

function PPHttpPost($methodName_, $nvpStr_) { 


$API_UserName = PAYPAL_USER; 
$API_Password = PAYPAL_PASS; 
$API_Signature = PAYPAL_SIGNATURE; 
$version = PAYPAL_VERSION; 

$API_Endpoint = "https://api-3t.paypal.com/nvp"; 
if ("sandbox" === PAYPAL_ENVIRONMENT || "-sandbox" === PAYPAL_ENVIRONMENT) { 
    $API_Endpoint = "https://api-3t." . PAYPAL_ENVIRONMENT . ".paypal.com/nvp"; 
} 

//$version = urlencode('63.0'); 
// Set the curl parameters. 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $API_Endpoint); 
curl_setopt($ch, CURLOPT_VERBOSE, 1); 

// Turn off the server and peer verification (TrustManager Concept). 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); 

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_POST, 1); 

// Set the API operation, version, and API signature in the request. 
$nvpreq = "METHOD=$methodName_&VERSION=$version&PWD=$API_Password&USER=$API_UserName&SIGNATURE=$API_Signature$nvpStr_"; 

// Set the request as a POST FIELD for curl. 
curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq); 

// Get response from the server. 
$httpResponse = curl_exec($ch); 

if (!$httpResponse) { 
    exit('$methodName_ failed: ' . curl_error($ch) . '(' . curl_errno($ch) . ')'); 
} 

// Extract the response details. 
$httpResponseAr = explode("&", $httpResponse); 

$httpParsedResponseAr = array(); 
foreach ($httpResponseAr as $i => $value) { 
    $tmpAr = explode("=", $value); 
    if (sizeof($tmpAr) > 1) { 
     $httpParsedResponseAr[$tmpAr[0]] = $tmpAr[1]; 
    } 
} 

if ((0 == sizeof($httpParsedResponseAr)) || !array_key_exists('ACK', $httpParsedResponseAr)) { 
    exit("Invalid HTTP Response for POST request($nvpreq) to $API_Endpoint."); 
} 

return $httpParsedResponseAr; 
} 

// Obtain the token from PayPal. 
if (!array_key_exists('token', $_REQUEST)) { 
    exit('Token is not received.'); 
} 

// Set request-specific fields. 
$token = urlencode(htmlspecialchars($_REQUEST['token'])); 

// Add request-specific fields to the request string. 
$nvpStr = "&TOKEN=$token"; 

// Execute the API operation; see the PPHttpPost function above. 
$httpParsedResponseAr = PPHttpPost('GetExpressCheckoutDetails', $nvpStr); 

if ("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) { 
    // Extract the response details. 
    $payerID = $httpParsedResponseAr['PAYERID']; 
    $fname = $httpParsedResponseAr['FIRSTNAME']; 
    $lname = $httpParsedResponseAr['LASTNAME']; 
    $street1 = $httpParsedResponseAr["PAYMENTREQUEST_0_SHIPTOSTREET"]; 
    if (array_key_exists("PAYMENTREQUEST_0_SHIPTOSTREET2", $httpParsedResponseAr)) { 
     $street2 = $httpParsedResponseAr["PAYMENTREQUEST_0_SHIPTOSTREET2"]; 
    } 
    $city_name = $httpParsedResponseAr["PAYMENTREQUEST_0_SHIPTOCITY"]; 
    $state_province = $httpParsedResponseAr["PAYMENTREQUEST_0_SHIPTOSTATE"]; 
    $postal_code = $httpParsedResponseAr["PAYMENTREQUEST_0_SHIPTOZIP"]; 
    $country_code = $httpParsedResponseAr["PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE"]; 

// $_SESSION['st_fname'] = htmlspecialchars(urldecode($fname)); 
// $_SESSION['st_lname'] = htmlspecialchars(urldecode($lname)); 
// $_SESSION['st_address'] = htmlspecialchars(urldecode($street1)); 
// $_SESSION['st_address2'] = htmlspecialchars(urldecode($street2)); 
// $_SESSION['st_city'] = htmlspecialchars(urldecode($city_name)); 
// $_SESSION['st_state'] = htmlspecialchars(urldecode($state_province)); 
// $_SESSION['st_zip'] = htmlspecialchars(urldecode($postal_code)); 
    $_SESSION['pp_token'] = htmlspecialchars(urldecode($httpParsedResponseAr['TOKEN'])); 
    $_SESSION['pp_payerid'] = htmlspecialchars(urldecode($httpParsedResponseAr['PAYERID'])); 
    $_SESSION['pp_email'] = htmlspecialchars(urldecode($httpParsedResponseAr['EMAIL'])); 
    $_SESSION['pp_phone'] = htmlspecialchars(urldecode($httpParsedResponseAr['PHONE'])); 
    $_SESSION['paymentType'] = "paypal"; 





    //echo 'Get Express Checkout Details Completed Successfully: '.print_r($httpParsedResponseAr, true); 
    header('Location: ' . $path . '/paypal_do.php'); 
} else { 
    $_SESSION['cc_msg'] = "Paypal payment failed. Please try again"; 
    //print_r($httpParsedResponseAr); 
    header('Location: ' . $path . '/pay.php'); 

    //exit('GetExpressCheckoutDetails failed: ' . print_r($httpParsedResponseAr, true)); 
} 

SetExpressCheckout

function PPHttpPost($methodName_, $nvpStr_) { 



$API_UserName = PAYPAL_USER; 
$API_Password = PAYPAL_PASS; 
$API_Signature = PAYPAL_SIGNATURE; 
$version = PAYPAL_VERSION; 

$API_Endpoint = "https://api-3t.paypal.com/nvp"; 
if ("sandbox" === PAYPAL_ENVIRONMENT || "-sandbox" === PAYPAL_ENVIRONMENT) { 
    $API_Endpoint = "https://api-3t." . PAYPAL_ENVIRONMENT . ".paypal.com/nvp"; 
} 

//$version = urlencode('63.0'); 
// Set the curl parameters. 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $API_Endpoint); 
curl_setopt($ch, CURLOPT_VERBOSE, 1); 

// Turn off the server and peer verification (TrustManager Concept). 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); 

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_POST, 1); 

// Set the API operation, version, and API signature in the request. 
$nvpreq = "METHOD=$methodName_&VERSION=$version&PWD=$API_Password&USER=$API_UserName&SIGNATURE=$API_Signature$nvpStr_"; 

// Set the request as a POST FIELD for curl. 
curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq); 



// Get response from the server. 
$httpResponse = curl_exec($ch); 

if (!$httpResponse) { 
    exit("$methodName_ failed: " . curl_error($ch) . '(' . curl_errno($ch) . ')'); 
} 

// Extract the response details. 
$httpResponseAr = explode("&", $httpResponse); 

$httpParsedResponseAr = array(); 
foreach ($httpResponseAr as $i => $value) { 
    $tmpAr = explode("=", $value); 
    if (sizeof($tmpAr) > 1) { 
     $httpParsedResponseAr[$tmpAr[0]] = $tmpAr[1]; 
    } 
} 

if ((0 == sizeof($httpParsedResponseAr)) || !array_key_exists('ACK', $httpParsedResponseAr)) { 
    exit("Invalid HTTP Response for POST request($nvpreq) to $API_Endpoint."); 
} 

return $httpParsedResponseAr; 
} 

// Set request-specific fields. 

$paymentAmount = urlencode(number_format($_SESSION['grandTotal'], 2)); 
$currencyID = urlencode('USD');  // or other currency code ('GBP', 'EUR', 'JPY', 'CAD', 'AUD') 
$paymentType = urlencode('Sale'); // or 'Sale' or 'Order' 

$returnURL = urlencode($path . "/paypal_get.php"); 
$cancelURL = urlencode($path . "/pay.php"); 

/* 

    $sql = "SELECT * FROM cart WHERE session_id = '".session_id()."'"; 
    $result = mysql_query($sql) or die(mysql_error()); 
    $count = 0; 

    while($rows=mysql_fetch_array($result)){ 
    $sql = "SELECT * FROM products WHERE id = ".$rows['item_id']; 
    $results = mysql_query($sql); 
    $item_row = mysql_fetch_array($results); 

    $sql = "SELECT * FROM frame_options WHERE id = ".$rows['frame_id']; 
    $results = mysql_query($sql); 
    $item_frame = mysql_fetch_array($results); 

    //build the item row 
    $item = $item_row['width']." x ".$item_row['height']." ".$rows['finish_id']; 


    $nvpStr .= "&L_PAYMENTREQUEST_0_NAME".$count."=".$item; 
    $nvpStr .= "&L_PAYMENT_REQUEST_0_QTY".$count."=".$rows['qty']; 
    $nvpStr .= "&L_PAYMENT_REQUEST_0_AMT".$count."=".$rows['price']; 

    $count++; 

    } 
    if(isset($_SESSION['discount']) && $_SESSION['discount'] <> 0){ 
    $nvpStr .= "&L_PAYMENTREQUEST_0_NAME".$count."=Discount"; 
    $nvpStr .= "&L_PAYMENT_REQUEST_0_QTY".$count."=1"; 
    $nvpStr .= "&L_PAYMENT_REQUEST_0_AMT".$count."=-".$_SESSION['discount']; 
    } 

    //determine shipping cost 

    $sql = "SELECT * FROM shipping_options WHERE id = ".$_SESSION['shipping_option']; 
    $result = mysql_query($sql) or die(mysql_error()); 
    $shipping_row = mysql_fetch_array($result); 

    $paymentAmount = $paymentAmount - $shipping_rows['rate'] - $_SESSION['sales_tax']; 

    $nvpStr .= "&PAYMENTREQUEST_0_SHIPPINGAMT = ".$shipping_row['rate']; 

    $sql = "SELECT SUM(price) as itemTotal FROM cart WHERE session_id = '".session_id()."'"; 
    $result = mysql_query($sql) or die(mysql_error()); 
    $itemTotal_row = mysql_fetch_array($result); 
    $nvpStr .= "&PAYMENTREQUEST_0_ITEMAMT = ".$itemTotal_row['itemTotal']; 
*/ 
// Add request-specific fields to the request string. 
$nvpStr .= "&PAYMENTREQUEST_0_AMT=$paymentAmount&RETURNURL=$returnURL&CANCELURL=$cancelURL&PAYMENTREQUEST_0_PAYMENTACTION=$paymentType&CURRENCYCODE=$currencyID"; 
$nvpStr .= "&HDRIMG=" . $path . "/images/logo_white_background.png&useraction=commit"; 






echo $nvpStr; 



// Execute the API operation; see the PPHttpPost function above. 
$httpParsedResponseAr = PPHttpPost('SetExpressCheckout', $nvpStr); 


if ("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) { 
    // Redirect to paypal.com. 
    $token = urldecode($httpParsedResponseAr["TOKEN"]); 
    $payPalURL = "https://www.paypal.com/webscr&cmd=_express-checkout&token=$token&useraction=commit"; 
    if ("sandbox" === $environment || "-sandbox" === $environment) { 
     $payPalURL = "https://www.$environment.paypal.com/webscr&cmd=_express-checkout&token=$token"; 
    } 
    header("Location: $payPalURL"); 
    exit; 
} else { 
    exit('SetExpressCheckout failed: ' . print_r($httpParsedResponseAr, true)); 
} 

DoExpressCheckout

function PPHttpPost($methodName_, $nvpStr_) { 



$API_UserName = PAYPAL_USER; 
$API_Password = PAYPAL_PASS; 
$API_Signature = PAYPAL_SIGNATURE;  
$version = PAYPAL_VERSION; 

$API_Endpoint = "https://api-3t.paypal.com/nvp"; 
if ("sandbox" === PAYPAL_ENVIRONMENT || "-sandbox" === PAYPAL_ENVIRONMENT) { 
    $API_Endpoint = "https://api-3t." . PAYPAL_ENVIRONMENT . ".paypal.com/nvp"; 
} 

//$version = urlencode('63.0'); 

// setting the curl parameters. 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $API_Endpoint); 
curl_setopt($ch, CURLOPT_VERBOSE, 1); 

// Set the curl parameters. 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); 

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_POST, 1); 

// Set the API operation, version, and API signature in the request. 
$nvpreq = "METHOD=$methodName_&VERSION=$version&PWD=$API_Password&USER=$API_UserName&SIGNATURE=$API_Signature$nvpStr_"; 

// Set the request as a POST FIELD for curl. 
curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq); 

// Get response from the server. 
$httpResponse = curl_exec($ch); 

if (!$httpResponse) { 
    exit('$methodName_ failed: ' . curl_error($ch) . '(' . curl_errno($ch) . ')'); 
} 

// Extract the response details. 
$httpResponseAr = explode("&", $httpResponse); 

$httpParsedResponseAr = array(); 
foreach ($httpResponseAr as $i => $value) { 
    $tmpAr = explode("=", $value); 
    if (sizeof($tmpAr) > 1) { 
     $httpParsedResponseAr[$tmpAr[0]] = $tmpAr[1]; 
    } 
} 

if ((0 == sizeof($httpParsedResponseAr)) || !array_key_exists('ACK', $httpParsedResponseAr)) { 
    exit("Invalid HTTP Response for POST request($nvpreq) to $API_Endpoint."); 
} 

return $httpParsedResponseAr; 
} 

/** 
* This example assumes that a token was obtained from the SetExpressCheckout API call. 
* This example also assumes that a payerID was obtained from the SetExpressCheckout API call 
* or from the GetExpressCheckoutDetails API call. 
*/ 
// Set request-specific fields. 
$payerID = urlencode($_SESSION['pp_payerid']); 
$token = urlencode($_SESSION['pp_token']); 

$paymentType = urlencode("Sale"); // or 'Sale' or 'Order' 
$paymentAmount = urlencode(number_format($_SESSION['grandTotal'], 2)); 
$currencyID = urlencode("USD");  // or other currency code ('GBP', 'EUR', 'JPY', 'CAD', 'AUD') 
// Add request-specific fields to the request string. 
$nvpStr = "&TOKEN=$token&PAYERID=$payerID&PAYMENTACTION=$paymentType&AMT=$paymentAmount&CURRENCYCODE=$currencyID"; 

// Execute the API operation; see the PPHttpPost function above. 
$httpParsedResponseAr = PPHttpPost('DoExpressCheckoutPayment', $nvpStr); 


if ("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || 
     "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) { 
    $_SESSION['paypal_transaction_id'] = $httpParsedResponseAr['TRANSACTIONID']; 

    cartToOrder(); 


    redirect("order_confirmation.php"); 
    exit('Express Checkout Payment Completed Successfully: ' . print_r($httpParsedResponseAr, true)); 
} else { 
    exit('DoExpressCheckoutPayment failed: ' . print_r($httpParsedResponseAr, true)); 
} 
+0

Возможно, проблема заключается в том, чтобы добавить много продуктов за один сеанс, используя один токен? – Pavel

+0

Я бы порекомендовал вам рассмотреть вопрос о том, добавить ли вы код к этому вопросу? – Anders

+0

@pavel Я добавил код для трех шагов в экспресс-оплате PayPal, который я использую. Дайте мне знать, если вам нужно увидеть какой-либо другой код. – jcopeland

ответ

0

Во-первых, с одной лексем (на один запрос HTTP) у вас есть возможность создать одну сессию с продуктами. Если вы используете какой-либо метод API (DoExpressCheckoutPayment, CreateRecurringPaymentsProfile и т. Д.), Вы будете использовать этот токен! Другим вариантом является истечение времени текущего токена, но в этом случае сообщение об ошибке будет отличаться от «Успешная транзакция уже завершена для этого токена».

Поэтому вы должны снова использовать метод SetExpressCheckout API, чтобы получить еще один токен.

+0

Я использую другой SetExpressCheckout. Я завершаю процесс снова после каждого заказа. Возможно ли, что токен paypal сохраняется в сеансе и не перезаписывается вторым, поскольку он уже установлен? Я думаю, я мог бы просто очистить сессию для токена paypal, но я не думаю, что это имеет к этому какое-то отношение. – jcopeland

+0

Каждый токен связан с продуктами и деталями, которые были установлены с помощью метода SetExpressCheckout. Укажите код – Pavel