Custom PHP
CRM Webhook Integration in PHP: Verification, Retries and Idempotency
CRM webhook integration in PHP is the practice of receiving platform events at a public endpoint and turning them into reliable application state. In my builds it means verifying an HMAC signature before parsing the body, writing an idempotency key on first sight, returning 2xx fast, and moving real work to a queue with bounded retries and structured logs.
What a CRM webhook sends and what your endpoint must do
A CRM webhook is an HTTP POST from the platform to a URL you control, carrying JSON for an event such as contact.created, deal.updated or invoice.paid. The payload is only a notification: the current record usually lives behind the CRM API, so your endpoint should fetch what it needs rather than trust a stale snapshot. In my builds at webdev-saif.com the handler does four things in order: reject requests that fail the signature check, persist the delivery ID, acknowledge with 200, and enqueue the work. That split keeps the public endpoint boring and fast, which matters because most CRM providers time out in 5 to 10 seconds and retry anything slower or non-2xx.
- Treat the POST as a notification, not the source of truth
- Accept only POST requests with a JSON content type
- Read the untouched raw body from php://input
- Return 2xx before doing slow downstream work
- Key every delivery by the provider event ID
Verifying the signature before you trust the body
Signature verification is a cheap check that stops anyone else from posting fake deals into your system. Most CRMs sign the exact raw body with HMAC-SHA256 and send the digest in a header such as X-Signature or X-Hub-Signature-256. Compute the digest with hash_hmac using sha256, the raw body and your shared secret, then compare it with hash_equals($expected, $provided) — never ===, so a timing attack cannot walk the digest byte by byte. Recompute from the raw bytes: decoding JSON and re-encoding changes whitespace and key order and will break the match. I also reject requests whose signed timestamp header is older than about five minutes, and keep a small array of active secrets so a rotated secret still verifies in-flight deliveries.
- Sign and compare raw body bytes, not re-encoded JSON
- Use hash_equals for a constant-time digest comparison
- Reject timestamps outside a five-minute window
- Keep old and new secrets valid during rotation
- Return 401 before touching the database on mismatch
Acknowledge fast, process the event in a queue
The webhook response is a contract with the sender, not a report of completed work. Return 200 or 204 as soon as the delivery is recorded, then hand the event to a queue worker that calls the CRM API and writes to your database. In PHP I usually push a job onto a database-backed queue or Redis through a small custom class rather than adding a framework to a single endpoint. The worker gets a bounded timeout, a retry count and a dead-letter destination. If you must process inline, keep it under a second and never call a slow third party before responding. A slow handler causes duplicate deliveries, which then forces you to solve idempotency under pressure.
- Acknowledge with 2xx once the delivery ID is stored
- Move API calls and database writes into a queued job
- Set a per-job timeout and a maximum attempt count
- Route exhausted jobs to a dead-letter table for replay
Retries and backoff for at-least-once delivery
Assume at-least-once delivery: every provider will resend an event when it sees a timeout or a 5xx. Design retries you control instead of relying on the CRM to be gentle. Use exponential backoff with jitter — for example 30 seconds, 2 minutes, 10 minutes and 1 hour, then dead-letter — so a downstream outage is not amplified by a thundering herd. Honour a Retry-After header when the provider sends one. Distinguish permanent failures from transient ones: a 400 or 422 caused by bad data should not be retried five times, while a 503 or a locked database row should. A practical target is that a transient five-minute outage clears without manual intervention and without duplicate side effects.
- Exponential backoff with jitter, capped at five attempts
- Retry 5xx and network timeouts, not validation errors
- Honour Retry-After from the CRM response
- Dead-letter exhausted jobs with the delivery ID attached
Idempotency: making duplicate deliveries harmless
Idempotency is what makes retries safe: processing the same event twice must produce the same state as processing it once. Derive a key from the provider event ID plus the source system, and enforce it with a UNIQUE database index rather than a check-then-insert, which races under concurrent deliveries. On first sight, insert the key inside the same transaction as your business write; on a duplicate, return the stored result and skip the side effect. Keep a dedupe window of a few days to a week depending on the provider retry policy. Be careful with actions that cannot be rolled back, such as sending email — put those behind the same keyed record so a replay cannot notify a contact twice.
- UNIQUE index on (source, event_id) as the source of truth
- Insert the key in the same transaction as the business write
- Return the stored result on a duplicate delivery
- Guard irreversible actions such as email behind the key
Logging that helps during an incident
Logs are the only evidence you have when a CRM claims it delivered an event you never saw. Write structured JSON lines with a fixed set of fields: timestamp in UTC, delivery ID, event type, signature result, HTTP status, elapsed milliseconds, attempt number and job ID. Never log the shared secret or a full payload containing personal data; store a hash of the raw body if you need to prove what arrived. Carry the record across the queue boundary by passing the delivery ID into the job. Alert on a rising 401 rate, a growing dead-letter table and jobs stuck in retry, not on every single failure. A practical retention window is 30 days for debug logs and longer for the delivery ledger.
Testing and the mistakes I see most often
Before shipping, capture one real payload from the CRM and replay it locally with curl through a tunnel such as ngrok. Write a unit test for the signature helper with a known secret and a fixed body, and an integration test that replays the same delivery twice and asserts only one database row exists. Then force a 500 on the first attempt and confirm the job retries rather than disappearing. The mistakes I see most often are verifying a signature after decoding JSON, returning 200 before saving the delivery ID, retrying validation failures, and logging success for an event that was only enqueued. Each of those turns a small outage into silent data loss.
Frequently asked questions
What is a CRM webhook in PHP?
A CRM webhook is an HTTP POST your CRM sends to a PHP endpoint when something changes, such as a contact created or a deal closed. Your script verifies the signature, records the delivery, and updates your own database or a queue. The webhook is a notification; the authoritative record stays in the CRM unless you fetch it through its API.
How do I verify a webhook signature in PHP?
Read the raw request body before decoding anything, compute an HMAC-SHA256 digest with your shared secret, and compare it to the signature header using hash_equals. Reject a mismatch with 401 immediately. Also check the signed timestamp to block replayed requests, and keep the previous secret valid briefly during rotation so in-flight deliveries do not fail.
Why does my CRM keep resending the same event?
Most resends happen because the endpoint answered slowly, returned a non-2xx status, or threw an error after receiving the event. CRM providers treat anything outside a fast 2xx as undelivered and retry. Record the delivery ID, return 200 quickly, and move slow work to a queue. If duplicates still reach you, enforce a unique key on the event ID.
What is an idempotency key for webhooks?
An idempotency key is a stable identifier, usually the CRM event ID plus the source system, that lets your code recognise a redelivery. Store it with a unique database constraint and write it in the same transaction as the business change. When the same key arrives again, return the stored result instead of repeating the side effect, such as creating a duplicate order or sending another email.
Should I process the webhook immediately or queue it?
Queue it unless the work is trivial. Responding 200 before the job runs stops the CRM from retrying, and a worker can apply backoff, timeouts and dead-lettering without a request timeout. For inline processing, keep the handler under a second and never call a slow third party before responding. The trade-off is that you must monitor queue depth and worker failures.
Can you help integrate our CRM with a PHP site?
Yes. I'm Saif Al Jahan, a freelance WordPress and PHP developer based in Mymensingh, Bangladesh (GMT+6). I build custom PHP endpoints and WordPress integrations with signature verification, retry-safe queues, idempotent writes and delivery logging. I can review an existing webhook handler, fix duplicate or missing events, or build one from scratch. Reach me through the contact page with your CRM name and a payload sample.