WooviWebhookController.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. if (!$this->isPaidStatus($status)) {
  36. return ResponseLib::sendOk([
  37. 'correlation_id' => $correlationId,
  38. 'status' => $status,
  39. 'updated' => false,
  40. ], 'S_WEBHOOK_IGNORED');
  41. }
  42. try {
  43. $payment = $this->paymentModel->findByExternalId($correlationId);
  44. } catch (\Throwable $e) {
  45. return ResponseLib::sendFail('Falha ao consultar pagamento: ' . $e->getMessage(), [], 'E_DATABASE')->withStatus(500);
  46. }
  47. if (!$payment) {
  48. return ResponseLib::sendFail('Pagamento não encontrado', ['correlation_id' => $correlationId], 'E_NOT_FOUND')->withStatus(404);
  49. }
  50. try {
  51. $this->paymentModel->updateStatusId((int)$payment['payment_id'], 1);
  52. } catch (\Throwable $e) {
  53. return ResponseLib::sendFail('Falha ao atualizar pagamento: ' . $e->getMessage(), [], 'E_DATABASE')->withStatus(500);
  54. }
  55. return ResponseLib::sendOk([
  56. 'payment_id' => (int)$payment['payment_id'],
  57. 'correlation_id' => $correlationId,
  58. 'status' => $status,
  59. 'status_id' => 1,
  60. 'updated' => true,
  61. ], 'S_PAYMENT_UPDATED');
  62. }
  63. private function isPaidStatus(string $status): bool
  64. {
  65. $normalized = strtoupper(trim($status));
  66. return in_array($normalized, ['PAID', 'COMPLETED', 'CONFIRMED', 'APPROVED'], true);
  67. }
  68. }