| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 |
- <?php
- namespace Controllers;
- use Libs\ResponseLib;
- use Psr\Http\Message\ServerRequestInterface;
- class WooviWebhookController
- {
- public function __invoke(ServerRequestInterface $request)
- {
- $rawBody = (string)$request->getBody();
- if ($rawBody === '') {
- $rawBody = (string)file_get_contents('php://input');
- }
- $record = [
- 'received_at' => (new \DateTimeImmutable('now', new \DateTimeZone('UTC')))->format(DATE_ATOM),
- 'headers' => $this->normalizeHeaders($request->getHeaders()),
- 'raw_body' => $rawBody,
- ];
- $fileName = sprintf(
- 'woovi_webhook_%s_%s.txt',
- (new \DateTimeImmutable('now'))->format('Ymd_His'),
- bin2hex(random_bytes(4))
- );
- $filePath = dirname(__DIR__) . '/bin/' . $fileName;
- try {
- $encoded = json_encode($record, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
- if ($encoded === false) {
- $encoded = $rawBody;
- }
- file_put_contents($filePath, $encoded, LOCK_EX);
- } catch (\Throwable $e) {
- return ResponseLib::sendFail('Falha ao salvar webhook: ' . $e->getMessage(), [], 'E_INTERNAL')->withStatus(500);
- }
- return ResponseLib::sendOk([
- 'stored_file' => basename($filePath),
- ], 'S_WEBHOOK_SAVED');
- }
- /**
- * @param array<string, array<int, string>> $headers
- * @return array<string, string>
- */
- private function normalizeHeaders(array $headers): array
- {
- $normalized = [];
- foreach ($headers as $name => $values) {
- $normalized[$name] = implode(', ', $values);
- }
- return $normalized;
- }
- }
|