Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

alchalade's avatar

Handling Incomming Payment Request

Hi, The system receives payments from third-party services. I add a middleware for those requests.

Route::group(['prefix' => 'payments', 'middleware' => 'payment'], function () {
    Route::post('/service1', 'PaymentController@storeService1');
    Route::post('/service2', function(){ }); //handles the whole process in the middleware

});

What makes sense (at least for me) to handle the payment in the middleware (determine the Payment Provider, check if the request comes from a whitelist service-provider IP or if the data structure is okay, etc.)

Here is the part which feels wrong

After the middleware determines the PaymentService it creates a ProcessorClass for it ( like XPaymentProcessor, YPaymentProcessor) which implements IPaymentProvider (with handlePayment, sendResult). After that, it triggers the handlePayment function with request content. From there I want to emit an Event to further ServiceProviders.

But somehow it feels terribly wrong to handle the whole process in the middleware. Shall I just validate the request and give the information to my Controller or what would be a good solution for my problem?

0 likes
4 replies
arukomp's avatar

have the actual data processing in the controller methods. It makes sense that way because every one of the different payment methods might need slightly different processing, and you really don't wanna have multiple ifelse or switch statements in the middleware.

In this scenario, the middleware's job really is just to validate access (api token/key?).

If you'd like to validate input (required fields, correct data types, etc), then I'd suggest using Form Requests - https://laravel.com/docs/5.6/validation#form-request-validation

alchalade's avatar

Unfortunately, the received data is XML. Therefore the form validation cannot solve my problem. I need to validate it in the middleware.

But I understand the context. Thanks.

arukomp's avatar
arukomp
Best Answer
Level 10

In this case, I'd suggest 2 middlewares:

  1. Validate api key/secret - grant/deny access
  2. Convert XML request into regular Laravel Request

The second middleware could be reused in other parts of your application, plus you'll be able to use Laravel's form validation

1 like
alchalade's avatar

the idea with two middlewares satisfies me now :)

Please or to participate in this conversation.