WooviWebhookController.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. namespace Controllers;
  3. use Libs\ResponseLib;
  4. use Psr\Http\Message\ServerRequestInterface;
  5. class WooviWebhookController
  6. {
  7. public function __invoke(ServerRequestInterface $request)
  8. {
  9. $rawBody = (string)$request->getBody();
  10. if ($rawBody === '') {
  11. $rawBody = (string)file_get_contents('php://input');
  12. }
  13. $record = [
  14. 'received_at' => (new \DateTimeImmutable('now', new \DateTimeZone('UTC')))->format(DATE_ATOM),
  15. 'headers' => $this->normalizeHeaders($request->getHeaders()),
  16. 'raw_body' => $rawBody,
  17. ];
  18. $fileName = sprintf(
  19. 'woovi_webhook_%s_%s.txt',
  20. (new \DateTimeImmutable('now'))->format('Ymd_His'),
  21. bin2hex(random_bytes(4))
  22. );
  23. $filePath = dirname(__DIR__) . '/bin/' . $fileName;
  24. try {
  25. $encoded = json_encode($record, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
  26. if ($encoded === false) {
  27. $encoded = $rawBody;
  28. }
  29. file_put_contents($filePath, $encoded, LOCK_EX);
  30. } catch (\Throwable $e) {
  31. return ResponseLib::sendFail('Falha ao salvar webhook: ' . $e->getMessage(), [], 'E_INTERNAL')->withStatus(500);
  32. }
  33. return ResponseLib::sendOk([
  34. 'stored_file' => basename($filePath),
  35. ], 'S_WEBHOOK_SAVED');
  36. }
  37. /**
  38. * @param array<string, array<int, string>> $headers
  39. * @return array<string, string>
  40. */
  41. private function normalizeHeaders(array $headers): array
  42. {
  43. $normalized = [];
  44. foreach ($headers as $name => $values) {
  45. $normalized[$name] = implode(', ', $values);
  46. }
  47. return $normalized;
  48. }
  49. }