当前位置: 首页 > 知识库问答 >
问题:

PayPal PHP SDK:由于身份验证凭据无效或缺少授权标头,身份验证失败

冯鸿哲
2023-03-14
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, {...} 
{"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;
    }

}

共有1个答案

谭琛
2023-03-14

我仔细查看了日志文件,发现了错误:

{"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);
 类似资料:
  • 我对社交网络分析和twitter api是新手。我想收集关于特定主题的tweets。所以我写了下面的代码 在我的程序中,我需要在哪里提供凭据 谢谢

  • OAuth术语已经困扰我很久了。OAuth授权是像一些人建议的那样,还是认证? 如果我错了,请纠正我,但我一直认为授权是允许某人访问某个资源的行为,而OAuth似乎没有任何实际允许用户访问给定资源的实现。OAuth实现所讨论的都是为用户提供一个令牌(签名的,有时是加密的)。然后,每次调用都会将该令牌传递到后端服务endpoint,在后端服务endpoint上检查该令牌的有效性,这也不是OAuth的

  • 我正在使用谷歌应用程序引擎和谷歌数据存储。我正在使用谷歌图书馆 我的示例代码是: 我使用Spring靴和码头作为容器。 在本地,它工作正常,数据在谷歌数据存储中更新。 问题是当我部署应用程序到google-app-Engine,我得到下面的异常,当我得到datastore.put方法。 注意:在本地环境和google-app-Engine中,我定义了环境变量GOOGLE_APPLICATION_C

  • 我有一个已经完成的j2ee(jsf、cdi、jpa)应用程序,它完美地使用了ApacheShiro,它工作得非常好,我喜欢Shiro注释(hasRole、hasPermission等)。 现在,该项目还必须能够通过SiteMinder进行身份验证,我的问题是: 我如何设置一个领域来处理SiteMinder身份验证而不丢失Shiro授权(似乎SiteMinder会在HTTP头中给我用户名和Rolen