TshieldWebhookController.php 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. <?php
  2. namespace Controllers;
  3. use Libs\ResponseLib;
  4. use Models\TshieldWebhookModel;
  5. use Psr\Http\Message\ResponseInterface;
  6. use Psr\Http\Message\ServerRequestInterface;
  7. class TshieldWebhookController
  8. {
  9. private TshieldWebhookModel $model;
  10. private string $logFilePath;
  11. public function __construct()
  12. {
  13. $this->model = new TshieldWebhookModel();
  14. $this->logFilePath = $this->resolveLogFilePath($_ENV['TSHIELD_WEBHOOK_LOG_FILE'] ?? null);
  15. }
  16. public function __invoke(ServerRequestInterface $request)
  17. {
  18. $requestId = $this->generateRequestId();
  19. $rawBody = (string)$request->getBody();
  20. if ($rawBody === '') {
  21. $rawBody = (string)file_get_contents('php://input');
  22. }
  23. $body = json_decode($rawBody, true);
  24. try {
  25. if (!is_array($body)) {
  26. $response = ResponseLib::sendFail('Invalid JSON payload.', [], 'E_VALIDATE')->withStatus(400);
  27. $this->logWebhook($request, $requestId, $rawBody, null, $response, ['result' => 'invalid_json']);
  28. return $response;
  29. }
  30. $statusDescription = $body['status']['status'] ?? null;
  31. if ($statusDescription !== 'Aprovado') {
  32. $response = ResponseLib::sendOk([
  33. 'processed' => false,
  34. 'reason' => 'Status not approved. No action taken.',
  35. ], 'S_IGNORED');
  36. $this->logWebhook($request, $requestId, $rawBody, $body, $response, [
  37. 'result' => 'ignored',
  38. 'status_description' => $statusDescription,
  39. ]);
  40. return $response;
  41. }
  42. $externalNumber = $body['number'] ?? $body['token'] ?? null;
  43. if (!is_string($externalNumber) || trim($externalNumber) === '') {
  44. $response = ResponseLib::sendFail('Missing analysis number/token in payload.', [], 'E_VALIDATE')->withStatus(400);
  45. $this->logWebhook($request, $requestId, $rawBody, $body, $response, ['result' => 'missing_number']);
  46. return $response;
  47. }
  48. $updated = $this->model->approveByExternalId($externalNumber);
  49. if (!$updated) {
  50. $response = ResponseLib::sendFail(
  51. 'No user found for provided analysis number.',
  52. ['number' => $externalNumber],
  53. 'E_NOT_FOUND'
  54. )->withStatus(404);
  55. $this->logWebhook($request, $requestId, $rawBody, $body, $response, [
  56. 'result' => 'not_found',
  57. 'number' => $externalNumber,
  58. ]);
  59. return $response;
  60. }
  61. $response = ResponseLib::sendOk([
  62. 'processed' => true,
  63. 'number' => $externalNumber,
  64. ]);
  65. $this->logWebhook($request, $requestId, $rawBody, $body, $response, [
  66. 'result' => 'updated',
  67. 'number' => $externalNumber,
  68. ]);
  69. return $response;
  70. } catch (\Throwable $e) {
  71. $response = ResponseLib::sendFail('Webhook processing error.', [
  72. 'request_id' => $requestId,
  73. 'error' => $e->getMessage(),
  74. ], 'E_WEBHOOK')->withStatus(500);
  75. $this->logWebhook($request, $requestId, $rawBody, is_array($body) ? $body : null, $response, [
  76. 'result' => 'exception',
  77. 'exception' => [
  78. 'message' => $e->getMessage(),
  79. 'type' => get_class($e),
  80. ],
  81. ]);
  82. return $response;
  83. }
  84. }
  85. private function generateRequestId(): string
  86. {
  87. try {
  88. return bin2hex(random_bytes(16));
  89. } catch (\Throwable $e) {
  90. return uniqid('tshield_', true);
  91. }
  92. }
  93. private function logWebhook(
  94. ServerRequestInterface $request,
  95. string $requestId,
  96. string $rawBody,
  97. ?array $decodedBody,
  98. ResponseInterface $response,
  99. array $extra = []
  100. ): void {
  101. $ts = (new \DateTimeImmutable())->format('c');
  102. $serverParams = $request->getServerParams();
  103. $ip = $serverParams['REMOTE_ADDR'] ?? null;
  104. $method = $request->getMethod();
  105. $uri = (string)$request->getUri();
  106. $responseBody = $this->getResponseBodyForLog($response);
  107. $entry = [
  108. 'ts' => $ts,
  109. 'service' => 'tshield_webhook',
  110. 'request_id' => $requestId,
  111. 'method' => $method,
  112. 'uri' => $uri,
  113. 'ip' => $ip,
  114. 'request_raw' => $rawBody,
  115. 'request_json' => $decodedBody,
  116. 'response_status' => $response->getStatusCode(),
  117. 'response_body' => $responseBody,
  118. ];
  119. if (!empty($extra)) {
  120. $entry['context'] = $extra;
  121. }
  122. $encoded = json_encode($entry, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
  123. if ($encoded === false) {
  124. $encoded = '{"ts":"' . $ts . '","service":"tshield_webhook","request_id":"' . $requestId . '","error":"unable_to_encode_log"}';
  125. }
  126. try {
  127. @file_put_contents($this->logFilePath, $encoded . "\n", FILE_APPEND | LOCK_EX);
  128. } catch (\Throwable $e) {
  129. }
  130. error_log('[TShieldWebhook] ' . $encoded);
  131. }
  132. private function getResponseBodyForLog(ResponseInterface $response): ?string
  133. {
  134. try {
  135. $stream = $response->getBody();
  136. if ($stream === null) {
  137. return null;
  138. }
  139. if (method_exists($stream, 'isSeekable') && $stream->isSeekable()) {
  140. $pos = $stream->tell();
  141. $stream->rewind();
  142. $contents = $stream->getContents();
  143. $stream->seek($pos);
  144. return $contents;
  145. }
  146. return (string)$stream;
  147. } catch (\Throwable $e) {
  148. return null;
  149. }
  150. }
  151. private function resolveLogFilePath(?string $path): string
  152. {
  153. $path = trim((string)$path);
  154. if ($path === '') {
  155. $path = 'tshield_webhook.txt';
  156. }
  157. if (!preg_match('/^(?:[A-Za-z]:\\\\|\\/)/', $path)) {
  158. $path = rtrim(dirname(__DIR__), '/\\') . DIRECTORY_SEPARATOR . $path;
  159. }
  160. $dir = dirname($path);
  161. if (!is_dir($dir)) {
  162. @mkdir($dir, 0775, true);
  163. }
  164. return $path;
  165. }
  166. }