Skip to content
Advertisement

Checkout-PHP-SDK and createOrder connection issue

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&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 += 'nn' + 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 + 'nnSee 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 PayPalCheckoutSdkOrdersOrdersCreateRequest;
        use PayPalCheckoutSdkCorePayPalHttpClient;
        use PayPalCheckoutSdkCoreSandboxEnvironment;
        use PayPalCheckoutSdkOrdersOrdersCaptureRequest;
        
        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.

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement