Checkout-PHP-SDK 和 createOrder 连接问题

发布于 2025-01-16 18:55:06 字数 6547 浏览 1 评论 0原文

尝试实现 Checkout-PHP-SDK paypal API 来 createOrder JS 调用。据我所知,我必须将数据从 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文件中。现在看起来像上面一样。

Trying to implement the Checkout-PHP-SDK paypal API to createOrder JS call.As far as I understand I have to send the data from php file to js approval form. But I am getting an error when I press the "PayPal Pay" button.

The JS codes are like below :

 <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¤cy=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>

The php file is like this :

     <?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());
}
}

Should I create, and catch the order in php file and then send it to JS? Actually is it the proper way to send the data? Any help would be highly appreciated. Thanks.

enter image description here

I have added CAPTURE method to the php file. and now it looks like above.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

可遇━不可求 2025-01-23 18:55:06

每个路由(创建路由和捕获路由)都必须返回 JSON 字符串形式的响应,不得返回任何其他文本或 HTML。 print_r 不适合。

Each of your routes (the create route, and the capture route) must return a response that is a JSON string, and no other text nor HTML. print_r is not suitable.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文