Checkout-PHP-SDK和createOrder连接问题

Checkout-PHP-SDK and createOrder connection issue

尝试将 Checkout-PHP-SDK paypal API 实现为 createOrder JS call.As 据我所知,我必须将数据从 php 文件发送到js审批表。但是当我按下“PayPal Pay”按钮时出现错误。

JS代码如下:

 <div id="paypal-button-container"></div>
    <script>
         function loadAsync(url, callback) {
                            var s = document.createElement('script');
                            s.setAttribute('src', url); s.onload = callback;
                            document.head.insertBefore(s, document.head.firstElementChild);
                            }
                            // Usage -- callback is inlined here, but could be a named function
                            loadAsync('https://www.paypal.com/sdk/js?client-id=AQgUM6x3URK1A-rcNIq56covuc0CYGv3pb5sYeL6-cqsO1HYV2CV6h4ur6BCly_1YYd3-UOMTNGtwQXd&currency=USD&disable-funding=card', function() {
        paypal.Buttons({
            // Call your server to set up the transaction
            createOrder: function(data, actions) {
                return fetch('https://example.com/TESTS.php', {
                    method: 'post'
                }).then(function(res) {
                    return res.json();
                }).then(function(orderData) {
                    return orderData.id;
                });
            },
            // Call your server to finalize the transaction
            onApprove: function(data, actions) {
                return fetch('/demo/checkout/api/paypal/order/' + data.orderID + '/capture/', {
                    method: 'post'
                }).then(function(res) {
                    return res.json();
                }).then(function(orderData) {
                    //   (1) Recoverable INSTRUMENT_DECLINED -> call actions.restart()
                    //   (2) Other non-recoverable errors -> Show a failure message
                    //   (3) Successful transaction -> Show confirmation or thank you
                    // This example reads a v2/checkout/orders capture response, propagated from the server
                    // You could use a different API or structure for your 'orderData'
                    var errorDetail = Array.isArray(orderData.details) && orderData.details[0];
                    if (errorDetail && errorDetail.issue === 'INSTRUMENT_DECLINED') {
                        return actions.restart(); // Recoverable state, per:
                        // https://developer.paypal.com/docs/checkout/integration-features/funding-failure/
                    }
                    if (errorDetail) {
                        var msg = 'Sorry, your transaction could not be processed.';
                        if (errorDetail.description) msg += '\n\n' + errorDetail.description;
                        if (orderData.debug_id) msg += ' (' + orderData.debug_id + ')';
                        return alert(msg); // Show a failure message (try to avoid alerts in production environments)
                    }
                    // Successful capture! For demo purposes:
                    console.log('Capture result', orderData, JSON.stringify(orderData, null, 2));
                    var transaction = orderData.purchase_units[0].payments.captures[0];
                    alert('Transaction '+ transaction.status + ': ' + transaction.id + '\n\nSee console for all available details');
                    // Replace the above to show a success message within this page, e.g.
                    // const element = document.getElementById('paypal-button-container');
                    // element.innerHTML = '';
                    // element.innerHTML = '<h3>Thank you for your payment!</h3>';
                    // Or go to another URL:  actions.redirect('thank_you.html');
                });
            }

        }).render('#paypal-button-container');
    })  
    </script>

php文件是这样的:

     <?php  
        
        use PayPalCheckoutSdk\Orders\OrdersCreateRequest;
        use PayPalCheckoutSdk\Core\PayPalHttpClient;
        use PayPalCheckoutSdk\Core\SandboxEnvironment;
        use PayPalCheckoutSdk\Orders\OrdersCaptureRequest;
        
        require __DIR__ . '/Checkout-PHP-SDK-develop/vendor/autoload.php';
        // Creating an environment
        $clientId = "AQgUM7x3URK1A-rcNIq56covuc0CYGv3pb5sYeL6-cqsO1HYV2CV6h4ur6BCly_1YYd3-UOMTNGtwQXd";
        $clientSecret = "EDm88hmcFd6arhd7vaJ6d9AWjIvCScR6E6s0eM3OKqwf1uZt0G0KlLNUXG057vesyXR4eYP3RKDLJBz8";
        
        $environment = new SandboxEnvironment($clientId, $clientSecret);
        $client = new PayPalHttpClient($environment);
        
        $request = new OrdersCreateRequest();
        $request->prefer('return=representation');
        $request->body = [
                             "intent" => "CAPTURE",
                             "purchase_units" => [[
                                 //"reference_id" => "test_ref_id1",
                                 "amount" => [
                                     "value" => "100.00",
                                     "currency_code" => "USD"
                                 ]
                             ]],
                             "application_context" => [
                                  "cancel_url" => "https://example.com/cancelled",
                                  "return_url" => "https://example.com/success"
                             ] 
                         ];
        try {
            $response = $client->execute($request);
            print_r($response);
        }catch (HttpException $ex) {
          // echo $ex->statusCode;
            print_r($ex->getMessage());
        }
   if(isset($_POST['id'])) {
    
$od_id = $response->result->id;
//echo $od_id;
$request1 = new OrdersCaptureRequest($od_id);
$request1->prefer('return=representation');
try {
    // Call API with your client and get a response for your call
    $response1 = json_encode($client->execute($request1));
    return $response1;
     // If call returns body in response, you can get the deserialized version from the result attribute of the response
   return $request1;
}catch (HttpException $ex) {
    echo $ex->statusCode;
   // print_r($ex->getMessage());
}
}

我应该在 php 文件中创建并捕获订单,然后将其发送给 JS 吗?实际上这是发送数据的正确方法吗?任何帮助将不胜感激。谢谢。

我已将 CAPTURE 方法添加到 php 文件中。现在它看起来像上面。

您的每个路由(创建路由和捕获路由)都必须 return 一个 JSON 字符串的响应,并且没有其他文本或 HTML。 print_r不合适。