Baatzo API v1 reference

Baatzo API v1

Send one approved Utility or Authentication WhatsApp template to one number, read how it went, and get a signed webhook each time its status changes. API messages appear in the contact's chat in Baatzo, marked API, and cost what any message costs: Meta's charge, which Meta bills you directly, plus Baatzo's fee from your message credit.

View as Markdown Open in ChatGPT Open in Claude

Base URL
https://api.baatzo.com
Plans
Starter, Growth and Pro; the sandbox on every plan
Format
JSON over HTTPS

Marketing templates cannot be sent through API v1. Campaign endpoints, event webhooks beyond message status and marketing sends come later. Contacts can be read and added through the MCP server.

Keys and scopes

An Owner or Admin with two-step verification on makes keys in the Baatzo web app, under Settings, Developers. A key is shown once: keep it on your server, never in an app or a web page. Baatzo stores only a hash of it, so a lost key is revoked and replaced. A revoked key stops working on the next request. To replace a key without downtime, press Roll beside it: you get a new key with the same name, scopes and countries, and the old one keeps working for 24 hours. A key can be rolled once.

Send it in the Authorization header:

Authorization: Bearer bz_live_K7Q2M9XA_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
ScopeAllows
messages:sendPOST /v1/messages
messages:readGET /v1/messages/{id}; on the MCP server, the templates and the credit balance
contacts:readGET /v1/contacts/{id}/consent-certificate; on the MCP server, listing contacts
contacts:writeOn the MCP server, adding and updating contacts
data:exportPOST /v1/exports, GET /v1/exports and the download

A new key sends only to Indian numbers. The workspace Owner can add countries to a key in Settings, Developers. This stops bots that request codes to numbers abroad from running up your Meta bill.

Sandbox keys start bz_test_ and work everywhere, on every plan (see Sandbox).

Limits and retries

Sandbox

Build and test before your WhatsApp number is connected or Meta has approved anything. In Settings, Developers, create a sandbox key: it is free on every plan, up to 5 per workspace, and starts bz_test_. It holds messages:send and messages:read only; contacts, consent certificates and exports need a live key.

Authorization: Bearer bz_test_K7Q2M9XA_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Send toWhat happens
+919000000001message.failed after about 2 seconds with Meta's error 131026 (message undeliverable) and its plain explanation.
+919000000002Sent and delivered, never read.
Any other numberSent, delivered and read.

Import into Postman

The whole of API v1 is one OpenAPI 3.1 document. In Postman, click Use resources or import in the sidebar, then the Import tab, and enter this address:

https://api.baatzo.com/docs/openapi.json

Set the collection's bearer token to a sandbox key and give each send a new Idempotency-Key.

Send a message

POST/v1/messages

Sends one approved template to one number. Needs messages:send.

FieldTypeNotes
tostringRequired. The number in E.164, such as +919829012345.
template.namestringRequired. An approved Utility or Authentication template of your workspace.
template.languagestringRequired. The template's language code exactly as in Baatzo, such as en or en_IN.
fromstringMeta's phone number ID of the sending number. Needed only when the workspace has more than one number for the template.
variables.bodyobjectEach variable by name (or number, for a numbered template). For Authentication: { "code": "482913" }, 1 to 15 letters and digits. Up to 1,024 characters each, with no line breaks or tabs.
variables.header.documentobject{ "link", "filename" } for a template with a document header, such as a PDF report. The link must be https, at most 2,048 characters, with no user name or password. WhatsApp fetches the file; Baatzo does not.
variables.buttonsarray{ "index", "url" } for a URL button with a variable, { "index", "copy_code" } for a copy-code button. Without index, the position in the array.
referencestringYour own id, up to 64 characters, returned in reads and webhooks.

A login code

curl https://api.baatzo.com/v1/messages \
  -H "Authorization: Bearer $BAATZO_KEY" \
  -H "Idempotency-Key: login-88213-1" \
  -H "Content-Type: application/json" \
  -d '{ "to": "+919829012345",
        "template": { "name": "login_code", "language": "en" },
        "variables": { "body": { "code": "482913" } },
        "reference": "login-88213" }'
// Node.js 18 or later: fetch is built in.
const res = await fetch('https://api.baatzo.com/v1/messages', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.BAATZO_KEY}`,
    'Idempotency-Key': 'login-88213-1',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    to: '+919829012345',
    template: { name: 'login_code', language: 'en' },
    variables: { body: { code: '482913' } },
    reference: 'login-88213',
  }),
});
const answer = await res.json();
if (!res.ok) throw new Error(`${answer.code}: ${answer.message}`);
# Python 3.9 or later, with: pip install requests
import os
import requests

res = requests.post(
    "https://api.baatzo.com/v1/messages",
    headers={
        "Authorization": f"Bearer {os.environ['BAATZO_KEY']}",
        "Idempotency-Key": "login-88213-1",
    },
    json={
        "to": "+919829012345",
        "template": {"name": "login_code", "language": "en"},
        "variables": {"body": {"code": "482913"}},
        "reference": "login-88213",
    },
    timeout=30,
)
answer = res.json()
if not res.ok:
    raise RuntimeError(f"{answer['code']}: {answer['message']}")
<?php
// PHP 8.0 or later, with the curl extension.
$ch = curl_init('https://api.baatzo.com/v1/messages');
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . getenv('BAATZO_KEY'),
        'Idempotency-Key: login-88213-1',
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS => json_encode([
        'to' => '+919829012345',
        'template' => ['name' => 'login_code', 'language' => 'en'],
        'variables' => ['body' => ['code' => '482913']],
        'reference' => 'login-88213',
    ]),
]);
$raw = curl_exec($ch);
if ($raw === false) {
    throw new RuntimeException(curl_error($ch));
}
$answer = json_decode($raw, true);
if (curl_getinfo($ch, CURLINFO_RESPONSE_CODE) >= 400) {
    throw new RuntimeException("{$answer['code']}: {$answer['message']}");
}

A report with a PDF

// Node.js 18 or later: fetch is built in.
const res = await fetch('https://api.baatzo.com/v1/messages', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.BAATZO_KEY}`,
    'Idempotency-Key': `report-${report.id}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    to: '+919829012345',
    template: { name: 'mock_test_report', language: 'en' },
    variables: {
      body: { parent_name: 'Asha', student: 'Ravi' },
      header: { document: { link: report.pdfUrl, filename: 'Mock test 4.pdf' } },
    },
    reference: `report-${report.id}`,
  }),
});
const answer = await res.json();
if (res.status === 429 || res.status === 503) {
  // Wait Retry-After seconds. For a 503 on a code, send a new code.
}
# Python 3.9 or later, with: pip install requests
res = requests.post(
    "https://api.baatzo.com/v1/messages",
    headers={
        "Authorization": f"Bearer {os.environ['BAATZO_KEY']}",
        "Idempotency-Key": f"report-{report.id}",
    },
    json={
        "to": "+919829012345",
        "template": {"name": "mock_test_report", "language": "en"},
        "variables": {
            "body": {"parent_name": "Asha", "student": "Ravi"},
            "header": {"document": {"link": report.pdf_url, "filename": "Mock test 4.pdf"}},
        },
        "reference": f"report-{report.id}",
    },
    timeout=30,
)
answer = res.json()
if res.status_code in (429, 503):
    ...  # Wait Retry-After seconds. For a 503 on a code, send a new code.
// The same curl call as the login code, with this body.
$body = json_encode([
    'to' => '+919829012345',
    'template' => ['name' => 'mock_test_report', 'language' => 'en'],
    'variables' => [
        'body' => ['parent_name' => 'Asha', 'student' => 'Ravi'],
        'header' => ['document' => ['link' => $report->pdfUrl, 'filename' => 'Mock test 4.pdf']],
    ],
    'reference' => "report-{$report->id}",
]);
// On 429 or 503, wait Retry-After seconds. For a 503 on a code, send a new code.

Answers

201 Created
{ "id": "0193f6c2-7a1e-7c55-9d1b-4f2b6c1d9a10", "status": "accepted", "reference": "login-88213" }
HTTPstatusMeans
201acceptedWhatsApp took the message. Webhooks follow as it is sent, delivered and read.
201failed, withheldWhatsApp refused it for good. error carries WhatsApp's code and a plain explanation in English and Hindi. No Baatzo fee.
202queuedA Utility send WhatsApp asked to wait. Baatzo retries it; the webhook tells you how it ends.
202unknownWhatsApp did not answer in time. It may still deliver; the webhook settles it. Do not send again with a new Idempotency-Key.

Read a message

GET/v1/messages/{id}

Any message sent through the API in your workspace. Needs messages:read.

curl https://api.baatzo.com/v1/messages/0193f6c2-7a1e-7c55-9d1b-4f2b6c1d9a10 \
  -H "Authorization: Bearer $BAATZO_KEY"

{ "id": "0193f6c2-7a1e-7c55-9d1b-4f2b6c1d9a10",
  "status": "delivered", "status_rank": 5, "reference": "login-88213",
  "template": { "name": "login_code", "language": "en", "category": "authentication" },
  "created_at": "2027-01-28T09:15:00.120Z",
  "times": { "accepted_at": "…", "sent_at": "…", "delivered_at": "…", "read_at": null, "failed_at": null },
  "charge": { "category": "authentication", "baatzo_fee_paise": 2, "state": "chargeable",
              "meta_charge_estimate": { "amount_micro_rupees": "115000", "is_estimate": true } },
  "error": null }

Meta bills its own charge to your WhatsApp Business account; meta_charge_estimate is an estimate from Meta's published rate. baatzo_fee_paise is Baatzo's fee, taken from your message credit only when Meta charges for the message.

Export everything

POST/v1/exports
GET/v1/exports
GET/v1/exports/{id}/download

Your whole workspace in one zip: contacts, their consent history and the whole consent ledger, messages, templates (JSON), every invoice and credit note (PDF), a campaigns summary and the automations (JSON). It is the same export as Settings, Export everything. Needs data:export. The POST needs an Idempotency-Key of 8 to 100 letters, digits, - or _; it answers 202 with the export queued, and the key's creator gets an email when it is ready. A ready export can be downloaded for 7 days, then it is deleted. One export of everything is built at a time (409 export_in_progress).

curl -X POST https://api.baatzo.com/v1/exports \
  -H "Authorization: Bearer $BAATZO_KEY" -H "Idempotency-Key: export-2027-02-01"

202 Accepted
{ "export": { "id": "0193f6d1-…", "status": "queued", "everything": true, "contacts": null,
              "created_at": "…", "completed_at": null, "expires_at": null, "download_url": null } }

curl https://api.baatzo.com/v1/exports -H "Authorization: Bearer $BAATZO_KEY"
{ "exports": [ { "id": "0193f6d1-…", "status": "ready", "download_url": "/v1/exports/0193f6d1-…/download", … } ],
  "next_cursor": null }
GET/v1/contacts/{id}/consent-certificate

A PDF of one contact's consent ledger: who they are, their consent now, and every opt-in and opt-out with its date, source, the statement shown, the IP address and the person or key that recorded it where Baatzo has them, each with its record id. Needs contacts:read. It is for your records, not legal advice. The workspace's whole ledger is a CSV in the web app (Settings, Business, Your data).

Status events

Set one HTTPS URL for your workspace in Settings, Developers. Baatzo posts an event each time a message sent through the API is sent, delivered, read or fails. The page shows the signing secret once (it starts whsec_), sends a test event, and lists 30 days of deliveries.

POST https://your-server.example/baatzo-webhook
Baatzo-Signature: t=1801123456,v1=5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bd
Content-Type: application/json

{ "id": "evt_0193f6c4-…", "type": "message.delivered",
  "created_at": "2027-01-28T09:15:02Z",
  "data": { "message_id": "0193f6c2-…", "reference": "login-88213",
            "wamid": "wamid.HBgMOTE5ODI5MDEyMzQ1FQIAERgS…",
            "status": "delivered", "status_rank": 5,
            "charge": { "category": "authentication", "baatzo_fee_paise": 2, "state": "chargeable" },
            "error": null } }

Verify the signature

v1 is the HMAC-SHA256 of the timestamp, a full stop and the raw body, keyed with your secret, in hex. Check it on the raw bytes before parsing the JSON, compare in constant time, and refuse a timestamp more than 5 minutes off. After you rotate the secret, both the old and the new one sign for 24 hours, so the header carries two v1 values: accept the event if either matches.

// Verifying a Baatzo status webhook (API v1). Node.js 18 or later, no packages.
//
// Baatzo sends   Baatzo-Signature: t=1801123456,v1=<hex>[,v1=<hex>]
// where each v1 is the HMAC-SHA256 of "<t>.<raw body>" keyed with your signing secret (whsec_...).
// During a secret rotation the header carries two v1 values for 24 hours; accept the request if any matches.
// Check the RAW body, byte for byte, before parsing it as JSON.

const { createHmac, timingSafeEqual } = require('crypto');

const TOLERANCE_SECONDS = 5 * 60;

/**
 * True when the header is a valid Baatzo signature of rawBody under secret, made at most 5 minutes
 * from now. rawBody is a Buffer or string, exactly as received.
 */
function verifyBaatzoSignature(rawBody, header, secret, now = Date.now()) {
  if (typeof header !== 'string' || typeof secret !== 'string') return false;
  let t = null;
  const signatures = [];
  for (const part of header.split(',')) {
    const i = part.indexOf('=');
    const k = part.slice(0, i).trim();
    const v = part.slice(i + 1).trim();
    if (k === 't' && /^\d{1,12}$/.test(v)) t = Number(v);
    if (k === 'v1' && /^[0-9a-f]{64}$/.test(v)) signatures.push(Buffer.from(v, 'hex'));
  }
  if (t === null || !signatures.length) return false;
  if (Math.abs(Math.floor(now / 1000) - t) > TOLERANCE_SECONDS) return false;
  const body = Buffer.isBuffer(rawBody) ? rawBody : Buffer.from(String(rawBody), 'utf8');
  const expected = createHmac('sha256', secret).update(`${t}.`).update(body).digest();
  return signatures.some((s) => s.length === expected.length && timingSafeEqual(s, expected));
}

module.exports = { verifyBaatzoSignature };

// Express example: keep the raw body for the check.
//
//   app.post('/baatzo-webhook', express.raw({ type: 'application/json' }), (req, res) => {
//     if (!verifyBaatzoSignature(req.body, req.get('Baatzo-Signature'), process.env.BAATZO_WEBHOOK_SECRET)) {
//       return res.status(400).end();
//     }
//     const event = JSON.parse(req.body.toString('utf8'));
//     // Drop a repeat by event.id; ignore a status older than one you already have (event.data.status_rank).
//     res.status(200).end(); // answer within 5 seconds, then do the work
//   });
# Verifying a Baatzo status webhook (API v1). Python 3.9 or later, no packages.
#
# Baatzo sends   Baatzo-Signature: t=1801123456,v1=<hex>[,v1=<hex>]
# where each v1 is the HMAC-SHA256 of "<t>.<raw body>" keyed with your signing secret (whsec_...).
# During a secret rotation the header carries two v1 values for 24 hours; accept the request if any matches.
# Check the RAW body, byte for byte, before parsing it as JSON.

import hashlib
import hmac
import re
import time

TOLERANCE_SECONDS = 5 * 60


def verify_baatzo_signature(raw_body, header, secret, now=None):
    """True when header is a valid signature of raw_body (bytes), made at most 5 minutes from now."""
    if not isinstance(header, str) or not secret:
        return False
    t, signatures = None, []
    for part in header.split(","):
        k, _, v = (x.strip() for x in part.partition("="))
        if k == "t" and re.fullmatch(r"[0-9]{1,12}", v):
            t = int(v)
        if k == "v1" and re.fullmatch(r"[0-9a-f]{64}", v):
            signatures.append(v)
    if t is None or not signatures:
        return False
    if abs(int(time.time() if now is None else now) - t) > TOLERANCE_SECONDS:
        return False
    expected = hmac.new(secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256).hexdigest()
    return any(hmac.compare_digest(s, expected) for s in signatures)


# Flask example: request.get_data() is the raw body.
#
#   @app.post("/baatzo-webhook")
#   def baatzo_webhook():
#       raw = request.get_data()
#       if not verify_baatzo_signature(raw, request.headers.get("Baatzo-Signature"), os.environ["BAATZO_WEBHOOK_SECRET"]):
#           return "", 400
#       event = json.loads(raw)
#       # Drop a repeat by event["id"]; ignore a status older than one you already have (status_rank).
#       return "", 200  # answer within 5 seconds, then do the work
<?php
// Verifying a Baatzo status webhook (API v1). PHP 8.0 or later, no packages.
//
// Baatzo sends   Baatzo-Signature: t=1801123456,v1=<hex>[,v1=<hex>]
// where each v1 is the HMAC-SHA256 of "<t>.<raw body>" keyed with your signing secret (whsec_...).
// During a secret rotation the header carries two v1 values for 24 hours; accept the request if any matches.
// Check the RAW body, byte for byte, before parsing it as JSON.

const BAATZO_TOLERANCE_SECONDS = 300;

/** True when $header is a valid Baatzo signature of $rawBody, made at most 5 minutes from now. */
function verify_baatzo_signature(string $rawBody, ?string $header, string $secret, ?int $now = null): bool
{
    if ($header === null || $secret === '') {
        return false;
    }
    $t = null;
    $signatures = [];
    foreach (explode(',', $header) as $part) {
        [$k, $v] = array_map('trim', array_pad(explode('=', $part, 2), 2, ''));
        if ($k === 't' && preg_match('/^[0-9]{1,12}$/D', $v)) {
            $t = (int) $v;
        }
        if ($k === 'v1' && preg_match('/^[0-9a-f]{64}$/D', $v)) {
            $signatures[] = $v;
        }
    }
    if ($t === null || $signatures === []) {
        return false;
    }
    if (abs(($now ?? time()) - $t) > BAATZO_TOLERANCE_SECONDS) {
        return false;
    }
    $expected = hash_hmac('sha256', $t . '.' . $rawBody, $secret);
    foreach ($signatures as $signature) {
        if (hash_equals($expected, $signature)) {
            return true;
        }
    }
    return false;
}

// A webhook script: php://input is the raw body.
//
//   $raw = file_get_contents('php://input');
//   if (!verify_baatzo_signature($raw, $_SERVER['HTTP_BAATZO_SIGNATURE'] ?? null, getenv('BAATZO_WEBHOOK_SECRET'))) {
//       http_response_code(400);
//       exit;
//   }
//   $event = json_decode($raw, true);
//   // Drop a repeat by $event['id']; ignore a status older than one you already have (status_rank).
//   http_response_code(200); // answer within 5 seconds, then do the work

The same files: verify-signature.js, verify-signature.py and verify-signature.php.

Delivery log and replay

Settings, Developers lists the last 30 days of deliveries: the time, the event, the wamid, your server's HTTP status, how long it took and the attempts. Each one opens to show the payload, the status code and the first 2 KB of your server's answer.

Error codes

Every error is { "code", "message", "details" }. Act on code; message is for people and may change.

CodeHTTPWhen
unauthenticated401The key is missing, malformed, unknown or revoked.
forbidden403The key lacks the scope (details.reason is missing_scope), or the workspace is suspended or closing.
plan_required403The workspace is on Template Studio. Keys stay after a downgrade, but requests fail until a paid plan returns.
idempotency_key_required400A send has no Idempotency-Key.
invalid_request422A field fails validation. details lists each { field, message }.
template_not_found404No template with that name and language.
template_not_approved422The template is not approved now (details.status says what it is).
category_not_allowed422The template is Marketing, including one Meta has moved to Marketing.
recipient_not_allowed422The number's country is not allowed for this key (details.country).
recipient_opted_out422The person withdrew consent for messages like this.
insufficient_credit402Your message credit cannot cover Baatzo's fee. Nothing was sent. Top up in Billing.
sending_paused409The number cannot send now; details.reason says why (for example reconnect_needed or meta_payment).
idempotency_key_reused422The same Idempotency-Key with a different body.
request_in_progress409The first request with this Idempotency-Key is still running. Try again in a moment.
rate_limited429Over the key's limit, or too many wrong keys from your address. See Retry-After.
retry_later503An Authentication send hit a temporary WhatsApp error. Send a new code.
not_found404No such message (or contact, or export) in this workspace.
idempotency_key_invalid400POST /v1/exports: the Idempotency-Key is not 8 to 100 letters, digits, - or _.
idempotency_in_progress409POST /v1/exports: the first request with this key is still running.
export_in_progress409An export of everything is being built already.
export_expired410The export is not ready yet, or its 7 days are over.

Statuses

statusstatus_rankMeans
queued0 to 1Not with WhatsApp yet.
unknown1WhatsApp did not answer in time; a webhook settles it.
accepted2WhatsApp took it.
held3WhatsApp is checking it before delivery.
sent4Sent to the person's phone.
delivered5On the person's phone.
read6Opened.
failed, withheld7Not delivered. Withheld messages are held back by Meta and not charged.