skip to Main Content

I am trying to call the PayPal server to set up the transaction but it returns a 419 PAGE EXPIRED error on the console.

PayPal create order script

 createOrder: function(data, actions) {
                return fetch('/create-payment', {
                    method: 'post'
                }).then(function(res) {
                    return res.json();
                }).then(function(orderData) {
                    return orderData.id;
                });
            },

Laravel Route

Route::post('/create-payment', [PayPalController::class, 'create_payment'])->name('create-payment');

Controller

public function create_payment()
    {

      $order = new OrdersCreateRequest();
        $order->prefer('return=representation');

        $order->body = array(
            'intent' => 'CAPTURE',
            'application_context' =>
                array(
                    'return_url' => '/pages/orders',
                    'cancel_url' => '/pages/orders'
                ),
            'purchase_units' =>
                array(
                    0 =>
                        array(
                            'amount' =>
                                array(
                                    'currency_code' => 'USD',
                                    'value' => '420.00'
                                )
                        )
                )
        );
        try {
            $result = $this->client->execute($order);
            return $result;
        }
        catch(HttpException $ex) {
            print_r($ex->getMessage());
        }

   }

Blade

<div id="paypal-button-container"></div>

I know I need to add @csrf but where?

enter image description here

2

Answers


  1. CSRF verification enabled by default in Laravel. so either you need to pass crsf token or skip that route from verification middleware.

    Option 1

    Add this route to csrf verification middleware except array.

    App/Http/Middleware/VerifyCsrfToken.php
    
    protected $except = [
        "create-payment"
    ];
    

    Option 2

    Add this in your page head.

        <meta name="csrf-token" content="{{ csrf_token() }}">
    

    and this in script

        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
    
    Login or Signup to reply.
  2. I think even you can override script from paypal without disabling csrf token .

    <script>
            // Render the PayPal button into #paypal-button-container
           // X-CSRF-TOKEN is also required to add in request, otherwise you will not be able to access the createorder url
            paypal.Buttons({
                // Call your server to set up the transaction
                createOrder: function(data, actions) {
                    var _token = "{{ csrf_token() }}";
                    return fetch('http://yoursite.com/createorder', {
                        method: 'post',
                        headers: {
                            'X-CSRF-TOKEN': _token,
                            'Content-Type': 'application/json',
                        },
                    }).then(function(res) {
                        return res.json();
                    }).then(function(orderData) {
                        return orderData.result.id;
                    });
                },
                // Call your server to finalize the transaction
                onApprove: function(data, actions) {
                    var _token = "{{ csrf_token() }}";
                    return fetch('http://yoursite.com/captureorder/' + data.orderID + '/capture/', {
                        method: 'post',
                        headers: {
                            'X-CSRF-TOKEN': _token,
                            'Content-Type': 'application/json',
                        },
                    }).then(function(res) {
                        return res.json();
                    }).then(function(orderData) {
                        // Three cases to handle:
                        //   (1) Recoverable INSTRUMENT_DECLINED -> call actions.restart()
                        //   (2) Other non-recoverable errors -> Show a failure message
                        //   (3) Successful transaction -> Show a success / thank you message
                        // Your server defines the structure of 'orderData', which may differ
                        var errorDetail = Array.isArray(orderData.details) && orderData.details[0];
                        if (errorDetail && errorDetail.issue === 'INSTRUMENT_DECLINED') {
                            // Recoverable state, see: "Handle Funding Failures"
                            // https://developer.paypal.com/docs/checkout/integration-features/funding-failure/
                            return actions.restart();
                        }
                        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 + ')';
                            // Show a failure message
                            return alert(msg);
                        }
                        // Show a success message to the buyer
                        alert('Transaction completed by ' + orderData.result.payer.name.given_name);
                    });
                }
            }).render('#paypal-button-container');
        </script>
    

    Ref:http://findnerd.com/list/view/Paypal-Checkout-REST-api-integration-in-Laravel-5-7-with-smart-payment-buttons/74304/

    Ref:https://developer.paypal.com/demo/checkout/#/pattern/server

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search