webhook.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. declare(strict_types=1);
  3. header('Content-Type: application/json; charset=utf-8');
  4. // Only accept POST requests
  5. if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
  6. http_response_code(405);
  7. echo json_encode(['error' => 'Method Not Allowed', 'allowed' => ['POST']]);
  8. exit;
  9. }
  10. // Validate key parameter
  11. if (!isset($_GET['key']) || empty($_GET['key'])) {
  12. http_response_code(400);
  13. echo json_encode(['error' => 'Missing key parameter']);
  14. exit;
  15. }
  16. $key = $_GET['key'];
  17. $dataPath = __DIR__ . '/data/webhooks.json';
  18. $maxRequestsPerWebhook = 100;
  19. // Read and validate webhook
  20. $fp = fopen($dataPath, 'c+');
  21. if (!$fp) {
  22. http_response_code(500);
  23. echo json_encode(['error' => 'Internal server error']);
  24. exit;
  25. }
  26. flock($fp, LOCK_EX);
  27. $raw = stream_get_contents($fp);
  28. $data = json_decode($raw, true);
  29. // Find the webhook
  30. $webhookIndex = null;
  31. foreach ($data['webhooks'] as $index => $webhook) {
  32. if ($webhook['key'] === $key) {
  33. $webhookIndex = $index;
  34. break;
  35. }
  36. }
  37. if ($webhookIndex === null) {
  38. flock($fp, LOCK_UN);
  39. fclose($fp);
  40. http_response_code(404);
  41. echo json_encode(['error' => 'Webhook not found']);
  42. exit;
  43. }
  44. // Capture request data
  45. $request = [
  46. 'timestamp' => date('c'),
  47. 'method' => $_SERVER['REQUEST_METHOD'],
  48. 'headers' => getallheaders() ?: [],
  49. 'body' => file_get_contents('php://input')
  50. ];
  51. // Add request to webhook
  52. $data['webhooks'][$webhookIndex]['requests'][] = $request;
  53. // Enforce max requests limit (FIFO - remove oldest)
  54. if (count($data['webhooks'][$webhookIndex]['requests']) > $maxRequestsPerWebhook) {
  55. array_shift($data['webhooks'][$webhookIndex]['requests']);
  56. }
  57. // Write back to file
  58. ftruncate($fp, 0);
  59. rewind($fp);
  60. fwrite($fp, json_encode($data, JSON_PRETTY_PRINT));
  61. flock($fp, LOCK_UN);
  62. fclose($fp);
  63. // Return success response
  64. http_response_code(200);
  65. echo json_encode(['success' => true, 'message' => 'Request logged']);