File size: 1,615 Bytes
cf14c12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<?php

declare(strict_types=1);

namespace Presentation\RequestHandlers;

use Billing\Infrastructure\Payments\Exceptions\WebhookException;
use Billing\Infrastructure\Payments\PaymentGatewayFactoryInterface;
use Easy\Http\Message\RequestMethod;
use Easy\Http\Message\StatusCode;
use Easy\Router\Attributes\Middleware;
use Easy\Router\Attributes\Route;
use Presentation\Middlewares\ExceptionMiddleware;
use Presentation\Response\EmptyResponse;
use Presentation\Response\JsonResponse;
use Presentation\Response\Response;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\RequestHandlerInterface;

#[Middleware(ExceptionMiddleware::class)]
#[Route(path: '/webhooks/[:gateway]', method: RequestMethod::POST)]
class WebhookRequestHandler implements RequestHandlerInterface
{
    public function __construct(
        private PaymentGatewayFactoryInterface $factory,
        private ContainerInterface $container
    ) {
    }

    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        $gateway = $this->factory->create($request->getAttribute('gateway'));

        // Handle the webhook request...
        $handler = $gateway->getWebhookHandler();

        if (is_string($handler)) {
            $handler = $this->container->get($handler);
        }

        try {
            $handler->handle($request);
        } catch (WebhookException $th) {
            return new JsonResponse(['error' => $th->getMessage()], StatusCode::BAD_REQUEST);
        }

        return new EmptyResponse();
    }
}