繁体   English   中英

PayPal 智能按钮和 REST Checkout SDK - SyntaxError: Unexpected end of JSON input OR 期望传递订单 ID

[英]PayPal Smart Buttons and REST Checkout SDK - SyntaxError: Unexpected end of JSON input OR Expected an order id to be passed

我正在尝试使用REST checkout SDK并使用服务器端调用 API 来实现 PayPal 的智能按钮。

但是我createOrder部分有一些问题。

JS代码:

paypal.Buttons({
    style: {
        size: 'responsive',
        layout: 'vertical'
    },
    createOrder: function() {
        return fetch(blm_custom_vars.wp_home + 'classes/paypal/paypal-create-order.php', {
            method: 'post',
            headers: {
                'content-type': 'application/json'
            }
        }).then(function(res) {
            return res.json();
        }).then(function(data) {
            return data.id;
        });
    },
    onApprove: function(data) {
        return fetch(blm_custom_vars.wp_home + 'classes/paypal/paypal-capture-order.php', {
            method: 'post',
            headers: {
                'content-type': 'application/json'
            },
            body: JSON.stringify({
                orderID: data.id
            })
        }).then(function(res) {
            return res.json();
        }).then(function(details) {
            alert('Transaction funds captured from ' + details.payer_given_name);
        })
    },
}).render('.purchase-modal');

paypal-create-order.php 中的 PHP 代码

namespace Sample\CaptureIntentExamples;

require(__DIR__ . '/paypal-client.php');

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

class CreateOrder {

    /**
     * This is the sample function to create an order. It uses the
     * JSON body returned by buildRequestBody() to create an order.
     */

    public static function createOrder($debug = false) {

        $request = new OrdersCreateRequest();
        $request->prefer('return=representation');
        $request->body = self::buildRequestBody();

        // Call PayPal to set up a transaction
        $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 print the whole response body, uncomment the following line
             echo json_encode($response->result, JSON_PRETTY_PRINT);

        }

        return $response;

    }

    /**
     * Setting up the JSON request body for creating the order with minimum request body. The intent in the
     * request body should be "AUTHORIZE" for authorize intent flow.
     *
     */

    private static function buildRequestBody() {

        return array(
            'intent' => 'CAPTURE',
            'application_context' =>
                array(
                    'shipping_preference' => 'NO_SHIPPING',
                    'user_action' => 'PAY_NOW',
                    'payment_method' => array(
                        'payee_preferred' => 'IMMEDIATE_PAYMENT_REQUIRED',
                    ),
                    //'custom_id' => '',
                    'return_url' => 'https://example.com/return',
                    'cancel_url' => 'https://example.com/cancel'
                ),
            'purchase_units' => array(
                    0 => array(
                            'amount' => array(
                                    'currency_code' => 'AUD',
                                    'value' => '70.00',
                                    'breakdown' => array(
                                        'item_total' => array(
                                            'currency_code' => 'AUD',
                                            'value' => '75.00',
                                        ),
                                        'discount' => array(
                                            'currency_code' => 'AUD',
                                            'value' => '5.00',
                                        ),
                                    ),
                            ),
                            'description' => 'something',
                            'items' => array(
                                0 => array(
                                    'name' => 'something',
                                    'unit_amount' => array(
                                        'currency_code' => 'AUD',
                                        'value' => '75.00',
                                    ),
                                    'quantity' => 1,
                                    'category' => 'DIGITAL_GOODS',
                                ),
                            ),
                    )
            )
        );

    }

}


/**
 * This is the driver function that invokes the createOrder function to create
 * a sample order.
 */

$debug = (ACTIVE_SERVER == 'dev') ? true : false;

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

现在,当我有$debug = true ,服务器输出似乎是正确的响应。 没有什么好看的。 虽然我必须关闭调试以避免其他 JSON 错误。

所以一旦我关闭它,我就会收到错误消息:

语法错误:JSON 输入意外结束

我想这是因为它是一个空页面,因为createOrder脚本返回数据而不是输出数据? 但这就是PayPal所说的。

所以我尝试将其更改为: echo json_encode($response); 然后我又犯了一个错误:

期望传递订单 ID

在 JS 中,我最初有这个:

}).then(function(data) {
    return data.orderID;
});

...但随后意识到从createOrder脚本返回的数组引用了id而不是orderID所以我将其更改为return data.id; 但它没有帮助。

我在这里做错了什么?

只需确保您正在回显/返回整个响应,或者至少包含{"id":"......"}

您可以在浏览器的 Dev Tools Network 选项卡中查看发生了什么。

所以从 PHP,做:

echo json_encode($response->result, JSON_PRETTY_PRINT);

..应该没问题,但是在 $debug=true if 块之下/之外,并且在它上面或周围没有任何其他打印或回显行,因为您必须输出有效的 JSON,并且只输出有效的 JSON(对于执行 createOrder fetch 的 JS到您的服务器以便能够解析它)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM