使用REST PHP的PayPal返回错误400

时间:2013-11-28 00:46:03

标签: php rest paypal

我在PHP中使用REST API尝试创建PayPal购买,但每次运行时我只会收到一个通用的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

1 个答案:

答案 0 :(得分:2)

我遇到了同样的问题,但最终通过捕获Exception而不是PPConnectionException(根据欺骗我们两个的SDK示例代码)揭示了根本原因。一旦我这样做,我就可以转储异常细节,这些细节显示PayPal抱怨我的交易金额没有正确格式化 - 我在小数点后只有一位数。查看上面的代码,情况可能并非如此,但更改异常处理程序应该可以快速揭示真正的问题。

您将来可能也容易受到其他值的格式问题的影响,您可以使用以下方法解决这些问题:

money_format('%!i', $amount)