'Send data when the purchase is complete in PayPal (onApprove)

I am trying to send the data to another php file where I could check and save data into my database when onApprove has been completed :

 <script>
                                // Render the PayPal button into #paypal-button-container
                                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=test&currency=USD&disable-funding=card', function() {
                            paypal.Buttons({
                                // Set up the transaction
                                createOrder: function(data, actions) {
                                    return actions.order.create({
                                        purchase_units: [{
                                            amount: {
                                                value: <?echo $cart->getCartTotal(true)?>
                                             
                                            }
                                        }]
                                    });
                                },
                                // Finalize the transaction
                                      onApprove: function(data, actions) {
            // show loader on screen whilst wating to redirect
            $('.checkout-loader').addClass('active');
            
            // excute php script
            var EXECUTE_URL = 'https://example.com/TESTS.php?success='+success;
            // Authorize the transaction
            actions.order.capture().then(function(details) {
                // Call your server to validate and capture the transaction
                return fetch(EXECUTE_URL, {
                    method: 'post',
                    headers: {
                        'content-type': 'application/json'
                    },
                    body: JSON.stringify({
                        orderID     : data.orderID,
                        success : "okaysuc"
                    })
                }).then(function(response){
                    // redirect to the completed page if paid
                    window.location.href = '/success/' + data.orderID;
                });
            });
        }
    }).render('#paypal-button-container');
                            });
                            </script>

And my TESTS.php :

<?php  
$retour = $_POST['success']; //I have tried json_decode() also, didnt work....
$db->query("INSERT INTO mydbname(order_id) VALUES ('$retour')");   //empty data is added to databse  
$cart = new Cart();
if($retour == 'okaysuc'){
//my code goes here.. But not works because data is empty. it is not sent. 
}
?>

Everything works except the POSTed variables. I don't know how to send the datas to another php file. Does somebody know where is the mistake ? I have tried almost all but no success. Thanks.



Solution 1:[1]

Do NOT use actions.order.create() / actions.order.capture() to create/capture orders on the client side, and only later send data to a server after client side events are completed

Instead, switch to a proper client-server integration. Follow the PayPal Checkout integration guide and make 2 routes on your server, one for 'Create Order' and one for 'Capture Order' (see the optional step 5 in 'Add and modify the code'). Both of these routes should return only JSON data (no HTML or text). Inside the 2nd route, when the capture API is successful you should store its resulting payment details in your database (particularly purchase_units[0].payments.captures[0].id, which is the PayPal transaction ID) and perform any necessary business logic (such as sending confirmation emails or reserving product) immediately before forwarding your return JSON to the frontend caller.

Pair those 2 routes with the frontend approval flow: https://developer.paypal.com/demo/checkout/#/pattern/server

Your fetch to the create or capture endpoints should be extended to include a body param with any additional data you wish to send, which can be verified for correctness before that action proceeds on the server, and only stored in the event of a successful capture response.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Preston PHX