Laravel 8 - online payment przelewy24 gateway implementation

Viewed 366

I would like to implement online payment in my project. I use the Przelewy24 gateway from Poland.

For Laravel 8, I chose the plugin that works here: https://github.com/mnastalski/przelewy24-php

The error I am struggling with is the feedback from the gateway about whether the transfer was received or booked or not.

I contacted the Przelewy24 technical support and received a reply from them that they get the following information in their logs:

[responseBody] => Redirecting to "/ login" Redirecting is "/ login". [httpResponseCode] => 302

I have tried in many ways but unfortunately without any results. The following code has been changed many times.

BACKEND

-- web.php --

Route::post('/order_status', 'Payment_Controller@order_status')->name('order_status');
Auth::routes([ 'verify' => true ]);
...
...
Route::get('/orderPaymentMethods/', 'Payment_Controller@paymentMethods')->name('orderPayments_paymentMethods');
Route::get('/order-success', 'Payment_Controller@order_success')->name('order_success'); 
-- Payment_Controller.php

private function create_instance()
    {
        return new Przelewy24([
            'merchant_id' => $this->partnerId,
            'crc' => $this->crc,
            'pos_id' => $this->posId,
            'live' => false,  // `true` for production/live mode
        ]);
    }

    public function create_transaction()
    {
        $this->currency = $this->settings->first()->currency;

        if (!$this->sessionId) {
            $this->sessionId = $this->set_sessionId();
        }

        $this->checkCart();     // this function is checking if cart is empty or not
        $this->get_totalPrice_from_cart();         // this function is geting total price of cart
        $this->user_email = \Auth::user()->email;

        try {
            $this->transaction = $this->create_instance()->transaction([
                'session_id' => $this->sessionId,
                'url_return' => route('order_success'),
                'url_status' => route('order_status'),
                'amount' => $this->price,
                'description' => $this->description,
                'email' => $this->user_email,
                'currency' => $this->currency,
            ]);

            if ($this->transaction->token()) {
                /** TRANSACTION STARTED */
                return $this->transaction;
            }
            return 'Create transaction failed';

        } catch (ApiResponseException $e) {
            return 'Error(transaction): (' . $e->getCode() . ') - ' . $e->getMessage();
        }
    }

    public function set_sessionId()
    {
        // for testing purpose 1h session ID
        $this->sessionId = md5($this->posId . '|' . $this->partnerId . '|' . $this->price . '|' . $this->currency . '|' . $this->crc . '|' . date('Ymd-H'));

        return $this->sessionId;
    }

    public function order_success()
    {
        // this is returning page from przelewy24
        return view('order_success');
    }

    public function order_status()
    {
        // this is returning status and it doesn't work.
        // $webhook is always empty because as i mention before - support from przelewy24 getting Error 302 -redirecting to '/login'

        $this->checkCart();
        $instance = $this->create_instance();
        $webhook = $instance->handleWebhook();

        try {
            $verify = $instance->verify([
                'session_id' => $webhook->sessionId(),
                'order_id' => $webhook->orderId(),
                'amount' => $webhook->amount(),
            ]);
        } catch (ApiResponseException $e) {
            return $e->getMessage();
        }

        return response()->json($verify);
    }

FRONTEND

-- cartPage_paymentMethod.blade.php --

<html>
...
...
@php
  /** PAYMENT */

$transaction = new App\Http\Controllers\Payment_Controller();
$sessionId = $transaction->set_sessionId();
$create_trans = $transaction->create_transaction();
$transaction_url = '';
if(is_string($create_trans))
    echo $create_trans;
else
    $transaction_url = $create_trans->redirectUrl();

@endphp

<form method="post" action="{{$transaction_url}}">
    @csrf
    <button class="btn btn-primary">{{__('labels.toPayment')}}</button>
</form>
-- order_success.blade.php -- //


@section('content')

    <div id="message">Waiting for payment...</div>
    <div id="response">-</div>

    @push('custom-js')
        <script type="text/javascript">
            $(document).ready(function() {

                setTimeout(function() {

                    $.ajaxSetup({
                        headers: {
                            "Content-Type"    : "application/json",
                            "Accept"          : "application/json",
                            "cache-control": "no-cache",
                            "X-Requested-With": "XMLHttpRequest",
                            'X-CSRF-TOKEN'    : $('meta[name="csrf-token"]').attr('content')
                        },
                    });
                    $.ajax({
                        type       : "POST",
                        url        : '{{route('order_status')}}',
                        dataType   : "JSON",
                        headers    : {
                        },
                        processData: false,
                        success    : function(resp) {
                            console.log(resp);
                            $('#response').html(resp);
                        },
                        error      : function(xhr) {
                            console.log(xhr);
                        }
                    })
                }, 1000)

            })
        </script>
    @endpush
@endsection

I thought there might be a problem with laravel not allowing external scripts or that it 'tries' to force the script to log in (i.e. redirects to the login page) but `order_status' in my opinion the user does not have to be logged in.

There is no read/write to DB yet. This is the next step that I will follow as the above code finally starts working properly. I have been struggling with it for two weeks ... so please. HELP!

2 Answers

First guess is the route is AUTH protected but it doesn't seem to be as is mentioned in question.

`order_status' in my opinion the user does not have to be logged in

Double-check the route's middleware to make sure there is no auth there.If it didn't help , I would suggest using monitoring packages like telescope to see what is exactly going on.

I believe it gives you enough data to fix the problem.

UPDATE

order_status route is in web middleware and is csrf protected. So solution is to exclude it from csrf protection as is explained here

Here is the issue: [responseBody] => Redirecting to "/ login" Redirecting is "/ login". [httpResponseCode] => 302

Looks like you Laravel app requires authorization for this URL. It shouldn't. Check the begging of the controller file. If it have something like this:

public function __construct()
{
    $this->middleware('auth');
}

remove it for order_success method. Or just create another controller for callback without auth middleware.

Related