Back to blog
Developers 8 min read

Automate OTP testing with the CrabSMS API

Order numbers, wait for the webhook and read codes from your test suite.

Terminal preview showing a POST request to order a US number and an incoming sms.received webhook payload
On this page
  1. Choosing temporary numbers vs rentals for automated tests
  2. Architecture: webhooks first, polling fallback
  3. Parsing OTP codes defensively
  4. Handling timeouts, retries, and automatic refunds
  5. Security checklist for API credentials in CI
  6. Frequently asked questions

To automate SMS OTP testing with the CrabSMS API, create an API key in your dashboard, request a SIM-backed US non-VoIP number over REST at the start of your test case, pass that number into your app’s sign-up screen, and capture the arriving code via an incoming SMS webhook (with a short polling fallback). Because every line runs on a real US carrier SIM, your end-to-end tests exercise real carrier SMS routing instead of mocked stubs.

Mocking OTP checks works fine in unit tests, yet real production bugs almost always hide in the integration layer: broken SMS provider credentials, misformatted E.164 prefixes, carrier short-code filtering, or race conditions between code expiration and user submission. Testing against real US SIM lines catches those regressions before real users hit them.

This guide outlines a clean, reliable test architecture you can drop into Playwright, Cypress, Pytest, or any backend CI pipeline. Always review the live endpoint schemas, auth headers, and webhook payload fields in the official CrabSMS API documentation before shipping code.

Choosing temporary numbers vs rentals for automated tests

Different test suites need different phone number lifecycles. Matching the right order type keeps test flakiness low and budgets predictable.

Test pattern Recommended product Why it works cleanly
Fresh account registration (E2E) Temporary number (5-10 min) Clean unused number per test run; automatic balance refund if test aborts before SMS
Repeated login 2FA / password reset checks Long-term rental (3, 7, 14, or 30 days) Fixed phone number wired to a dedicated staging account across many builds
Smoke tests across multiple environments One shared CrabSMS balance Order temporary lines and renew rentals via the same API key

If you are weighing durations for a staging environment, read our breakdown of temporary numbers vs long-term rentals.

Architecture: webhooks first, polling fallback

A clean automated OTP flow follows four stages:

  1. Order a US number: Call the order creation endpoint for your target service or rental window and store the returned order_id and E.164 number.
  2. Trigger the OTP in your app: Enter the assigned US number into your registration or login form via Playwright, Selenium, or a direct HTTP call to your staging backend.
  3. Receive the SMS: Listen for the incoming SMS webhook on your test runner or staging receiver, match it by order_id or number, and extract the numeric passcode. For production webhook architecture, idempotency, and retry handling, see how to receive SMS webhooks reliably in your backend.
  4. Clean up and assert: Submit the code, assert the verified session state, and log the order_id in your CI artifact output so failures are effortless to inspect.
# Conceptual workflow: check https://portal.crabsms.com/api/docs for exact paths and fields
POST /v1/orders
Authorization: Bearer $CRABSMS_API_KEY
Content-Type: application/json

{ "service": "your_service", "type": "temporary" }
# -> { "order_id": "ord_94812", "number": "+15550142093", "status": "active" }

# Incoming webhook pushed to your endpoint as soon as the SIM receives the SMS
webhook sms.received
{ "order_id": "ord_94812", "number": "+15550142093", "code": "482917" }

Parsing OTP codes defensively

Never assume every SMS template has the same word order forever. Copywriters tweak notification text all the time (“Your code is 482917” becomes “482917 is your verification code for AppName. Expires in 10 minutes.”).

A small helper that handles both explicit parsed code fields and raw SMS text keeps tests from breaking when copy changes:

export function extractOtpCode(payload) {
  if (payload && typeof payload.code === "string" && payload.code.trim()) {
    return payload.code.trim();
  }
  const text = String(payload?.text || payload?.message || "");
  // Match 4 to 8 consecutive digits while ignoring phone numbers with +1
  const cleaned = text.replace(/\+\d[\d\s-]{8,}/g, " ");
  const match = cleaned.match(/\b(\d{4,8})\b/);
  if (!match) {
    throw new Error(`No OTP digits found in SMS payload: ${text}`);
  }
  return match[1];
}

Tip for parallel CI jobs Always key your webhook inbox map by order_id (or full E.164 phone number), never by “latest SMS received”. When four GitHub Actions shards run in parallel, matching by order_id guarantees test worker A never reads test worker B’s verification code.

Handling timeouts, retries, and automatic refunds

Carrier SMS delivery normally takes a few seconds, though real wireless networks occasionally experience 20 to 60 second spikes. Build three safeguards into your test helper:

  • Use realistic timeouts: Wait at least 90 to 120 seconds for an incoming OTP before failing a step, rather than timing out after 10 seconds.
  • Avoid aggressive resend loops: Sending five OTP requests inside 15 seconds triggers your own app’s rate limiter and makes debugging harder. See why verification codes sometimes fail to arrive.
  • Rely on automatic balance refunds: If your CI runner crashes before triggering an SMS, or if your staging SMS provider fails to transmit, CrabSMS automatically refunds temporary orders that expire with zero SMS received. Details are documented in how refunds work when no SMS arrives.
  • Check live availability gracefully: Physical SIM inventory fluctuates throughout the day. If a specific service has zero stock during a spike, log the status cleanly and retry on a short backoff instead of throwing an unhandled null error. You can see how we track live inventory in new apps added to CrabSMS this month.

Security checklist for API credentials in CI

  • Store your CrabSMS API key strictly in encrypted CI secrets (GitHub Actions Secrets, GitLab CI Variables, or a vault), never committed to source control.
  • Verify webhook authenticity and ignore unexpected payloads before pushing events into your test queue.
  • Redact incoming SMS bodies and OTP values from public CI logs so real session codes never leak in build traces.

Need help setting up higher-volume testing or choosing the right mix of temporary numbers and rentals for your engineering team? Read the API Docs or message our team directly on the Contact page.

Frequently asked questions

Where do I get a CrabSMS API key?

Sign in to your CrabSMS dashboard and create an API key from your account settings. All API orders draw from the same balance you use in the web portal.

Should my test suite use webhooks or polling to read incoming OTPs?

Webhooks are preferred for CI and backend integrations because CrabSMS pushes incoming messages to your server as soon as the SIM receives them. Pairing webhooks with a timed polling fallback makes test runs resilient if a local dev tunnel drops.

Can I automate both temporary numbers and long-term rentals through the API?

Yes. You can order temporary verification numbers for fresh sign-up tests as well as manage long-term rentals, renewals, and message history programmatically.

What happens to my API balance if a test fails to trigger an SMS?

If no SMS arrives on a temporary order before it expires, the full order cost returns to your CrabSMS balance automatically, just like manual orders in the dashboard.

How do I run parallel CI test workers without mixing up verification codes?

Create a separate CrabSMS order for each parallel test worker and key your incoming webhook records by order identifier rather than reading the latest global message, so concurrent sign-up flows stay completely isolated.

Ready to wire SMS verification into CI?

Create an API key in your dashboard, inspect the REST endpoints, and test against physical US SIM cards.

Read the API docs

Keep reading

All articles
All articles

Get new guides on Telegram

We post new articles, newly supported apps and promo codes in the CrabSMS News channel.