# Claywire API: WhatsApp OTP and template messages

> Send WhatsApp one-time codes for login/signup, and send approved WhatsApp templates (one or bulk), from your own server. Messages go out from the Claywire customer's own connected WhatsApp number.

Base URL: https://www.claywire.in/api/v1
Human docs: https://www.claywire.in/docs/api

## Rules for integrators (and AI coding agents)

- Call the API from a SERVER only. The API key can send billed messages; never put it in frontend code, a mobile app, or a git repo. Read it from an env var, e.g. `CLAYWIRE_API_KEY`.
- Send JSON with `Content-Type: application/json` and `Authorization: Bearer <key>`. Keys look like `cw_live_` followed by 43 characters.
- Phone numbers must include the country code: `+919876543210`. Spaces and dashes are tolerated.
- Never generate, store or log OTP codes yourself. Claywire generates the code, sends it, and keeps only a hash. You store only the `id` returned by send.
- Branch on HTTP status and `error.code`, never on `error.message` text (messages may change).
- On 429, wait the number of seconds in the `Retry-After` header.
- Send an `Idempotency-Key` header (a UUID per logical send) on `/otp/send` and `/messages/*`. If your request times out, retry with the SAME key: Claywire returns the first response (with `Idempotent-Replayed: true`) instead of sending again. Keys are per API key and kept 24 hours. A failure before anything was sent can be retried with the same key; a failure after sending began is final for that key, so a retry never sends twice.

## Prerequisites (done once by the Claywire workspace owner, in the dashboard)

1. WhatsApp number connected (Settings → Integrations) and the account approved for live messaging.
2. For OTP: an approved OTP template (Settings → Templates → OTP template).
3. For template messages: an approved template with a text header or no header.
4. An API key (Settings → Developers) with scope `otp`, `messages`, or both.

## POST /otp/send

Send a one-time code on WhatsApp.

Request body:

| Field | Type | Required | Notes |
|---|---|---|---|
| to | string | yes | Recipient phone, E.164 |
| codeLength | integer | no | 4-8, default 6 |
| ttlSeconds | integer | no | 60-900, default 300 |
| template | string | no | OTP template name; default is the oldest approved one |
| language | string | no | Template language code, e.g. `en` |

Response `201`:

```json
{ "id": "8f1c2b3a-5d6e-4f70-8a9b-0c1d2e3f4a5b", "expiresAt": "2026-11-16T12:05:00.000Z" }
```

Store `id` server-side (e.g. in the session) until the user enters the code.

Limits: one code per phone every 30 s, at most 5 per phone per 10 minutes, 60 sends per minute per key.

## POST /otp/verify

Request body: `{ "id": "<id from send>", "code": "482913" }` (code is 4-8 digits).

A well-formed request always returns `200`:

```json
{ "verified": true }
```

or

```json
{ "verified": false, "reason": "invalid_code" }
```

`reason` is one of: `invalid_code`, `expired`, `too_many_attempts`, `already_used`, `not_found`. Each code allows 5 attempts and can be used once. Log the user in only when `verified` is `true`.

## POST /messages/template

Send one approved template.

```json
{ "to": "+919876543210", "template": "order_shipped", "language": "en", "variables": { "1": "Asha", "2": "#4821" } }
```

`variables` fill the template's {{1}}, {{2}} placeholders, keyed by number; every placeholder needs a value. `language` is optional.

Response `201`: `{ "id": "wamid.HBgM...", "status": "sent" }`

## POST /messages/template/bulk

One template to up to 100 recipients, each with its own variables.

```json
{
  "template": "order_shipped",
  "recipients": [
    { "to": "+919876543210", "variables": { "1": "Asha", "2": "#4821" } },
    { "to": "+919812345678", "variables": { "1": "Ravi", "2": "#4822" } }
  ]
}
```

Response `200`:

```json
{
  "sent": 1, "failed": 0, "skipped": 1,
  "results": [
    { "to": "+919876543210", "status": "sent", "id": "wamid.HBgM..." },
    { "to": "+919812345678", "status": "skipped", "error": { "code": "forbidden", "message": "This number has opted out." } }
  ]
}
```

`results` is in request order. `skipped`: invalid, duplicate or opted-out number, or bad variables. `failed`: WhatsApp refused it, or the balance ran out (`insufficient_balance`; the rest of the batch fails the same way). Up to 5 sends run in parallel, so 100 recipients take a few seconds; set your HTTP client timeout to at least 60 s. For more than 100, call repeatedly.

## Errors

Every non-2xx response:

```json
{ "error": { "code": "rate_limited", "message": "Wait 24s before sending another code to this number." } }
```

| Status | code | Meaning |
|---|---|---|
| 400 | invalid_request | Malformed JSON or invalid field |
| 401 | unauthorized | Key missing, invalid or revoked |
| 402 | insufficient_balance | Claywire credits or WhatsApp wallet too low |
| 403 | forbidden | Key lacks the scope, WhatsApp not connected, or number opted out |
| 403 | workspace_not_live | Claywire account not approved for live messaging yet |
| 404 | not_found | No template with that name |
| 409 | template_not_approved | Template not approved by Meta (or no approved OTP template) |
| 409 | idempotency_in_progress | A request with this Idempotency-Key is still running; retry after Retry-After |
| 422 | idempotency_key_reused | This Idempotency-Key was used for a different request |
| 429 | rate_limited | Too many requests; see Retry-After |
| 500 | internal_error | Retry with backoff |
| 502 | provider_error | WhatsApp refused the message; message says why |

## Reference implementation (Node.js / TypeScript, server side)

```ts
const CLAYWIRE = "https://www.claywire.in/api/v1";

async function claywire<T>(path: string, body: unknown): Promise<{ status: number; data: T }> {
  const res = await fetch(CLAYWIRE + path, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.CLAYWIRE_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify(body),
    signal: AbortSignal.timeout(15_000),
  });
  return { status: res.status, data: (await res.json()) as T };
}

type ApiError = { error: { code: string; message: string } };

/** Returns the OTP id to keep in the session, or throws with Claywire's error code. */
export async function sendOtp(phone: string): Promise<string> {
  const { status, data } = await claywire<{ id: string } & ApiError>("/otp/send", { to: phone });
  if (status !== 201) throw Object.assign(new Error(data.error.message), { code: data.error.code, status });
  return data.id;
}

/** True only when the code is correct, unexpired and unused. */
export async function verifyOtp(id: string, code: string): Promise<{ ok: boolean; reason?: string }> {
  const { status, data } = await claywire<{ verified: boolean; reason?: string } & ApiError>("/otp/verify", { id, code });
  if (status !== 200) throw Object.assign(new Error(data.error.message), { code: data.error.code, status });
  return { ok: data.verified === true, reason: data.reason };
}
```

Login flow: phone form → your backend calls `sendOtp` and saves the id in the session → code form → your backend calls `verifyOtp(sessionId, code)` → on `ok`, create the user session and clear the saved id.

## Python (requests)

```python
import os, requests

BASE = "https://www.claywire.in/api/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['CLAYWIRE_API_KEY']}"}

def send_otp(phone: str) -> str:
    r = requests.post(f"{BASE}/otp/send", json={"to": phone}, headers=HEADERS, timeout=15)
    if r.status_code != 201:
        raise RuntimeError(r.json()["error"]["code"])
    return r.json()["id"]

def verify_otp(otp_id: str, code: str) -> bool:
    r = requests.post(f"{BASE}/otp/verify", json={"id": otp_id, "code": code}, headers=HEADERS, timeout=15)
    r.raise_for_status()
    return r.json()["verified"] is True
```

## Prompt for an AI coding agent

Paste this into Claude Code, Cursor or Codex inside the app you're integrating:

```
Integrate WhatsApp OTP login using the Claywire API.
Read the spec at https://www.claywire.in/docs/api.md first and follow it exactly.

- Server side only. Read the key from the env var CLAYWIRE_API_KEY; never send it to the browser or commit it.
- Add two backend endpoints to this app: one that calls POST /otp/send with the user's phone (E.164, with country code) and stores the returned id in the user's session, and one that calls POST /otp/verify with that id and the code the user typed.
- Only log the user in when verify returns {"verified": true}. Show a clear message for each "reason" and for 429 (use Retry-After).
- Add a phone input step and a 6-digit code input step to the existing login/signup UI, matching its current styling.
- Write tests that mock the Claywire API.
```

## Webhooks (events pushed to your server)

Add an endpoint in Settings → Developers → Webhooks. You get a signing secret (`whsec_…`) once. Claywire then POSTs JSON events to your HTTPS URL:

```json
{ "id": "6f1c…", "type": "message.status", "created_at": "2026-11-20T10:00:05.000Z",
  "data": { "message_id": "wamid.HBgM...", "status": "read", "to": "919876543210", "kind": "otp", "timestamp": "2026-11-20T10:00:04.000Z" } }
```

| type | When | data |
|---|---|---|
| message.status | A message you sent with this API is sent, delivered, read or failed | message_id, status, to, kind (`otp` or `template`), timestamp |
| message.received | A customer messaged your WhatsApp number | message_id, from, type (`text`, `image`, …), text, timestamp |

Rules for receivers:

- Verify the `Claywire-Signature` header before trusting a request: `t=<unix seconds>,v1=<hex HMAC-SHA256(secret, "<t>.<raw body>")>`. Use the RAW request body, compare in constant time, and reject a `t` more than 300 seconds from now.
- Answer 2xx within 10 seconds, then do your work. Non-2xx, timeouts and redirects count as failures and are retried with backoff (6 attempts in total).
- Deliveries can repeat or arrive out of order. Deduplicate on `id`; for status, keep the most advanced (`sent` < `delivered` < `read`).

```ts
import { createHmac, timingSafeEqual } from "node:crypto";

export function verifyClaywire(rawBody: string, header: string | null, secret: string): boolean {
  if (!header) return false;
  const parts = Object.fromEntries(header.split(",").map((p) => p.split("=") as [string, string]));
  const t = Number(parts.t);
  if (!Number.isInteger(t) || Math.abs(Date.now() / 1000 - t) > 300) return false;
  const expected = createHmac("sha256", secret).update(`${t}.${rawBody}`).digest();
  const given = Buffer.from(parts.v1 ?? "", "hex");
  return given.length === expected.length && timingSafeEqual(given, expected);
}
```

## Not available yet

SMS fallback and media-header templates. Contact team@claywire.in if you need one.
