【问题标题】:PayPal Smart Payment Buttons: Error: JSON.parse: unexpected character at line 1 column 1 of the JSON dataPayPal 智能支付按钮:错误:JSON.parse:JSON 数据的第 1 行第 1 列出现意外字符
【发布时间】:2020-06-07 07:48:31
【问题描述】:

我已经尝试解决这个问题 2 天了..

我想从 PayPal 实现智能支付按钮,严格按照解释的每一步操作,但仍然出现以下错误:

Error: JSON.parse: unexpected character at line 1 column 1 of the JSON data

我的 用于 Button 渲染的 JavaScript

paypal.Buttons({
        createOrder: function() {
            return fetch('vendor/paypal/paypal-checkout-sdk/samples/CaptureIntentExamples/CreateOrder.php', {
                method: 'post',
                headers: {
                    'content-type': 'application/json'
                }
            }).then(function(res) {
                return res.json();
            }).then(function(data) {
                return data.orderID; // Use the same key name for order ID on the client and server
            });
        },
        onApprove: function(data, actions) {
            // This function captures the funds from the transaction.
            return actions.order.capture().then(function(details) {
                // This function shows a transaction success message to your buyer.
                alert('Transaction completed by ' + details.payer.name.given_name);
            });
        },
        onError: function(err) {
            alert(err);
        }
    }).render('#paypal-button-container');

我的CreateOrder.php

namespace Sample\CaptureIntentExamples;

require __DIR__ . '/../../../../autoload.php';


use Sample\PayPalClient;
use PayPalCheckoutSdk\Orders\OrdersCreateRequest;

class CreateOrder
{

    /**
     * Setting up the JSON request body for creating the Order. The Intent in the
     * request body should be set as "CAPTURE" for capture intent flow.
     * 
     */
    private static function buildRequestBody()
    {
        return array(
            'intent' => 'CAPTURE',
            'application_context' =>
                array(
                    'return_url' => 'https://example.com/return',
                    'cancel_url' => 'https://example.com/cancel'
                ),
            'purchase_units' =>
                array(
                    0 =>
                        array(
                            'amount' =>
                                array(
                                    'currency_code' => 'USD',
                                    'value' => '220.00'
                                )
                        )
                )
        );
    }

    /**
     * This is the sample function which can be sued to create an order. It uses the
     * JSON body returned by buildRequestBody() to create an new Order.
     */
    public static function createOrder($debug=false)
    {
        $request = new OrdersCreateRequest();
        $request->headers["prefer"] = "return=representation";
        $request->body = self::buildRequestBody();

        $client = PayPalClient::client();
        $response = $client->execute($request);
        if ($debug)
        {
            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";
            }
            // To toggle printing the whole response body comment/uncomment below line
            echo json_encode($response->result, JSON_PRETTY_PRINT), "\n";
        }


        return $response;
    }
}

if (!count(debug_backtrace()))
{
    CreateOrder::createOrder(true);
}

它基本上都是从 PayPal 演练中复制而来的。 如果我直接访问 CreateOrder.php,它正在创建一个订单,我可以看到没有错误的响应。

Status Code: 201 Status: CREATED [...]

【问题讨论】:

  • 如果您在 Chrome 中查看响应,它可能会在控制台"SyntaxError: Unexpected token S in JSON 中告诉您,这是响应的第一个字母:“状态代码 ...”。我现在也有同样的问题。它正在尝试接收 JSON 文件,而它所接收的只是响应:Status Code: 201 Status: CREATED Order ID: ...

标签: javascript php json parsing paypal


【解决方案1】:

我所做的是删除以 txt 格式打印响应的代码部分。这就是您收到 JSON 语法错误的原因。

public static function createOrder($debug=false)
  {
    $request = new OrdersCreateRequest();
    $request->prefer('return=representation');
    $request->body = self::buildRequestBody();
   // 3. Call PayPal to set up a transaction
    $client = PayPalClient::client();
    $response = $client->execute($request);

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

    // 4. Return a successful response to the client.
    return $response;
  }

顺便说一句,这个答案很有帮助:https://stackoverflow.com/a/63019280/12208549

【讨论】:

  • 不幸的是,这对 m 没有作用:c
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-14
  • 2016-01-30
  • 2020-01-11
  • 2020-10-13
  • 2019-05-11
  • 1970-01-01
  • 2017-05-18
相关资源
最近更新 更多