我正在学习PayPal SDK,当我第一次使用一个产品时,它工作得很好。现在我要处理一组产品。代码
$paypal = new ApiContext(
new OAuthTokenCredential(
'...',
'...'
)
);
$payer = new Payer();
$payer->setPaymentMethod('paypal');
$shipping = 2;
$totalPriceWithShipping = 0;
$totalPriceWithoutShipping = 0;
$items = [];
foreach(Controller::getData('productsInCart') as $product)
{
$totalPriceWithShipping += ($product->price + $shipping);
$totalPriceWithoutShipping += $product->price;
$item = new Item();
$item->setName($product->name)
->setPrice($product->price)
->setCurrency('USD')
->setQuantity(1);
$items[] = $item;
}
$itemList = new ItemList();
$itemList->setItems($items);
$details = new Details();
$details->setShipping($shipping)
->setSubtotal($totalPriceWithoutShipping);
$amount = new Amount();
$amount->setCurrency('USD')
->setTotal($totalPriceWithShipping)
->setDetails($details);
$transaction = new Transaction();
$transaction->setItemList($itemList)
->setAmount($amount)
->setDescription('Your Order from Online Shop')
->setInvoiceNumber(uniqid());
$redirectUrls = new RedirectUrls();
$redirectUrls->setReturnUrl('...')
->setCancelUrl('...');
$payment = new Payment();
$payment->setIntent('sale')
->setPayer($payer)
->setRedirectUrls($redirectUrls)
->setTransactions([$transaction]);
try {
$payment->create($paypal);
}
catch(Exception $e) {
die($e->getTrace());
}
die($payment->getApprovalLink());
但是我得到了这个错误:
你可以看一下$items array 条目数组美元致命错误:在C:'dev'htdocs'Shop'vendor' PayPal' rest-api-sdk-php'lib'PayPal'Core'PayPalHttpConnection.php:180 Stack trace: #0 C:'dev'htdocs'Shop'vendor' PayPal' rest-api-sdk-php'lib'PayPal'Transport'PayPalRestCall.php(74)中未捕获异常'PayPal' exception 'PayPalConnectionException'与消息'访问https://api.sandbox.paypal.com/v1/payments/payment时获得Http响应代码400 ':PayPal'Core'PayPalHttpConnection->execute('{"intent":"sale…')#1 C:'dev'htdocs'Shop'vendor' PayPal' rest-api-sdk-php'lib'PayPal'Common'PayPalResourceModel.php(102): PayPal'Transport'PayPalRestCall->execute(Array, '/v1/payments/pa…', 'POST', '{"intent":"sale…"', NULL) #2 C:'dev'htdocs'Shop'vendor'paypal'rest-api-sdk-php'lib' paypal' Api'Payment.php(422): paypal' Common'PayPalResourceModel::executeCall('/v1/payments/pa…', 'POST', '{"intent":"sale…"', NULL, Object(PayPal'Rest'ApiContext), NULL) #3 C:'dev'htdocs'Shop'app'controllers'CartController.php(183): PayPal'Api'Payment->create(Object(PayPal'Rest'ApiContext)) #4 [C中的内部函数:'dev'htdocs'Shop'vendor' PayPal'Rest - Api -sdk-php'lib'PayPal'Core'PayPalHttpConnection.php on line 180
获得400异常意味着,paypal正在返回一些异常。获取有关该异常的更多细节。您需要捕获未捕获的异常PayPal'Exception'PayPalConnectionException
以获得更多细节。
这个页面应该可以帮助你给出一些想法。下面是捕获该异常的示例代码:
try {
$payment->create($apiContext);
} catch (PayPal'Exception'PayPalConnectionException $ex) {
echo $ex->getCode(); // Prints the Error Code
echo $ex->getData(); // Prints the detailed error message
die($ex);
} catch (Exception $ex) {
die($ex);
}