Overview
A webhook is an HTTP request sent by another service when an event occurs. Treat it as untrusted input. A request reaching your endpoint does not prove that it came from the expected provider.
Verify the raw request body
Signature schemes commonly calculate an HMAC over the exact request bytes. Read the raw body before decoding JSON; re-encoding decoded data can change whitespace or key order and invalidate verification.
$rawBody = file_get_contents('php://input');
$provided = $_SERVER['HTTP_X_WEBHOOK_SIGNATURE'] ?? '';
$secret = getenv('WEBHOOK_SECRET');
$expected = hash_hmac('sha256', $rawBody, $secret);
if (!is_string($provided) || !hash_equals($expected, $provided)) {
http_response_code(401);
exit;
}
This is a generic pattern, not a substitute for the provider's exact signature specification. Some providers prefix the digest, include a timestamp, or sign additional fields. Follow their documented algorithm and compare signatures with a constant-time function.
Prevent replay
If the provider signs a timestamp, reject requests outside a small, documented tolerance. Store event IDs and reject duplicates. A timestamp alone does not stop a valid request from being replayed inside the accepted window.
Acknowledge and process carefully
Validate the event structure and persist the event before returning success. For lengthy work, enqueue a job and respond promptly. If processing fails after persistence, retry internally rather than asking the provider to resend indefinitely.
Idempotent event handling
Create a unique database constraint on the provider and event ID. Insert the event once, then process it with a state transition. This protects against duplicate deliveries and concurrent retries.
Operational checklist
- Verify signatures using the exact raw body and provider rules.
- Keep webhook secrets outside the document root.
- Validate timestamps and event identifiers.
- Enforce request-size and content-type limits.
- Persist before acknowledging.
- Make event processing idempotent.
- Log event IDs and outcomes, never secrets or full sensitive payloads.
References
GitHub Webhooks: Securing your webhooks · OWASP API Security