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

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

刘凡
2023-03-14

这是我从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?客户id=aala1ylo5yjaubynmeptah3mdaq0o9uaoqgdpy2kgs-syd8kbjicmk8qypaee99zzgenopodoge

错误:意外的令牌

错误:意外的令牌

这是服务器的回复

在/home/MYSERVER/public/vendor/paypal/PayPalHttp/lib/PayPalHttp/HttpClient中出现致命错误Uncaught PayPalHttp\HttpException:{“错误”:“无效的客户端”,“错误描述”:“客户端身份验证失败”。php:215堆栈跟踪:#0/home/MYSERVER/public/vendor/paypal/paypalhttp/lib/paypalhttp/HttpClient。php(100):PayPalHttp\HttpClient-

下面是服务器代码,取自顶部的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);
}
?>

共有1个答案

公良天逸
2023-03-14

这就是解决办法

<?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);
}
?>
 类似资料:
  • 问题内容: 在处理类似于Facebook的内容提要的React应用程序组件中,我遇到了一个错误: Feed.js:94未定义的“ parsererror”“ SyntaxError:JSON中位置0处的意外令牌< 我遇到了一个类似的错误,事实证明这是render函数中HTML的错字,但这里似乎并非如此。 更令人困惑的是,我将代码回滚到了较早的已知工作版本,但仍然出现错误。 Feed.js: 在Ch

  • 我用的是Angular 5.0.0。我想连接。但是,当您启动应用程序时,就会发生错误。

  • 问题内容: 我已使用php脚本(save-data.php)将数据成功保存到json文件中,但无法使用get-data.php脚本正确获取数据。 错误消息: angular.js : 12520语法 错误: Object.parse(本地)位置0处的JSON中的意外令牌< save-data.php : get-data.php : save-data.json : 样品控制器 : 编辑:我不需要

  • 我有一个问题是“在位置0处的JSON中未预期的令牌#”。 我想做的是在FireBase上使用CloudFunction删除FirebaseUser。 没有返回,但错误显示“存在意外的json令牌#” null null null 代码执行(活动)的结果是成功的,但实际上没有改变任何东西 错误

  • 我在Ionic 2“syntaxerror:uncurrent token 下面是我的Spring Boot代码。 [{“ID”:1,“用户名”:“donald@yahoo.com”,“策略”:“v121293031”,“名称”:“唐纳德”,“移动”:“0504735260”,“电子邮件”:“dcgatan@gmail.com”,“地址”:“Dafza dubai”,“金额”:800.98,“da

  • 问题内容: 在处理类似于Facebook的内容提要的React应用程序组件中,我遇到了一个错误: Feed.js:94未定义“ parsererror”“ SyntaxError:JSON中位置0处的意外令牌< 我遇到了类似的错误,事实证明这是render函数中HTML的错字,但这里似乎并非如此。 更令人困惑的是,我将代码回滚到了较早的已知工作版本,但仍然遇到错误。 Feed.js: 在Chrom