首页 > 解决方案 > Laravel 8 - 在线支付 przelewy24 网关实现

问题描述

我想在我的项目中实现在线支付。我使用来自波兰的 Przelewy24 网关。

对于 Laravel 8,我选择了适用于此处的插件: https ://github.com/mnastalski/przelewy24-php

我正在努力解决的错误是网关关于是否收到或预订转移的反馈。

我联系了 Przelewy24 技术支持并收到他们的回复,他们在日志中获得了以下信息:

[responseBody] => 重定向到“/login” 重定向是“/login”。[httpResponseCode] => 302

我尝试了很多方法,但不幸的是没有任何结果。以下代码已多次更改。

后端

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

前端

-- 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

我认为 laravel 可能存在不允许外部脚本的问题,或者它“尝试”强制脚本登录(即重定向到登录页面)但我认为“order_status”用户不必登录.

还没有对 DB 的读/写。这是我将遵循的下一步,因为上面的代码终于开始正常工作了。我已经为此苦苦挣扎了两个星期……所以请。帮助!

标签: phplaravelpayment-gatewaylaravel-8

解决方案


第一个猜测是路由受 AUTH 保护,但它似乎不像问题中提到的那样。

`order_status' 在我看来,用户不必登录

仔细检查路由的中间件以确保那里没有身份验证。如果没有帮助,我建议使用像望远镜这样的监控包来看看到底发生了什么。

我相信它可以为您提供足够的数据来解决问题。

更新

order_status 路由位于 web 中间件中,并且受 csrf 保护。因此,解决方案是将其从 csrf 保护中排除,如此处所述


推荐阅读