model = new TshieldWebhookModel(); } public function __invoke(ServerRequestInterface $request) { $body = json_decode((string)$request->getBody(), true); if (!is_array($body)) { return ResponseLib::sendFail('Invalid JSON payload.', [], 'E_VALIDATE')->withStatus(400); } error_log('[TShieldWebhook] payload=' . json_encode($body, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)); $statusDescription = $body['status']['status'] ?? $body['status'] ?? ($body['data']['status']['status'] ?? null); $statusNormalized = is_string($statusDescription) ? mb_strtolower(trim($statusDescription)) : ''; $isApproved = $statusNormalized === 'aprovado' || $statusNormalized === 'aprovada' || (is_string($statusNormalized) && str_contains($statusNormalized, 'aprov')); if (!$isApproved) { return ResponseLib::sendOk([ 'processed' => false, 'reason' => 'Status not approved. No action taken.', 'status' => $statusDescription, ], 'S_IGNORED'); } $externalIds = [ $body['number'] ?? null, $body['token'] ?? null, $body['data']['number'] ?? null, $body['data']['token'] ?? null, $body['analysis']['number'] ?? null, $body['analysis']['token'] ?? null, $body['query']['number'] ?? null, $body['query']['token'] ?? null, ]; $externalNumber = null; foreach ($externalIds as $candidate) { if (is_numeric($candidate)) { $candidate = (string)$candidate; } if (!is_string($candidate)) { continue; } $candidate = trim($candidate); if ($candidate === '') { continue; } $externalNumber = $candidate; break; } if ($externalNumber === null) { return ResponseLib::sendFail('Missing analysis number/token in payload.', [], 'E_VALIDATE')->withStatus(400); } error_log('[TShieldWebhook] approved candidates=' . json_encode($externalIds, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)); error_log('[TShieldWebhook] approved number=' . $externalNumber); $updated = $this->model->approveByExternalIds($externalIds); if (!$updated) { return ResponseLib::sendFail( 'No user found for provided analysis number.', ['number' => $externalNumber, 'candidates' => $externalIds], 'E_NOT_FOUND' )->withStatus(404); } return ResponseLib::sendOk([ 'processed' => true, 'number' => $externalNumber, ]); } }