2013-11-28 71 views
3

我在PHP中使用REST API嘗試創建PayPal購買,但每次運行它時我只會得到一個通用400錯誤。顯然這意味着不好的要求,但幾乎沒有給出任何細節。這裏是我的代碼的主要部分:PayPal與REST PHP返回錯誤400

define("PP_CONFIG_PATH", "../vendor/"); 

$apiContext = new ApiContext(new OAuthTokenCredential('-redacted-', '-redacted-')); // id, secret 

$addr = new Address(); 
$addr->setLine1($_POST['addr1']); 
if(isset($_POST['addr2']) && !empty($_POST['addr2'])) $addr->setLine2($_POST['addr2']); 
$addr->setCity($_POST['city']); 
$addr->setCountry_code($_POST['country']); 
$addr->setPostal_code($_POST['zip']); 
$addr->setState($_POST['state']); 
$addr->setPhone('9179261285'); // TODO put in actual phone 

$card = new CreditCard(); 
$card->setNumber($_POST['card_num']); 
$card->setExpire_month($_POST['expire_mon']); 
$card->setExpire_year($_POST['expire_yr']); 
$card->setCvv2($_POST['cvv2']); 
$card->setFirst_name($_GET['fname']); 
$card->setLast_name($_GET['lname']); 
$card->setBilling_address($addr); 

$fi = new FundingInstrument(); 
$fi->setCredit_card($card); 

$payer = new Payer(); 
$payer->setPayment_method('credit_card'); 
$payer->setFunding_instruments(array($fi)); 

$cost = $_POST['plan'] == 1 ? '19.95' : '29.95'; 

$amountDetails = new AmountDetails(); 
$amountDetails->setSubtotal($cost); 
$amountDetails->setTax('0.00'); 
$amountDetails->setShipping('0.00'); 

$amount = new Amount(); 
$amount->setCurrency('USD'); 
$amount->setTotal($cost); 
$amount->setDetails($amountDetails); 

$transaction = new Transaction(); 
$transaction->setAmount($amount); 
$transaction->setDescription('MyTrustCo membership subscription.'); 

$payment = new Payment(); 
$payment->setIntent('sale'); 
$payment->setPayer($payer); 
$payment->setTransactions(array($transaction)); 

try { 
    $response = $payment->create($apiContext); 
} catch (PPConnectionException $e) { 
    echo "<br />exception:<br />" . $e->getMessage() . "<br />"; 
} 

echo "response: " . $response; 
die(); 

代碼輸出的最後一部分:

exception: 
Got Http response code 400 when accessing https://api.sandbox.paypal.com/v1/payments/payment. 
got response 
response: 

我不知道這可能是導致此錯誤。我正在按照這個教程:https://developer.paypal.com/webapps/developer/docs/api/#create-a-payment

+0

當然,如果你能告訴我一個樣品轉儲是什麼,以及如何獲得一。 – Greg

+0

他確實在輸出中提供了轉儲。我有同樣的錯誤,但它是一個404,而這是唯一被返回的東西。 – cj5

+0

目前我自己也有同樣的問題(獲得400迴應)。有人發現了這個原因嗎? –

回答

2

我有同樣的問題,但最終通過捕獲異常而不是PPConnectionException(根據欺騙我們兩個的SDK示例代碼)發現的根本原因。一旦我這樣做了,我就可以拋出異常詳細信息,顯示PayPal抱怨我的交易金額格式不正確 - 小數點後我只有一位數字。看看上面的代碼,這可能不是這種情況,但更改異常處理程序應該很快顯示出真正的問題。

你也可能受到其它相關數據的格式問題,但在未來,你可以用下面的解析:

money_format('%!i', $amount) 
相關問題