-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebhook.php
More file actions
57 lines (47 loc) · 1.93 KB
/
Copy pathwebhook.php
File metadata and controls
57 lines (47 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<?php
/**
* A webhook receiver, framework-free. Point any PHP-capable web server at this file.
*
* export VISION_WEBHOOK_SECRET=whsec_… # dashboard → Webhooks
* php -S localhost:3000 examples/webhook.php
*
* The endpoint must be HTTPS and must not resolve to a private address, so a bare localhost
* receiver is unreachable by design — put a tunnel (ngrok, cloudflared) in front of it
* while developing.
*/
declare(strict_types=1);
require __DIR__ . '/../vendor/autoload.php';
use VisionApi\Exception\WebhookSignatureException;
use VisionApi\Webhook;
$secret = $_ENV['VISION_WEBHOOK_SECRET'] ?? getenv('VISION_WEBHOOK_SECRET');
if (!$secret) {
http_response_code(500);
exit("Set VISION_WEBHOOK_SECRET (dashboard → Webhooks).\n");
}
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
http_response_code(405);
exit;
}
// Read the raw bytes. The signature covers exactly what arrived — decoding first and
// re-encoding changes key order and whitespace, and the HMAC stops matching.
$body = file_get_contents('php://input') ?: '';
try {
$event = Webhook::verify($body, $_SERVER['HTTP_X_VISION_SIGNATURE'] ?? null, $secret);
} catch (WebhookSignatureException $e) {
error_log('rejected delivery: ' . $e->getMessage());
http_response_code(400);
exit;
}
// Any 2xx is success. Acknowledge immediately and do the work afterwards — a slow handler
// looks like a failed delivery and earns a retry at +1 m, +5 m, +15 m, +40 m.
http_response_code(202);
if (function_exists('fastcgi_finish_request')) {
fastcgi_finish_request();
}
if ($event['event'] === 'task.failed') {
error_log(sprintf('task %s failed: %s (delivery %s)',
$event['task_id'], $event['error']['code'], $_SERVER['HTTP_X_VISION_DELIVERY'] ?? '?'));
} else {
error_log(sprintf('task %s completed — %d credits', $event['task_id'], $event['credits_used']));
// $event['result'] carries the same members as the sync response.
}