WooviWebhookController.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. namespace Controllers;
  3. use Libs\ResponseLib;
  4. use Models\PaymentModel;
  5. use Psr\Http\Message\ServerRequestInterface;
  6. class WooviWebhookController
  7. {
  8. private PaymentModel $paymentModel;
  9. public function __construct()
  10. {
  11. $this->paymentModel = new PaymentModel();
  12. }
  13. public function __invoke(ServerRequestInterface $request)
  14. {
  15. $rawBody = (string)$request->getBody();
  16. if ($rawBody === '') {
  17. $rawBody = (string)file_get_contents('php://input');
  18. }
  19. $payload = json_decode($rawBody, true);
  20. if (!is_array($payload)) {
  21. return ResponseLib::sendFail('Payload inválido', [], 'E_VALIDATE')->withStatus(400);
  22. }
  23. $charge = $payload['charge'] ?? null;
  24. if (!is_array($charge)) {
  25. return ResponseLib::sendFail('Charge inválida', [], 'E_VALIDATE')->withStatus(400);
  26. }
  27. $correlationId = $charge['correlationID'] ?? null;
  28. $status = $charge['status'] ?? null;
  29. if (!is_string($correlationId) || $correlationId === '') {
  30. return ResponseLib::sendFail('correlationID inválido', [], 'E_VALIDATE')->withStatus(400);
  31. }
  32. if (!is_string($status) || $status === '') {
  33. return ResponseLib::sendFail('status inválido', [], 'E_VALIDATE')->withStatus(400);
  34. }
  35. try {
  36. $payment = $this->paymentModel->findByExternalId($correlationId);
  37. } catch (\Throwable $e) {
  38. return ResponseLib::sendFail('Falha ao consultar pagamento: ' . $e->getMessage(), [], 'E_DATABASE')->withStatus(500);
  39. }
  40. if (!$payment) {
  41. return ResponseLib::sendFail('Pagamento não encontrado', ['correlation_id' => $correlationId], 'E_NOT_FOUND')->withStatus(404);
  42. }
  43. try {
  44. $this->paymentModel->updateStatusId((int)$payment['payment_id'], 1);
  45. } catch (\Throwable $e) {
  46. return ResponseLib::sendFail('Falha ao atualizar pagamento: ' . $e->getMessage(), [], 'E_DATABASE')->withStatus(500);
  47. }
  48. return ResponseLib::sendOk([
  49. 'payment_id' => (int)$payment['payment_id'],
  50. 'correlation_id' => $correlationId,
  51. 'status' => $status,
  52. 'status_id' => 1,
  53. ], 'S_PAYMENT_UPDATED');
  54. }
  55. }