TshieldWebhookController.php 7.8 KB

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