PayPal Checkout 示例代码错误:位置 0 处 JSON 中的意外令牌 <

Posted

技术标签:

【中文标题】PayPal Checkout 示例代码错误:位置 0 处 JSON 中的意外令牌 <【英文标题】:PayPal Checkout example code error: Unexpected token < in JSON at position 0 【发布时间】:2020-05-08 00:06:13 【问题描述】:

这是我从https://developer.paypal.com/docs/checkout/integrate/获得的代码

 <script
                src="https://www.paypal.com/sdk/js?client-id=<?= $paypalID; ?>&currency=GBP"> 
              </script>

              <div id="paypal-button-container"></div>

              <script>



                paypal.Buttons(
                    createOrder: function(data, actions) 
                      // This function sets up the details of the transaction, including the amount and line item details.
                      return actions.order.create(
                        purchase_units: [
                          amount: 

                            "value": "<?= $grandTotalOP; ?>"
                          
                        ]
                      );
                    ,
                    onApprove: function(data) 
                        console.log(data);

                        var theBody = 'orderID' : data.orderID;
                        theBody = JSON.stringify(theBody);

                      return fetch('/capture-paypal-transaction', 
                        headers: 
                          'content-type': 'application/json'
                        ,
                        method: "POST",
                        body: theBody
                      ).then(function(res) 
                         console.log('test');
                         console.log(res);
                        return res.json();
                      ).then(function(details) 
                        alert('Transaction funds captured from ' + details.payer_given_name);
                      )
                    
                  ).render('#paypal-button-container');

              </script>

我在控制台中收到此错误

js?client-id=AaLa1ylO5YjAUByNm_epTAh3MDAmQ0o9UAoqGdPy2kgS-syd8KbJIcmk8QYpAeE99ZzgEnOfaPdoYfGe&currency=GBP:1 未捕获的 SyntaxError:意外的标记

错误:JSON 中位置 0 处的意外标记 https://www.paypal.com/sdk/js?client-id=AaLa1ylO5YjAUByNm_epTAh3MDAmQ0o9UAoqGdPy2kgS-syd8KbJIcmk8QYpAeE99ZzgEnOfaPdoYfGe&currency=GBP:1:295788) 在对象。 (https://www.paypal.com/sdk/js?client-id=AaLa1ylO5YjAUByNm_epTAh3MDAmQ0o9UAoqGdPy2kgS-syd8KbJIcmk8QYpAeE99ZzgEnOfaPdoYfGe&currency=GBP:1:302957) 在 JSON.parse() 在 o (https://www.paypal.com/sdk/js?client-id=AaLa1ylO5YjAUByNm_epTAh3MDAmQ0o9UAoqGdPy2kgS-syd8KbJIcmk8QYpAeE99ZzgEnOfaPdoYfGe&currency=GBP:1:302816) 在 WR (https://www.paypal.com/sdk/js?client-id=AaLa1ylO5YjAUByNm_epTAh3MDAmQ0o9UAoqGdPy2kgS-syd8KbJIcmk8QYpAeE99ZzgEnOfaPdoYfGe&currency=GBP:1:302969) 在 Ir.l.on (https://www.paypal.com/sdk/js?client-id=AaLa1ylO5YjAUByNm_epTAh3MDAmQ0o9UAoqGdPy2kgS-syd8KbJIcmk8QYpAeE99ZzgEnOfaPdoYfGe&currency=GBP:1:307996) 在红外 (https://www.paypal.com/sdk/js?client-id=AaLa1ylO5YjAUByNm_epTAh3MDAmQ0o9UAoqGdPy2kgS-syd8KbJIcmk8QYpAeE99ZzgEnOfaPdoYfGe&currency=GBP:1:308185) 在https://www.paypal.com/sdk/js?client-id=AaLa1ylO5YjAUByNm_epTAh3MDAmQ0o9UAoqGdPy2kgS-syd8KbJIcmk8QYpAeE99ZzgEnOfaPdoYfGe&currency=GBP:1:313190 在https://www.paypal.com/sdk/js?client-id=AaLa1ylO5YjAUByNm_epTAh3MDAmQ0o9UAoqGdPy2kgS-syd8KbJIcmk8QYpAeE99ZzgEnOfaPdoYfGe&currency=GBP:1:313236

错误:JSON 中位置 0 处的意外标记 https://www.paypal.com/sdk/js?client-id=AaLa1ylO5YjAUByNm_epTAh3MDAmQ0o9UAoqGdPy2kgS-syd8KbJIcmk8QYpAeE99ZzgEnOfaPdoYfGe&currency=GBP:1:295788) 在阵列。 (https://www.paypal.com/sdk/js?client-id=AaLa1ylO5YjAUByNm_epTAh3MDAmQ0o9UAoqGdPy2kgS-syd8KbJIcmk8QYpAeE99ZzgEnOfaPdoYfGe&currency=GBP:1:302957) 在 JSON.parse() 在 o (https://www.paypal.com/sdk/js?client-id=AaLa1ylO5YjAUByNm_epTAh3MDAmQ0o9UAoqGdPy2kgS-syd8KbJIcmk8QYpAeE99ZzgEnOfaPdoYfGe&currency=GBP:1:302816) 在 WR (https://www.paypal.com/sdk/js?client-id=AaLa1ylO5YjAUByNm_epTAh3MDAmQ0o9UAoqGdPy2kgS-syd8KbJIcmk8QYpAeE99ZzgEnOfaPdoYfGe&currency=GBP:1:302969) 在 Ir.l.on (https://www.paypal.com/sdk/js?client-id=AaLa1ylO5YjAUByNm_epTAh3MDAmQ0o9UAoqGdPy2kgS-syd8KbJIcmk8QYpAeE99ZzgEnOfaPdoYfGe&currency=GBP:1:307996) 在红外 (https://www.paypal.com/sdk/js?client-id=AaLa1ylO5YjAUByNm_epTAh3MDAmQ0o9UAoqGdPy2kgS-syd8KbJIcmk8QYpAeE99ZzgEnOfaPdoYfGe&currency=GBP:1:308185) 在https://www.paypal.com/sdk/js?client-id=AaLa1ylO5YjAUByNm_epTAh3MDAmQ0o9UAoqGdPy2kgS-syd8KbJIcmk8QYpAeE99ZzgEnOfaPdoYfGe&currency=GBP:1:313190 在https://www.paypal.com/sdk/js?client-id=AaLa1ylO5YjAUByNm_epTAh3MDAmQ0o9UAoqGdPy2kgS-syd8KbJIcmk8QYpAeE99ZzgEnOfaPdoYfGe&currency=GBP:1:313236

这是来自服务器的响应

致命错误未捕获的 PayPalHttp\HttpException: “错误”:“无效客户端”,“错误描述”:“客户端 身份验证失败" in /home/MYSERVER/public/vendor/paypal/paypalhttp/lib/PayPalHttp/HttpClient.php:215 堆栈跟踪: #0 /home/MYSERVER/public/vendor/paypal/paypalhttp/lib/PayPalHttp/HttpClient.php(100): PayPalHttp\HttpClient->parseResponse(对象(PayPalHttp\Curl)) #1 /home/MYSERVER/public/vendor/paypal/paypal-checkout-sdk/lib/PayPalCheckoutSdk/Core/AuthorizationInjector.php(37): PayPalHttp\HttpClient->执行(对象(PayPalCheckoutSdk\Core\AccessTokenRequest)) #2 /home/MYSERVER/public/vendor/paypal/paypal-checkout-sdk/lib/PayPalCheckoutSdk/Core/AuthorizationInjector.php(29): PayPalCheckoutSdk\Core\AuthorizationInjector->fetchAccessToken() #3 /home/MYSERVER/public/vendor/paypal/paypalhttp/lib/PayPalHttp/HttpClient.php(64): PayPalCheckoutSdk\Core\AuthorizationInjector->inject(对象(PayPalCheckoutSdk\Orders\OrdersGetRequest)) #4 /home/MYSERVER/public/public/capture-paypal-transaction.php(23): PayPalHttp\HttpClient- in /home/MYSERVER/public/vendor/paypal/paypalhttp/lib/PayPalHttp/HttpClient.php 上线 215

这是从顶部的 paypal 文档链接中获取的服务器代码

  <?php

namespace Sample;

require_once '/home/MYSERVER/public/vendor/autoload.php'; 

//1. Import the PayPal SDK client that was created in `Set up Server-Side SDK`.
use Sample\PayPalClient;
use PayPalCheckoutSdk\Orders\OrdersGetRequest;

class GetOrder


  // 2. Set up your server to receive a call from the client
  /**
   *You can use this function to retrieve an order by passing order ID as an argument.
   */
  public static function getOrder($orderId)
  

    // 3. Call PayPal to get the transaction details
    $client = PayPalClient::client();
    $response = $client->execute(new OrdersGetRequest($orderId));
    /**
     *Enable the following line to print complete response as JSON.
     */
    //print json_encode($response->result);
    print "Status Code: $response->statusCode\n";
    print "Status: $response->result->status\n";
    print "Order ID: $response->result->id\n";
    print "Intent: $response->result->intent\n";
    print "Links:\n";
    foreach($response->result->links as $link)
    
      print "\t$link->rel: $link->href\tCall Type: $link->method\n";
    
    // 4. Save the transaction in your database. Implement logic to save transaction to your database for future reference.
    print "Gross Amount: $response->result->purchase_units[0]->amount->currency_code $response->result->purchase_units[0]->amount->value\n";

    // To print the whole response body, uncomment the following line
    // echo json_encode($response->result, JSON_PRETTY_PRINT);
  


/**
 *This driver function invokes the getOrder function to retrieve
 *sample order details.
 *
 *To get the correct order ID, this sample uses createOrder to create a new order
 *and then uses the newly-created order ID with GetOrder.
 */

if (!count(debug_backtrace()))

  GetOrder::getOrder('REPLACE-WITH-ORDER-ID', true);

?>

【问题讨论】:

这是您的主要错误:"error":"invalid_client","error_description":"Client Authentication failed" 您需要进行一些调试以缩小原因。 感谢@PatrickQ 发布后我确实弄清楚了,但我现在有点不确定如何调试它......我还在想......我真的希望这里有人能得到答案.从我的角度来看,服务器端脚本不正确。我需要进一步查看文档,但这里肯定有人可以为我指明正确的方向??? 服务器脚本中肯定会有我应该放置客户端密码的地方吗? 我不相信 invalid_client 错误是主要错误。 “ @FeelsUnique 我们可能需要查看您的PayPalClient 课程。另外,您能否在网络检查器中显示对https://www.paypal.com/sdk/js?client-id=AaLa1ylO5YjAUByNm_epTAh3MDAmQ0o9UAoqGdPy2kgS-syd8KbJIcmk8QYpAeE99ZzgEnOfaPdoYfGe&amp;currency=GBP的请求的响应 【参考方案1】:

这就是解决办法

<?php

namespace Sample;

require_once '/home/server/public/vendor/autoload.php'; 

//1. Import the PayPal SDK client that was created in `Set up Server-Side SDK`.
use Sample\PayPalClient;
use PayPalCheckoutSdk\Orders\OrdersGetRequest;
use PayPalCheckoutSdk\Core\PayPalHttpClient;
use PayPalCheckoutSdk\Core\SandboxEnvironment;


ini_set('error_reporting', E_ALL); // or error_reporting(E_ALL);
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');

class PayPalClient

    /**
     * Returns PayPal HTTP client instance with environment that has access
     * credentials context. Use this instance to invoke PayPal APIs, provided the
     * credentials have access.
     */
    public static function client()
    
        return new PayPalHttpClient(self::environment());
    

    /**
     * Set up and return PayPal PHP SDK environment with PayPal access credentials.
     * This sample uses SandboxEnvironment. In production, use LiveEnvironment.
     */
    public static function environment()
    
        $clientId = getenv("CLIENT_ID") ?: "CLIENT_ID-here";
        $clientSecret = getenv("CLIENT_SECRET") ?: "CLIENT_SECRET-here";
        return new SandboxEnvironment($clientId, $clientSecret);
    



class GetOrder


  // 2. Set up your server to receive a call from the client
  /**
   *You can use this function to retrieve an order by passing order ID as an argument.
   */
  public static function getOrder($orderId)
  

    echo "testtttt ".$orderId;
    // 3. Call PayPal to get the transaction details
    $client = PayPalClient::client();
    $response = $client->execute(new OrdersGetRequest($orderId));
    /**
     *Enable the following line to print complete response as JSON.
     */
    print json_encode($response->result);
    print "Status Code: $response->statusCode\n";
    print "Status: $response->result->status\n";
    print "Order ID: $response->result->id\n";
    print "Intent: $response->result->intent\n";
    print "Links:\n";
    foreach($response->result->links as $link)
    
      print "\t$link->rel: $link->href\tCall Type: $link->method\n";
    
    // 4. Save the transaction in your database. Implement logic to save transaction to your database for future reference.
    print "Gross Amount: $response->result->purchase_units[0]->amount->currency_code $response->result->purchase_units[0]->amount->value\n";

    // To print the whole response body, uncomment the following line
    // echo json_encode($response->result, JSON_PRETTY_PRINT);
  


/**
 *This driver function invokes the getOrder function to retrieve
 *sample order details.
 *
 *To get the correct order ID, this sample uses createOrder to create a new order
 *and then uses the newly-created order ID with GetOrder.
 */
$request_body = file_get_contents('php://input');
$data = json_decode($request_body);
print_r($data);
echo 'order id = '.$data->orderID;
if (!count(debug_backtrace()))

  GetOrder::getOrder($data->orderID, true);

?>

【讨论】:

以上是关于PayPal Checkout 示例代码错误:位置 0 处 JSON 中的意外令牌 <的主要内容,如果未能解决你的问题,请参考以下文章

HTML 中用于 PayPal Express Checkout 的数字商品的示例代码或演示? [关闭]

PHP 支付中的 Paypal API Express Checkout 错误代码 13113

paypal checkout.js 检查错误交易

PayPal Express Checkout - 错误 400 错误请求

Flutter webview PayPal 输入错误?

Paypal API - checkout.js - 解析响应错误