| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- <?php
- declare(strict_types=1);
- header('Content-Type: application/json; charset=utf-8');
- // Only accept POST requests
- if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
- http_response_code(405);
- echo json_encode(['error' => 'Method Not Allowed', 'allowed' => ['POST']]);
- exit;
- }
- // Validate key parameter
- if (!isset($_GET['key']) || empty($_GET['key'])) {
- http_response_code(400);
- echo json_encode(['error' => 'Missing key parameter']);
- exit;
- }
- $key = $_GET['key'];
- $dataPath = __DIR__ . '/data/webhooks.json';
- $maxRequestsPerWebhook = 100;
- // Read and validate webhook
- $fp = fopen($dataPath, 'c+');
- if (!$fp) {
- http_response_code(500);
- echo json_encode(['error' => 'Internal server error']);
- exit;
- }
- flock($fp, LOCK_EX);
- $raw = stream_get_contents($fp);
- $data = json_decode($raw, true);
- // Find the webhook
- $webhookIndex = null;
- foreach ($data['webhooks'] as $index => $webhook) {
- if ($webhook['key'] === $key) {
- $webhookIndex = $index;
- break;
- }
- }
- if ($webhookIndex === null) {
- flock($fp, LOCK_UN);
- fclose($fp);
- http_response_code(404);
- echo json_encode(['error' => 'Webhook not found']);
- exit;
- }
- // Capture request data
- $request = [
- 'timestamp' => date('c'),
- 'method' => $_SERVER['REQUEST_METHOD'],
- 'headers' => getallheaders() ?: [],
- 'body' => file_get_contents('php://input')
- ];
- // Add request to webhook
- $data['webhooks'][$webhookIndex]['requests'][] = $request;
- // Enforce max requests limit (FIFO - remove oldest)
- if (count($data['webhooks'][$webhookIndex]['requests']) > $maxRequestsPerWebhook) {
- array_shift($data['webhooks'][$webhookIndex]['requests']);
- }
- // Write back to file
- ftruncate($fp, 0);
- rewind($fp);
- fwrite($fp, json_encode($data, JSON_PRETTY_PRINT));
- flock($fp, LOCK_UN);
- fclose($fp);
- // Return success response
- http_response_code(200);
- echo json_encode(['success' => true, 'message' => 'Request logged']);
|