TshieldWebhookController.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. namespace Controllers;
  3. use Libs\ResponseLib;
  4. use Models\TshieldWebhookModel;
  5. use Psr\Http\Message\ServerRequestInterface;
  6. class TshieldWebhookController
  7. {
  8. private TshieldWebhookModel $model;
  9. public function __construct()
  10. {
  11. $this->model = new TshieldWebhookModel();
  12. }
  13. public function __invoke(ServerRequestInterface $request)
  14. {
  15. $body = json_decode((string)$request->getBody(), true);
  16. if (!is_array($body)) {
  17. return ResponseLib::sendFail('Invalid JSON payload.', [], 'E_VALIDATE')->withStatus(400);
  18. }
  19. $statusDescription = $body['status']['status'] ?? null;
  20. if ($statusDescription !== 'Aprovado') {
  21. return ResponseLib::sendOk([
  22. 'processed' => false,
  23. 'reason' => 'Status not approved. No action taken.',
  24. ], 'S_IGNORED');
  25. }
  26. $number = $body['number'] ?? null;
  27. $token = $body['token'] ?? null;
  28. $cpf = $body['cpf'] ?? null;
  29. $cnpj = $body['cnpj'] ?? null;
  30. $externalCandidates = [];
  31. if (is_string($number) && trim($number) !== '') {
  32. $externalCandidates[] = $number;
  33. }
  34. if (empty($externalCandidates) && (!is_string($cpf) || trim($cpf) === '') && (!is_string($cnpj) || trim($cnpj) === '')) {
  35. return ResponseLib::sendFail('Missing analysis identifiers (number/cpf/cnpj) in payload.', [], 'E_VALIDATE')->withStatus(400);
  36. }
  37. $updatedRows = 0;
  38. $matchedBy = null;
  39. if (!empty($externalCandidates)) {
  40. $updatedRows = $this->model->approveByExternalIds($externalCandidates);
  41. if ($updatedRows > 0) {
  42. $matchedBy = 'external_id';
  43. }
  44. }
  45. if ($updatedRows === 0 && is_string($cpf) && trim($cpf) !== '') {
  46. $updatedRows = $this->model->approveByCpf($cpf);
  47. if ($updatedRows > 0) {
  48. $matchedBy = 'cpf';
  49. }
  50. }
  51. if ($updatedRows === 0 && is_string($cnpj) && trim($cnpj) !== '') {
  52. $updatedRows = $this->model->approveCompanyOwnerByCnpj($cnpj);
  53. if ($updatedRows > 0) {
  54. $matchedBy = 'cnpj_company_owner';
  55. }
  56. }
  57. if ($updatedRows === 0) {
  58. return ResponseLib::sendFail(
  59. 'No user found to update KYC for this webhook payload.',
  60. [
  61. 'number' => $number,
  62. 'token' => $token,
  63. 'cpf' => $cpf,
  64. 'cnpj' => $cnpj,
  65. ],
  66. 'E_NOT_FOUND'
  67. )->withStatus(404);
  68. }
  69. return ResponseLib::sendOk([
  70. 'processed' => true,
  71. 'updated_rows' => $updatedRows,
  72. 'matched_by' => $matchedBy,
  73. 'number' => $number,
  74. 'token' => $token,
  75. ]);
  76. }
  77. }