On this page
To receive SMS verification webhooks reliably in your backend, validate the incoming request, store the payload idempotently keyed by order ID, return HTTP 200 OK immediately (in under a second), and notify waiting workers asynchronously via a queue, Redis pub/sub, or database listener. Doing heavy work inline inside the webhook handler is the #1 cause of timeouts and flaky OTP pipelines.
If you have already started automating OTP testing with the CrabSMS API, switching from tight polling loops to webhooks cuts wasted requests and delivers verification codes the moment the physical US SIM receives them. The catch is that webhooks run over real internet HTTP connections, so your receiver needs a few simple production habits from day one.
Always check the live CrabSMS API documentation for exact payload field names, authentication headers, and endpoint specs before deploying your integration.
1. Acknowledge fast, process asynchronously
Never run a Playwright click, send an outbound email, or wait on a third-party API inside the HTTP request handler that receives an SMS webhook. Keep the handler boring and fast:
- Parse and verify the incoming request body and headers according to the API docs.
- Write the raw event (
order_id,number,message_id, raw SMS body, timestamp) into your fast store (Postgres, Redis, or an in-memory map for ephemeral CI runners). - Return
200 OKimmediately so the sender knows delivery succeeded. - Wake up the waiting test runner or worker asynchronously.
// Minimal Express-style webhook handler pattern (check API docs for exact payload schema)
import express from "express";
const app = express();
app.use(express.json({ limit: "64kb" }));
// Keyed by orderId -> Set of seen messageIds for idempotency
const seenMessages = new Set();
const inboxByOrder = new Map();
app.post("/webhooks/crabsms", (req, res) => {
const event = req.body || {};
const orderId = String(event.order_id || "");
const messageKey = String(event.message_id || `${orderId}:${event.received_at || event.code || ""}`);
if (!orderId) {
return res.status(400).json({ error: "missing order_id" });
}
// Idempotent guard: ignore duplicate retries safely
if (!seenMessages.has(messageKey)) {
seenMessages.add(messageKey);
const list = inboxByOrder.get(orderId) || [];
list.push(event);
inboxByOrder.set(orderId, list);
}
// Acknowledge immediately before downstream consumers act
return res.status(200).json({ ok: true });
});
2. Design for idempotency and out-of-order delivery
In distributed systems, “at-least-once” delivery means your endpoint can receive the exact same webhook twice if a network hiccup drops the acknowledgment packet. If your receiver blindly appends messages or re-submits an already-used OTP form on every POST, duplicate retries break your state machine.
Deduplicate every incoming SMS using a unique delivery key (or (order_id, code, timestamp) composite unique index in SQL) so processing the same webhook twice produces the exact same stored state.
3. Match strictly by order ID, never “latest SMS”
One shortcut causes endless mysterious test failures: reading SELECT * FROM sms_events ORDER BY created_at DESC LIMIT 1.
That query works fine when one developer runs one test on Friday afternoon. On Monday morning, when five CI builds or two staging services order US numbers at the same second, Worker A grabs Worker B’s six-digit code and both runs fail. Key every lookup strictly on the order_id returned at order creation (and clean up stale entries after your order TTL).
4. Pair webhooks with a gentle polling fallback
What happens if your staging tunnel restarts right in the middle of a 30-second verification window? A hybrid listener gives you the speed of webhooks with zero single point of failure:
| Mechanism | Role in your backend | Recommended cadence |
|---|---|---|
| Incoming webhook | Primary instant delivery path | Real-time push as SMS lands |
| Order status fallback poll | Safety net if a webhook is missed | Check once after 20-30s, then every 10-15s |
| Overall OTP wait timeout | Clean failure + refund boundary | 90 to 120 seconds before aborting |
Remember that on CrabSMS temporary orders, if no SMS ever arrives before the number expires, the full order price returns to your balance automatically. Read how refunds work when no SMS arrives and our guide on why verification codes sometimes fail to arrive so your retry alerts separate carrier/app issues from webhook outages.
Quick observability habit Always log the CrabSMS
order_idand HTTP status code in your structured logs while redacting the actual OTP digits (code: "[REDACTED]"). If you ever need human help diagnosing an order, sharing thatorder_idlets our team check carrier logs right away.
5. Testing webhooks locally without headaches
During local development, you do not need to deploy to production just to test your JSON parser:
- Replay sample
curlPOST payloads againsthttp://localhost:3000/webhooks/crabsmsfirst to verify validation,400handling, and duplicate deduplication. - Use a short-lived HTTPS tunnel when testing against live physical US SIM deliveries from your laptop, then point your dedicated staging/CI webhook URL to a stable HTTPS endpoint behind TLS.
- Keep separate API keys or separate tags for staging vs production so test traffic never pollutes production analytics.
Building a higher-volume SMS verification integration or choosing the right mix of temporary numbers and long-term rentals? Check the API Docs or message our team directly on the Contact page.
Frequently asked questions
Why should my webhook endpoint return HTTP 200 before running slow business logic?
Webhook senders enforce tight HTTP timeouts. If your handler blocks on database migrations, browser steps, or external API calls before responding, the delivery can time out and trigger unnecessary duplicate retries.
How should I correlate an incoming SMS webhook to a specific verification flow?
Store the order identifier and assigned E.164 phone number when you place the order, then index your incoming webhook records by that order identifier rather than reading the most recent global message.
What if my local development server does not have a public HTTPS URL?
Use a temporary HTTPS tunnel during local development to test your webhook receiver, or fall back to timed status polling in local runs while using real webhooks in staging and CI.
Where can I check the exact CrabSMS webhook headers and JSON fields?
Always check the live CrabSMS API documentation in your portal for current endpoint URLs, authentication headers, and exact webhook payload field names.
How should my backend handle duplicate webhook deliveries for the same SMS?
Make your webhook consumer idempotent by storing each incoming message or delivery ID with a unique database constraint, so network retries never process the same OTP code twice.
Explore live endpoints, webhook payloads, and authentication details in the official documentation.