PayPal PHP SDK:由于身份验证凭据无效或缺少授权标头,身份验证失败
2019-01-20
11808
我是 PayPal SDK 的新手,正在尝试在 Laravel 应用程序中使用 PayPal Checkout SDK。
我已按照以下 github 页面 中的大部分说明进行操作,第一次调用 create-payment 函数似乎有效;但是,当我在 PayPal 弹出窗口上按下继续来执行交易时,它会失败并产生以下错误:
Error: Request to post /api/execute-payment failed with 500 error. Correlation id: unknown
{
"message": "Got Http response code 400 when accessing https://api.sandbox.paypal.com/v1/payments/payment/PAY-3RB62059V6076291ALRCHT6Y/execute.",
"exception": "PayPal\\Exception\\PayPalConnectionException",
"file": "C:\\websites\\online-webstore\\vendor\\paypal\\rest-api-sdk-php\\lib\\PayPal\\Core\\PayPalHttpConnection.php",
"line": 207, {...}
检查链接: https://api.sandbox.paypal.com/v1/payments/payment/PAY-3RB62059V6076291ALRCHT6Y/execute ,我收到错误:
{"name":"AUTHENTICATION_FAILURE","message":"Authentication failed due to invalid authentication credentials or a missing Authorization header.","links":[{"href":"https://developer.paypal.com/docs/api/overview/#error","rel":"information_link"}]}
这是我的设置,因此对于客户端:
<script src="https://www.paypalobjects.com/api/checkout.js"></script>
<div id="paypal-button"></div>
<script>
paypal.Button.render({
env: 'sandbox', // Or 'production'
// Set up the payment:
// 1. Add a payment callback
payment: function(data, actions) {
// 2. Make a request to your server
return actions.request.post('/api/create-payment')
.then(function(res) {
// 3. Return res.id from the response
return res.id;
});
},
// Execute the payment:
// 1. Add an onAuthorize callback
onAuthorize: function(data, actions) {
// 2. Make a request to your server
return actions.request.post('/api/execute-payment', {
paymentID: data.paymentID,
payerID: data.payerID
})
.then(function(res) {
console.log(res);
alert('PAYMENT WENT THROUGH!!');
}).catch(function(err){
console.log("Error "+err);
});
}
}, '#paypal-button');
</script>
在我的控制器中设置如下所以:
class CheckoutController extends Controller
{
private $apiContext;
private $client_id;
private $secret;
public function __construct()
{
$this->middleware('auth', ['except'=>['createPayment', 'executePayment']]);
// Detect if we are running in live mode or sandbox
if(config('paypal.settings.mode') == 'live'){
$this->client_id = config('paypal.live_client_id');
$this->secret = config('paypal.live_secret');
} else {
$this->client_id = config('paypal.sandbox_client_id');
$this->secret = config('paypal.sandbox_secret');
}
// Set the Paypal API Context/Credentials
$this->apiContext = new ApiContext(new OAuthTokenCredential($this->client_id, $this->secret));
$this->apiContext->setConfig(config('paypal.settings'));
}
public function createPayment () {
$payer = new Payer();
$payer->setPaymentMethod("paypal");
$item1 = new Item();
$item1->setName('Ground Coffee 40 oz')
->setCurrency('USD')
->setQuantity(1)
->setSku("123123") // Similar to `item_number` in Classic API
->setPrice(7.5);
$item2 = new Item();
$item2->setName('Granola bars')
->setCurrency('USD')
->setQuantity(5)
->setSku("321321") // Similar to `item_number` in Classic API
->setPrice(2);
$itemList = new ItemList();
$itemList->setItems(array($item1, $item2));
$details = new Details();
$details->setShipping(1.2)
->setTax(1.3)
->setSubtotal(17.50);
$amount = new Amount();
$amount->setCurrency("USD")
->setTotal(20)
->setDetails($details);
$transaction = new Transaction();
$transaction->setAmount($amount)
->setItemList($itemList)
->setDescription("Payment description")
->setInvoiceNumber(uniqid());
$baseUrl = \URL::to('/');
$redirectUrls = new RedirectUrls();
$redirectUrls->setReturnUrl("http://online-webstore/paypalRedirect/true")
->setCancelUrl("http://online-webstore/paypalRedirect/false");
$payment = new Payment();
$payment->setIntent("sale")
->setPayer($payer)
->setRedirectUrls($redirectUrls)
->setTransactions(array($transaction));
$request = clone $payment;
try {
$payment->create($this->apiContext);
} catch (Exception $ex) {
exit(1);
}
$approvalUrl = $payment->getApprovalLink();
return $payment;
}
public function executePayment (Request $request) {
$paymentId = $request->paymentID;
$payment = Payment::get($paymentId, $this->apiContext);
$execution = new PaymentExecution();
$execution->setPayerId($request->PayerID);
try {
$result = $payment->execute($execution, $this->apiContext);
} catch (PayPal\Exception\PayPalConnectionException $ex) {
echo $ex->getData(); // Prints the detailed error message
die($ex);
}
return $result;
}
}
我还正确地将我的凭证包含在我的 .env 文件中,并在沙盒模式下运行它。
有人可以告诉我哪里可能出错了,如果需要,我很乐意提供更多信息。
2个回答
我仔细查看了日志文件并注意到了错误:
{"name":"VALIDATION_ERROR","details":[{"field":"payer_id","issue":"Payer ID is invalid"}],"message":"Invalid request - see details","information_link":"https://developer.paypal.com/docs/api/payments/#errors","debug_id":"81885e7bbe957"}
结果发现我的代码中有一个轻微的拼写错误:
$execution->setPayerId($request->PayerID);
它实际上应该是:
$execution->setPayerId($request->payerID);
Coder123
2019-01-20
您必须检查您的 CLIENT_SECRET 和 CLIENT_ID 。就我而言,这是错误的,这就是我遇到此错误的原因,但是当我更改这些密钥时,它工作正常。检查
Sajeed Kannoje
2022-01-21