WhatsApp Outbound API
All docs Platform API Sign in

WhatsApp Outbound API

Send approved WhatsApp template messages from your own backend — order confirmations, OTPs, campaigns — and track delivery per recipient.

Overview

The API is REST over HTTPS, JSON in and JSON out. There is one base URL:

https://everysecond.ai/api/v1/whatsapp

Everything you send goes out as a Meta-approved template from the WhatsApp number connected to your project. Three calls cover most integrations: list templates, read a template's required parameters, send.

One key, one project. Your API key is the project selector. A key for project “Ready Car” only ever sees Ready Car's templates, Ready Car's WhatsApp number and Ready Car's campaigns — even if you own ten other projects on the same account. You never pass a project id anywhere.

Authentication

Send your project API key (es_…) on every request, as a bearer token or an X-Api-Key header — both are equivalent:

Authorization: Bearer es_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# or
X-Api-Key: es_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Where to find your key

Dashboard → Integration → your agent → API key. Each agent has its own key; generate or rotate it there. The same key serves the chat API, the leads feed, webhooks management and orders.

Keep keys server-side. A project key can send WhatsApp messages and spend credits. Never ship it in a browser bundle, mobile app or public repo. Rotate it on the Integration screen if it leaks — generating a new key immediately invalidates the old one.

SituationStatusBody
No key sent401Missing API key. Send it as "Authorization: Bearer <key>" or "X-Api-Key".
Unknown / rotated key401Invalid API key.
Feature disabled by an admin403This feature is currently disabled.

Quickstart

From zero to a delivered message in four calls.

1 — List the templates this project can send

curl -s -H "Authorization: Bearer $KEY" \
  https://everysecond.ai/api/v1/whatsapp/templates

2 — Read what the template needs

curl -s -H "Authorization: Bearer $KEY" \
  https://everysecond.ai/api/v1/whatsapp/templates/19/schema

The example_recipient in the response is a ready-to-copy recipient object containing only the fields this template requires.

3 — Send

curl -s -X POST https://everysecond.ai/api/v1/whatsapp/send \
  -H "Authorization: Bearer $KEY" \
  -H 'Content-Type: application/json' \
  -d '{
        "name": "Order confirmations",
        "template_id": 19,
        "recipients": [
          { "phone": "01207256335",
            "variables": { "1": "Ahmed", "2": "RC-10293", "3": "2x oil filter", "4": "1450 EGP" } }
        ]
      }'

4 — Check delivery

curl -s -H "Authorization: Bearer $KEY" \
  https://everysecond.ai/api/v1/whatsapp/campaigns/88/recipients

Nothing partial ever happens. If any recipient is missing a variable or has an undeliverable number, the whole call fails with 422 and a list of exactly what to fix. No campaign is created, nothing is queued, no credits are spent.

Responses & errors

Success payloads are always under data:

{ "data": { … } }

Every failure — including field validation — uses the same envelope: an error sentence, plus details when more than one thing needs fixing.

{
  "error": "Validation failed.",
  "details": [
    "Recipient #1: variable {{2}} (Discount Code) is required.",
    "Recipient #2 (12345): Too short for country code +20."
  ]
}

Messages are written to be shown to a human operator as-is — they name the recipient, the field and the fix. Parse details when you need to map errors back to rows in your own system.

StatusMeaningWhat to do
200OK—
201Campaign createdStore data.id to poll later
401Missing / invalid keyCheck the header and that the key wasn't rotated
402Not enough WhatsApp creditsRead details.credits_required vs details.credits_balance, top up
403Feature disabled platform-wideContact support
404Template / account / campaign not in this key's projectYou are probably using another project's key
409Project has no connected WhatsApp numberConnect one in the dashboard first
422Payload or recipient validation failedFix everything in details and retry
429Rate limitedWait Retry-After seconds

Rate limits

120 requests per minute per API key, shared with every other /api/v1 group the same key calls (chats, leads, orders, reservations, webhooks, agent). Every response carries your current budget:

X-RateLimit-Limit: 120
X-RateLimit-Remaining: 118

Exceeding it returns 429 with a Retry-After header (seconds). This limits API calls, not messages — one call can carry 5000 recipients, so batch instead of looping one request per contact.

LimitValue
Requests per minute, per key (all /api/v1 groups together)120
Recipients per campaign5000
Send pacing~1 message/second, staggered automatically
Header mediaMeta's own per-type size limits apply. The file is downloaded with a 30-second timeout and the upload is cached per sending number + URL for 12 hours

Endpoint reference

All paths are relative to https://everysecond.ai/api/v1/whatsapp.

GET/templates

The approved templates this key's project can actually send, with what each message costs in credits. Meta approves a template per WhatsApp Business account, so only templates approved on one of the project's own numbers are listed (with no number connected yet, every approved template of the project is listed). approved_on_waba_ids names the accounts (waba_id in GET /accounts) each one can be sent from.

{
  "data": [
    { "id": 19, "name": "order_confirmation", "category": "UTILITY",
      "language": "en_US", "status": "approved",
      "approved_on_waba_ids": ["925460023398932"], "credits_per_message": 1 }
  ],
  "project": { "id": 128, "name": "Ready Car" }
}

The project object echoes which project the key resolved to — the fastest way to confirm you are using the key you think you are.

GET/templates/{id}/schema

The contract for one template: exactly what each recipient must supply. It works for a template in any status (draft, pending, rejected…), so you can build the payload before Meta approves it — check status before sending.

{
  "data": {
    "id": 19, "name": "order_confirmation", "category": "UTILITY",
    "language": "en_US", "status": "approved",
    "body_text": "Hello {{1}}, order #{{2}} … total {{4}}",
    "variables": [
      { "key": "1", "label": "Customer Name", "example": "John", "required": true },
      { "key": "2", "label": null, "example": "10293", "required": true }
    ],
    "header": { "type": "IMAGE", "media_required": true, "text": null, "variables": [] },
    "button": { "has_dynamic_url": true, "required": true },
    "buttons": [
      { "index": 0, "type": "URL", "text": "Track order",
        "url": "https://shop.example/track/{{1}}", "input": "button_urls.0",
        "alias": "button_url", "example": "https://shop.example/track/ABC123", "required": true }
    ],
    "credits_per_message": 1,
    "example_recipient": {
      "phone": "+201012345678",
      "name": "optional",
      "variables": { "1": "John", "2": "10293" },
      "header_media_url": "https://example.com/media.jpg",
      "button_url": "https://shop.example/track/ABC123"
    }
  }
}
FieldMeaning
body_textThe approved body, with {{n}} placeholders in position
variables[].keyThe placeholder index — the key you use in variables
variables[].labelFriendly name if the template was built in EverySecond; null for templates synced from Meta
variables[].exampleThe sample value approved with the template — shows what belongs there
variables[].requiredfalse only for the code of an AUTHENTICATION template (generated_if_missing: true) — leave it out and one is generated per recipient
header.media_requiredtrue ⇒ every recipient needs header_media_url
header.text / header.variables[]A TEXT header and its {{n}} placeholders. Each entry's input (header_variables.1) is the recipient field to fill
button.has_dynamic_urltrue ⇒ the template has at least one URL button ending in {{1}}
buttons[]Every dynamic URL button: its position index, text, url and the recipient field to fill (input = button_urls.{index}; the first one also answers to alias button_url)
example_recipientCopy-paste starting point containing only the fields this template needs (button_url with one dynamic button, button_urls with two)

Templates belonging to another project return 404.

GET/accounts

The numbers this key can send from: the project's own WhatsApp number (kind: agent — the agent answers the replies) first, then the account's campaign numbers (kind: campaign, label = the name the owner gave it; no agent answers them, replies land in Conversations). Omit account_id when sending and the one flagged is_default is used — most integrations never call this endpoint; pass a campaign number's id as account_id to send from it. connected: false = Meta disconnected the number.

{
  "data": [
    { "id": 41, "kind": "agent", "label": null, "display_phone_number": "+20 10 35983229",
      "phone_number_id": "1001147353092199", "waba_id": "925460023398932",
      "connected": true, "is_default": true },
    { "id": 52, "kind": "campaign", "label": "Offers", "display_phone_number": "+20 10 55501010",
      "phone_number_id": "1180034412235511", "waba_id": "431100982215543",
      "connected": true, "is_default": false }
  ],
  "project": { "id": 128, "name": "Ready Car" }
}

GET/credits

Wallet balance and per-category pricing. Poll this before a large campaign to fail early.

{
  "data": {
    "balance": 4232,
    "cost_per_message": { "MARKETING": 1, "UTILITY": 1, "AUTHENTICATION": 1 }
  }
}

POST/send

Create a campaign and dispatch it immediately. This is the endpoint most integrations use.

FieldRequiredNotes
namerequiredLabel shown in the dashboard, ≤ 255 chars
template_idrequiredAn approved template of this project
account_idoptionalDefaults to the project's own number
recipientsrequired1–5000 recipient objects
skip_invalid_phonesoptionalDefault false. true leaves out numbers that fail validation (listed under data.skipped) instead of refusing the whole request — see Phone numbers
POST https://everysecond.ai/api/v1/whatsapp/send

{
  "name": "June Promo",
  "template_id": 12,
  "recipients": [
    {
      "phone": "01207256335",
      "name": "Ahmed",
      "variables": { "1": "Ahmed", "2": "SAVE20" },
      "header_media_url": "https://cdn.example.com/promo.jpg"
    }
  ]
}

Response 201:

{
  "data": {
    "id": 88, "name": "June Promo", "status": "queued", "template_id": 12,
    "project_id": 130, "phone_number_id": "996754190191551",
    "total_recipients": 1, "sent": 0, "delivered": 0, "read": 0, "failed": 0,
    "progress_percent": 0,
    "created_at": "2026-06-14T10:00:00+00:00", "completed_at": null
  }
}

total_recipients always equals the number of recipients you sent — invalid rows are rejected up front rather than silently dropped (or listed under skipped with skip_invalid_phones). For an AUTHENTICATION template the response also carries otp_codes — the code each recipient gets — see Authentication (OTP) templates.

The wallet is checked here: if it cannot cover credits_per_message × total_recipients you get 402 and no campaign is left behind.

POST/campaigns

Identical payload and checks to /send, but the campaign is created as a draft and nothing is queued or charged. Use this when a human should review the list in the dashboard before it goes out, then call the endpoint below. No credit check happens here — 402 only comes from the two send endpoints.

POST/campaigns/{id}/send

Dispatches a draft — one made through the API or in the dashboard. Returns the campaign payload with status: "queued".

It applies the dashboard's own rule: a draft is never dispatched while one of its numbers is invalid (a dashboard upload keeps invalid rows so they can be fixed inline). You get 422 listing them — fix or remove them on the campaign page, or send again with {"skip_invalid_phones": true}: the invalid rows are then removed (as the dashboard's Remove does), returned under data.skipped as {"recipient_id", "phone", "error"}, and the rest is sent.

{
  "error": "1 recipient number(s) are invalid. Fix or remove them on the campaign page, or send again with \"skip_invalid_phones\": true to leave them out.",
  "details": ["Recipient 12345: Too short for country code +20."]
}

Other errors: 422 if it is not a draft (the message names its current status) or has no valid recipients; 402 if the wallet cannot cover it (the draft is kept).

POST/campaigns/{id}/cancel

Stops a queued or processing campaign. Recipients that have not gone out are marked failed with Cancelled by user. Nothing is reserved up front — credits are only taken as each message is handed to Meta — so cancelled recipients simply cost nothing. Messages already handed to Meta cannot be recalled. A draft (or a finished campaign) cannot be cancelled: 422 naming its status — a draft never sends by itself anyway.

GET/campaigns/{id}

Poll for progress. Counters are updated from Meta's delivery webhooks.

{
  "data": {
    "id": 88, "status": "completed", "total_recipients": 250,
    "sent": 250, "delivered": 244, "read": 180, "failed": 6,
    "progress_percent": 100, "completed_at": "2026-06-14T10:04:11+00:00"
  }
}

GET/campaigns/{id}/recipients

Where a failure explains itself. Paginated with ?per_page= (max 500).

{
  "data": [
    { "id": 501, "phone": "201207256335", "name": "Ahmed", "status": "read",
      "error": null, "wa_message_id": "wamid.HBg…",
      "sent_at": "2026-06-14T10:00:03+00:00", "credits": 1, "refunded_at": null },
    { "id": 502, "phone": "201000000000", "name": null, "status": "failed",
      "error": "Template is paused due to quality.", "wa_message_id": null, "sent_at": null,
      "credits": 0, "refunded_at": "2026-06-14T10:00:04+00:00" }
  ],
  "meta": { "campaign_id": 88, "current_page": 1, "last_page": 1, "total": 2 }
}

error carries Meta's own rejection text, so you get the real reason (paused template, invalid media, re-engagement window) rather than a generic failure. credits is what the recipient cost — 0 once refunded, and refunded_at says when. For an AUTHENTICATION campaign each row also has otp_code, the code that recipient was sent.

The recipient object

FieldRequiredNotes
phonealwaysLocal or international; normalized and validated — see Phone numbers
variablesif the body has {{n}}Object keyed by the placeholder index as a string: {"1":"Ahmed"}. Every placeholder must be present and non-empty (the code of an AUTHENTICATION template may be left out — it is generated)
header_variablesif header.variables is not emptyThe {{n}} of a TEXT header, keyed like variables: {"1":"RC-10293"}
header_media_urlif header.media_requiredA valid URL (max 2048) of the image/video/PDF, reachable from EverySecond. Downloaded and uploaded to Meta at send time
button_urlif button.has_dynamic_urlValue for the first dynamic URL button: either the part that replaces {{1}} or the full link (trimmed to that part). A plain string, not validated as a URL, max 2048. variables.button_url is accepted too
button_urlsfor every buttons[] entryObject keyed by the button's index from the schema: {"1":"AB12","2":"https://shop.example/pay/INV-9"}. Same value rules as button_url; needed for a second dynamic button, optional for the first when button_url is given
country_codeoptionalDial code for this recipient, e.g. "44". Overrides the sender's country when normalizing a local number
nameoptionalDisplay label in the dashboard only — it is not inserted into the message

name does not fill {{1}}. If your template greets the customer by name, that name must also be passed in variables.

Template parameters

Body variables

Templates carry numbered placeholders. Supply every one, keyed by its index as a string, in any order:

// body: "Hello {{1}}, order #{{2}} total {{4}}"
"variables": { "1": "Ahmed", "2": "RC-10293", "3": "2x oil filter", "4": "1450 EGP" }

Missing one returns a message naming it exactly: Recipient #1: variable {{3}} is required.

Meta rejects variable values containing newlines, tabs, or 5+ consecutive spaces. Keep each value on one line — multi-line order contents should be joined with commas or " • ".

Media headers

When header.media_required is true, every recipient needs header_media_url. The URL only has to be reachable from EverySecond's servers — the file is uploaded to Meta before sending, so pre-signed and short-lived URLs work.

Text header variables

A TEXT header can carry a placeholder too ("Order {{1}}"). The schema lists it under header.variables; pass its value per recipient in header_variables:

"header_variables": { "1": "RC-10293" }

Dynamic URL buttons

Every URL button whose link ends in {{1}} needs a value per recipient — typically a per-customer tracking or checkout link. The schema lists each one under buttons[] with its index. With one such button, pass button_url; with two, pass button_urls keyed by index (button_url keeps filling the first):

// buttons: index 1 "Track" https://shop.example/track/{{1}}, index 2 "Pay" https://shop.example/pay/{{1}}
"button_urls": { "1": "AB12", "2": "https://shop.example/pay/INV-9" }

Send either the part that replaces {{1}} or the whole link — a value starting with the button's fixed prefix is trimmed to the suffix, so both lines above end up as AB12 / INV-9.

Authentication (OTP) templates

An AUTHENTICATION template always exposes exactly one variable, "1": the code. Pass your own, or omit variables entirely and a unique 6-digit code is generated per recipient (exactly as dashboard campaigns do) and echoed into both the body and the copy-code button. The send response hands every code back so you can verify the user:

"otp_codes": [
  { "index": 0, "recipient_id": 5012, "phone": "966501234567", "code": "482913", "generated": true },
  { "index": 1, "recipient_id": 5013, "phone": "966501234568", "code": "424242", "generated": false }
]

index is the position in your recipients array, generated says whether the platform made the code. GET /campaigns/{id}/recipients repeats it as otp_code.

Phone numbers

Numbers are stored and sent as international digits with no +. You can post whatever format your database holds:

You sendStored / sent asRule
01207256335201207256335Local number, given the sending number's country (Egypt)
201207256335201207256335Already international — untouched
+44 7911 123456447911123456Explicit +, punctuation stripped
0044791112345644791112345600 dialling prefix
07911123456 + "country_code":"44"447911123456Per-recipient country override

Every number is then validated offline against real per-country length and format rules, so a bad number is rejected at request time with a specific reason (Recipient #2 (12345): Too short for country code +20.) instead of being accepted by Meta and silently dropped as undeliverable.

Send to the good ones anyway: add "skip_invalid_phones": true next to recipients. Bad numbers are then left out instead of failing the whole request, and the response lists them as "skipped": [{"index": 0, "phone": "+205558852225", "error": "Not a valid number for country code +20"}] (index = position in your recipients array). If no number is valid the request is still refused with 422.

Sending to several countries? Either store numbers in full international format, or set country_code per recipient. Bare local numbers always inherit the sending number's country.

Delivery lifecycle

Campaign status

StatusMeaning
draftCreated via /campaigns, not yet dispatched
queuedJobs queued, the first message has not gone out yet
processingSending in progress (set when the first message starts going out); messages leave ~1/second
completedEvery recipient reached a final state and at least one was sent
failedEvery recipient failed — refused at send, unknown outcome, or a later failure receipt
cancelledStopped via /cancel

Recipient status

StatusMeaning
pendingQueued, not yet handed to Meta
sendingClaimed by a send job; the request to Meta is in flight (a few seconds)
sentAccepted by Meta; wa_message_id assigned
deliveredReached the handset
readOpened by the recipient
failedRejected — see error

Exactly once

Each recipient is sent at most once and charged at most once. A send job first claims the recipient, so two workers can never both send it. If the connection to Meta could not even be opened (DNS failure, connection refused, connect timeout) nothing left, and the send is retried automatically — up to 3 tries, 30 seconds apart, without charging again. If the request may have reached Meta but no answer came back (response timeout, connection dropped mid-response) it is never resent, to avoid a duplicate message: the recipient fails with an error starting with send_status_unknown and its credits are refunded.

delivered and read arrive asynchronously from Meta's webhooks, seconds to minutes later. Poll GET /campaigns/{id} every 10–30 seconds while progress_percent < 100; don't poll per recipient in a tight loop.

Replies to your messages

The agent never answers the first reply to a message you sent. When a template goes out to a customer — a campaign, POST /send, an order-status template — the customer's first message back to that number (text, voice note, photo, or a tap on a quick-reply button) is recorded in the conversation, shown in Tracking and the inbox as “Reply to campaign — not answered by the agent”, and left for your team. From the customer's second message on, the agent answers as usual — unless the chat is paused because a person took it over (a reply from your inbox or the WhatsApp Business app, or “Hand off”).

RuleDetail
Counts as “a reply”The customer's next message within 7 days of the send, to the number it was sent from. Later than that it is a new conversation and is answered.
A newer sendStarts the rule again: the first reply after each outbound message is held back.
Not affectedAuthentication (OTP) templates — a code invites no reply — and replies the agent sends inside an ongoing chat.
BillingThe unanswered message does not count toward the plan's message allowance.
Your systemsIt still fires message.received (and creates the lead as usual); no message.sent follows it.

Credits & billing

Outbound template messages are paid from the WhatsApp credit wallet, not your plan's chat-message quota. Credits are shared across all your projects.

  • Cost per message depends on the template category — see credits_per_message on any template.
  • A campaign is checked before it is queued (POST /send, POST /campaigns/{id}/send): if the balance can't cover it, you get 402 and nothing is queued. POST /campaigns does not check credits.
  • Nothing is reserved up front. Credits are taken once per message, as it is handed to Meta — a retry never charges again.
  • They are refunded automatically when Meta refuses the send, when the outcome is unknown (send_status_unknown), and when Meta accepts a message but later reports it as failed in a delivery receipt (Meta bills on delivery) — once per message.
{
  "error": "Not enough WhatsApp credits: this campaign needs 250 credit(s) for 250 recipient(s) but the balance is 40.",
  "details": { "credits_required": 250, "credits_balance": 40 }
}

Error catalogue

MessageStatusCause & fix
Template N was not found for project "X".404 The template belongs to a different project. Use that project's key, or pick an id from GET /templates.
Template "x" is "pending", not approved by Meta…422 Wait for Meta's approval; only approved templates can be sent.
Template "x" is approved on WhatsApp Business account A, but +20… belongs to B.422 The template is tied to another WABA. Send it from the matching number.
Project "X" has no connected WhatsApp number.409 Connect a number to that project in the dashboard.
WhatsApp account N is not connected to project "X".404 Drop account_id to use the project's default number.
Recipient #1: variable {{2}} (Discount Code) is required.422 Add the missing placeholder to that recipient's variables.
Recipient #1: header_media_url is required for this template (header format IMAGE).422 The template has a media header — every recipient needs a media URL.
Recipient #2 (12345): Too short for country code +20.422 Bad number. Fix it, or send country_code if it belongs to another country.
Recipient #1: header_variables.1 is required (the {{1}} in the template's text header).422 The template has a placeholder in its text header — pass header_variables.
Recipient #1: button_urls.2 is required (the {{1}} at the end of button "Pay": https://…/{{1}}).422 Every dynamic URL button needs a value — see buttons[] in the schema.
Campaign N is already "queued" and can only be sent while it is a draft.422 Already dispatched — don't retry the send; poll it instead.
N recipient number(s) are invalid. Fix or remove them on the campaign page…422 A dashboard draft still has invalid numbers. Fix them, or send with "skip_invalid_phones": true.
Not enough WhatsApp credits…402 Top up, or reduce the recipient list.

Per-recipient errors (after sending)

These appear in GET /campaigns/{id}/recipients as error, straight from Meta:

TextUsually means
Template is paused due to quality.Too many blocks/reports. Meta paused it — improve targeting and wait.
(#131047) Re-engagement message…The number never opted in, or the template category is wrong for this contact.
(#100) …image.link is not a valid URIThe media URL was unreachable when we fetched it.
Insufficient WhatsApp credits.The wallet emptied mid-campaign — top up and re-send the failed rows.
send_status_unknown: …The request may have reached Meta but no answer came back. Not resent (no duplicate risk), credits refunded. Check with the customer before sending again.
Could not reach WhatsApp after 3 attempt(s): …Meta could not be reached at all, three times. Nothing was sent; credits refunded.

Code examples

KEY="es_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
BASE="https://everysecond.ai/api/v1/whatsapp"

# 1) What can this project send?
curl -s -H "Authorization: Bearer $KEY" "$BASE/templates"

# 2) What does template 19 need?
curl -s -H "Authorization: Bearer $KEY" "$BASE/templates/19/schema"

# 3) Send it
curl -s -X POST "$BASE/send" \
  -H "Authorization: Bearer $KEY" \
  -H 'Content-Type: application/json' \
  -d '{
    "name": "Order #10293",
    "template_id": 19,
    "recipients": [
      { "phone": "01207256335",
        "variables": { "1": "Ahmed", "2": "RC-10293", "3": "2x oil filter", "4": "1450 EGP" } }
    ]
  }'

# 4) Per-recipient outcome
curl -s -H "Authorization: Bearer $KEY" "$BASE/campaigns/88/recipients"
// Laravel / Guzzle
use Illuminate\Support\Facades\Http;

$api = Http::withToken(config('services.everysecond.key'))
    ->baseUrl('https://everysecond.ai/api/v1/whatsapp')
    ->acceptJson();

$response = $api->post('/send', [
    'name'        => "Order #{$order->id}",
    'template_id' => 19,
    'recipients'  => [[
        'phone'     => $order->customer_phone,
        'name'      => $order->customer_name,
        'variables' => [
            '1' => $order->customer_name,
            '2' => (string) $order->id,
            '3' => $order->items_summary,
            '4' => number_format($order->total, 2) . ' EGP',
        ],
    ]],
]);

if ($response->status() === 422) {
    // Every fixable problem, one line each.
    logger()->warning('WhatsApp rejected', $response->json('details'));
} elseif ($response->failed()) {
    logger()->error('WhatsApp send failed', ['error' => $response->json('error')]);
} else {
    $order->update(['wa_campaign_id' => $response->json('data.id')]);
}
const BASE = 'https://everysecond.ai/api/v1/whatsapp';
const KEY  = process.env.EVERYSECOND_API_KEY;

async function sendOrderConfirmation(order) {
  const res = await fetch(`${BASE}/send`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      name: `Order #${order.id}`,
      template_id: 19,
      recipients: [{
        phone: order.phone,
        name: order.customerName,
        variables: {
          '1': order.customerName,
          '2': String(order.id),
          '3': order.itemsSummary,
          '4': `${order.total} EGP`,
        },
      }],
    }),
  });

  const body = await res.json();

  if (!res.ok) {
    // details[] lists exactly what to fix (422), or the shortfall (402).
    throw new Error(`${body.error} ${(body.details || []).join(' ')}`);
  }
  return body.data.id;           // campaign id — poll for delivery
}
import os, requests

BASE = "https://everysecond.ai/api/v1/whatsapp"
KEY  = os.environ["EVERYSECOND_API_KEY"]
H    = {"Authorization": f"Bearer {KEY}"}

def send_order_confirmation(order):
    r = requests.post(f"{BASE}/send", headers=H, json={
        "name": f"Order #{order['id']}",
        "template_id": 19,
        "recipients": [{
            "phone": order["phone"],
            "name": order["customer_name"],
            "variables": {
                "1": order["customer_name"],
                "2": str(order["id"]),
                "3": order["items_summary"],
                "4": f"{order['total']} EGP",
            },
        }],
    }, timeout=20)

    body = r.json()
    if r.status_code == 422:
        raise ValueError("; ".join(body["details"]))
    r.raise_for_status()
    return body["data"]["id"]

def delivery_report(campaign_id):
    r = requests.get(f"{BASE}/campaigns/{campaign_id}/recipients", headers=H, timeout=20)
    return [(x["phone"], x["status"], x["error"]) for x in r.json()["data"]]

Recipes

Transactional: one message per event

Call POST /send with a single recipient at the moment the event happens (order placed, shipment out). Name the campaign after the event ("Order #10293") so it is traceable in the dashboard, and store the returned campaign id on your record.

Bulk: one campaign for many contacts

Batch up to 5000 recipients into one call — not 5000 calls, which would hit the rate limit immediately. Then poll GET /campaigns/{id} until progress_percent reaches 100, and pull the failures once from /campaigns/{id}/recipients.

Review before sending

POST /campaigns → an operator checks it in the dashboard → POST /campaigns/{id}/send. Useful when marketing copy or the audience needs sign-off.

Handling a 422 cleanly

Because nothing is created on a 422, the safe pattern is: submit → on 422, fix the rows named in details → resubmit the whole payload. There is no partial state to reconcile and no risk of double-sending.

OTP delivery

Send an AUTHENTICATION template with no variables and let the platform generate the code — read it from data.otp_codes in the response — or pass your own in "1".

Go-live checklist

Before you point production traffic at this API:

  • Key stored in server-side config/secrets — never in client code.
  • You're using the key of the right project — confirm with the project object in GET /templates.
  • Template ids read from GET /templates at deploy time, not hardcoded from a colleague's screenshot.
  • Your code handles 422 (fix & resubmit), 402 (top up) and 429 (honour Retry-After) distinctly.
  • Phones stored in international format, or country_code set per recipient.
  • Campaign ids persisted so you can pull delivery reports later.
  • Wallet balance monitored via GET /credits.

Need something this page doesn't cover? Contact support from your dashboard — include the campaign id and the exact error text and it can be traced end to end.