Providers retry webhooks. They can arrive twice, out of order, or while your server is mid-deploy. A handler that assumes one clean delivery will eventually duplicate an email, a label or a payout.
1. Verify the signature first
Compute an HMAC of the raw request body with your shared secret and compare it in constant time. Reject anything that does not match before touching the database. Some hosts strip custom headers, so we also support a secret token in the URL as a fallback.
$expected = hash_hmac('sha256', $rawBody, $secret);
if (!hash_equals($expected, $signature)) { http_response_code(401); exit; }2. Take a lock on the record
Two copies of the same event can arrive at the same moment. A lock keyed to the order (for example a database lock) makes the second copy wait or exit instead of running in parallel.
3. Check an idempotency key
Store the provider's event ID when you finish handling it. If you see the same ID again, return success and do nothing. Acknowledge quickly and do slow work in a queue.
When not to rely on this alone
- If the event can be replayed days later, also check the current state of the record before applying it.
- If you handle money, log each event and its outcome so a mismatch can be reconciled.
