Documentation

Partner API

For software platforms that run WhatsApp for many shops: shops, embedded QR, sending, usage records, one signed webhook, reconciliation. Laravel / PHP examples.

For software platforms that run WhatsApp for many shops of their own. Your shops never see this service, never sign up here and never see our name: you call this API from your server, and everything the shop sees is yours.

Machine-readable spec: Download openapi.json (OpenAPI 3.1, also served live at GET /partner/v1/openapi.json). Every route on this page is in the spec.

ConceptsBeta

WordMeaning
PartnerYou. One account, one or more partner keys, one webhook, one safety policy.
ShopOne of your customers. You create it with your own externalId; it gets its own WhatsApp number slot. Shops have no logins here.
NumberThe WhatsApp number a shop links (by QR or pairing code). Each number has its own caps, warm-up and state.
MessageText or a document sent from a shop's number. Returns immediately as queued.
Usage recordOne per message. Says whether the message is billable yet. This is your charging signal.
ReferenceYour own structured tag on a message (sale id, event type, shop id). Returned unchanged everywhere.

You bill your shops in your own currency. Sendjade does not debit any wallet per message for a partner. Sendjade bills you monthly, in USD, per connected number (see "What Sendjade bills you" below).

Get startedBeta

  • Sendjade support creates your partner account and gives you a partner key: sjp_xxxxxxxx_.... It is shown once; only a hash is stored. Ask for separate keys per environment and per service; each key can be limited to certain scopes and to your server IP addresses.
  • Keep the key on your server only (an environment variable). Never put it in a browser or a mobile app.
  • Set your webhook URL (see The webhook) and store the secret it returns.
  • Create a shop, show the QR, send a test message.
Check your key
export SJ=https://api.sendjade.com/partner/v1                       # your base URL
export KEY=sjp_xxxxxxxx_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx   # example only: use your own key

curl -s $SJ/account -H "Authorization: Bearer $KEY"

Key rotation: ask support to rotate. The new key is shown once and the old one keeps working for an overlap you choose (default 60 minutes), so you can deploy without downtime. Revoked and expired keys stop working immediately.

ConventionsBeta

  • Auth: Authorization: Bearer sjp_.... A partner key only works under /partner/v1, and only sees your own shops and messages.
  • JSON everywhere. Success: { "data": ... }. Error: { "error": { "code": "not_on_whatsapp", "message": "...", ...extra } }. Branch on code, never on message.
  • Shop ids: you use your own externalId (letters, digits, _ . : -, up to 100 characters) in every URL. It is unique per partner.
  • Times are ISO 8601 in UTC.
  • Rate limits are per key (per minute), shown as x-ratelimit-* headers. Over the limit: 429 rate_limited. Repeated wrong keys from one IP are throttled.
  • Pagination: list endpoints return nextCursor; pass it as cursor until it is null.

Scopes

ScopeAllows
shops:readRead shops and their connection state
shops:writeCreate, suspend, resume and delete shops; rotate tokens; change limits
connectShow the QR code or pairing code and connect or unlink a shop number
messages:sendSend text messages and documents
messages:readList and read messages (reconciliation)
usage:readRead usage summary and the monthly statement
webhook:manageConfigure and test the webhook, read and redeliver deliveries
sending:controlSuspend or resume sending for the whole partner

A key without the scope gets 403 missing_scope.

IdempotencyBeta

Every send needs an Idempotency-Key header (any unique string up to 128 characters, for example sale-8841-receipt). Retrying with the same key never sends twice: you get the original message back with 200 and Idempotent-Replayed: true. Reusing a key for a different message returns 409 idempotency_key_reused.

ShopsBeta

Create (idempotent). Call it every time you onboard or re-sync a shop: the same externalId always returns the same shop. 201 = created now, 200 = already existed. Parallel identical calls create exactly one shop. A deleted shop's externalId cannot be reused (409 external_id_deleted).

POST /partner/v1/shops
curl -s -X POST $SJ/shops -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' \
  -d '{"externalId":"shop_1042","name":"Mama Chidi Store"}'
Response
{ "data": {
  "externalId": "shop_1042", "name": "Mama Chidi Store", "status": "active", "statusReason": null,
  "created": true,
  "instanceToken": "sj_...",            // only when created (201). Store it; or rotate later.
  "instance": {
    "id": "6c1f...", "state": "created", "phoneNumber": null,
    "warmup": { "active": true, "endsAt": null, "dailyCap": 30, "hourlyCap": 10 },
    "limits": { "dailyCap": 30, "hourlyCap": 10, "perRecipientHourly": 3, "perRecipientDaily": 8, "gapMs": 3000, "gapJitterMs": 4000 },
    "sent24h": 0 } } }
ActionCallWhat happens
ReadGET /shops/{externalId}Status, number state, warm-up, effective limits, messages in the last 24h
State onlyGET /shops/{externalId}/stateCheap to poll: state, phoneNumber, last disconnect
ListGET /shops?status=&limit=&cursor=
SuspendPOST /shops/{externalId}/suspend {"reason":"no credit"}Session stopped. Every send returns 403 shop_suspended. Use this when a shop has no credit.
ResumePOST /shops/{externalId}/resumeAllows sending again and reconnects the saved session. Also lifts an automatic pause.
DeleteDELETE /shops/{externalId}Soft delete: queued messages cancelled, number unlinked, credentials wiped. Message and usage history is kept for reconciliation.
Rotate tokenPOST /shops/{externalId}/token/rotateNew instance token (shown once); the old one stops working.
LimitsPATCH /shops/{externalId}/limitsdailyCap, hourlyCap, perRecipientHourly, perRecipientDaily. Never above your account policy.
Opt-outsGET /shops/{externalId}/opt-outsPeople who replied STOP

Shop `state`: created, qr_pending, connecting, connected, disconnected, logged_out, failed, and suspected_ban (the shop was auto-paused). Shop `status`: active, suspended, paused_suspected_ban, deleted.

Partner-wide switch. POST /sending/suspend {"reason":"incident"} stops sending for all your shops (403 sending_suspended, queued messages are cancelled, connections stay up). POST /sending/resume turns it back on.

Linking a number: embedded QR and pairing codeLive, phone check

Show the QR inside your own screen. Your server calls Sendjade; the browser only receives the image.

GET /partner/v1/shops/{externalId}/qr
curl -s $SJ/shops/shop_1042/qr -H "Authorization: Bearer $KEY"

# { "data": { "state": "qr_pending", "qr": "data:image/png;base64,iVBOR...", "expiresInSeconds": 18, "refreshAfterSeconds": 3, "phoneNumber": null } }
  • Call GET /shops/{externalId}/qr. It starts the session if needed. If qr is null and state is connecting, call again in a second.
  • Render qr in an <img src="...">. The code changes about every 20 seconds: poll every 3 seconds while the shop owner is on the screen.
  • The owner opens WhatsApp, Linked devices, Link a device and scans it. The device appears as your configured name, never ours.
  • Stop when state is connected (you also get an instance.state webhook).

Pairing code (the owner types a code instead of scanning; useful on mobile): POST /shops/{externalId}/pairing-code {"phoneNumber":"2348140001234"} returns { "code": "ABCD-EFGH", "expiresInSeconds": 60 }. The owner opens WhatsApp, Linked devices, Link with phone number instead.

Unlink / change number: POST /shops/{externalId}/logout. The warm-up restarts with the next number. If the owner removes the linked device on their phone, you receive instance.state with state: "logged_out": show the QR again.

SendingLive, phone check

POST /partner/v1/shops/{externalId}/messages/text
curl -s -X POST $SJ/shops/shop_1042/messages/text -H "Authorization: Bearer $KEY" \
  -H 'Content-Type: application/json' -H 'Idempotency-Key: sale-8841-receipt' \
  -d '{"to":"2348031234567","text":"Thanks for shopping at Mama Chidi Store! Total: N4,500",
       "reference":{"saleId":"8841","eventType":"receipt","shopId":"shop_1042"}}'
Response (202)
{ "data": { "duplicate": false, "message": {
  "messageId": "0b8d...", "shop": { "externalId": "shop_1042" }, "to": "2348031234567", "type": "text",
  "status": "queued", "errorCode": null, "reference": { "saleId": "8841", "eventType": "receipt", "shopId": "shop_1042" },
  "idempotencyKey": "sale-8841-receipt",
  "usage": { "usageId": "0b8d...", "billable": false, "reason": "queued", "billableAt": null, "deliveryUnconfirmed": false },
  "createdAt": "2026-11-19T10:00:00.000Z", "sentAt": null, "deliveredAt": null, "readAt": null, "updatedAt": "2026-11-19T10:00:00.000Z" } } }

202 means accepted for sending, not delivered. Follow the status by webhook.

  • `reference`: 1 to 10 keys, values are strings (200 chars), numbers or booleans. Stored with the message and echoed in every webhook, usage record and list.
  • Number check. Before anything is queued, the number is checked against WhatsApp. Not on WhatsApp: 422 not_on_whatsapp, nothing is queued and nothing can be billed. Only direct messages to a phone number are allowed (no groups).
  • STOP. If the customer replies STOP, they are opted out for that shop and later sends return 422 recipient_opted_out.

Documents (PDF, images)

By URL
curl -s -X POST $SJ/shops/shop_1042/messages/document -H "Authorization: Bearer $KEY" \
  -H 'Content-Type: application/json' -H 'Idempotency-Key: sale-8841-pdf' \
  -d '{"to":"2348031234567","url":"https://files.example-partner.com/receipts/8841.pdf","fileName":"Receipt-8841.pdf","caption":"Your receipt",
       "reference":{"saleId":"8841","eventType":"receipt_pdf","shopId":"shop_1042"}}'
By upload (multipart)
curl -s -X POST $SJ/shops/shop_1042/messages/document -H "Authorization: Bearer $KEY" -H 'Idempotency-Key: sale-8841-pdf' \
  -F to=2348031234567 -F caption='Your receipt' -F 'reference={"saleId":"8841","eventType":"receipt_pdf"}' -F file=@Receipt-8841.pdf

URL rules: https only, and the host must be in your allow-list (set by Sendjade support: exact hosts like files.example-partner.com or wildcards like *.cdn.example-partner.com). Redirects are followed only to allowed hosts. Private and internal addresses are always refused. Otherwise: 422 file_host_not_allowed / url_blocked. Maximum size 25 MB; executables are rejected. With an empty allow-list, use uploads.

Billing: usage recordsBeta

Every message response and every webhook carries a usage record:

usage
"usage": { "usageId": "0b8d...", "billable": false, "reason": "awaiting_delivery", "billableAt": null, "deliveryUnconfirmed": false }
  • `usageId` is stable and unique per message. Charge your shop at most once per `usageId`: use it as the idempotency key of your own charge.
  • `billable` only ever goes false to true, never back. With billableOn: DELIVERED (the default) it becomes true when WhatsApp reports the message delivered (or read). With billableOn: ACCEPTED it becomes true when WhatsApp accepts it.
  • reason: queued, awaiting_delivery, accepted, delivered, failed, cancelled, delivery_unconfirmed.
  • A message that fails, is cancelled, or goes to a number not on WhatsApp is never billable.
  • `delivery_unconfirmed`: accepted by WhatsApp but no delivery receipt after 24 hours (phone off for a long time). Reported as billable: false and flagged. If the receipt arrives later, it becomes billable then (and shows in updatedSince lists).

No wallet debit. Nothing is taken from any wallet when a message is sent. You decide what to charge your shops. A shop has no credit: POST /shops/{externalId}/suspend. Everything must stop: POST /sending/suspend.

What Sendjade bills you

Monthly, in USD, per connected number: the Partner plan price per number with a minimum number of numbers billed (see GET /statement, sendjadeFee). Messages are included. A Super Admin charges the wallet of your billing workspace once per closed month (the charge is idempotent: repeating it changes nothing); top the wallet up like any Sendjade workspace.

GET /statement?month=2026-11 returns the month's billable messages by shop and type, plus the fee. A message counts in the month it became billable (UTC), so it is in exactly one statement and a closed month never changes.

The webhookBeta

One URL for all your shops. events can filter (default all). POST /webhook/test sends a signed webhook.test. POST /webhook/rotate-secret issues a new secret (shown once). GET /webhook shows health; GET /webhook/deliveries lists attempts; POST /webhook/deliveries/{id}/redeliver sends one again with the same event id. Production URLs must be https.

PUT /partner/v1/webhook
curl -s -X PUT $SJ/webhook -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' \
  -d '{"url":"https://api.example-partner.com/hooks/whatsapp"}'
# -> { "data": { "webhook": {...}, "secret": "whsec_..." } }   the secret is shown ONCE

Envelope

Example event body
{
  "id": "evt_9f3a1c0d2b7e4a6f81c2d3e4",
  "type": "message.delivered",
  "sequence": 10452,
  "createdAt": "2026-11-19T10:00:07.120Z",
  "externalId": "shop_1042",
  "messageId": "0b8d...",
  "reference": { "saleId": "8841", "eventType": "receipt", "shopId": "shop_1042" },
  "data": {
    "status": "delivered", "to": "2348031234567", "type": "text", "errorCode": null, "errorMessage": null,
    "usage": { "usageId": "0b8d...", "billable": true, "reason": "delivered", "billableAt": "2026-11-19T10:00:07.100Z", "deliveryUnconfirmed": false },
    "idempotencyKey": "sale-8841-receipt", "sentAt": "...", "deliveredAt": "...", "readAt": null, "occurredAt": "..."
  }
}
`type`When`data`
message.queuedMessage accepted by the APIstatus, usage, ...
message.sentWhatsApp accepted it
message.deliveredDelivered to the phoneusage.billable is now true (default mode)
message.readRead
message.failedFailed or cancellederrorCode: send_failed, shop_suspended, shop_deleted, sending_suspended, ...
instance.stateThe number's connection changedstate: connected, disconnected, logged_out, qr_pending, connecting, failed, suspected_ban; plus status, reason, shopStatus, phoneNumber
shop.statusSuspend, resume, delete, auto-pausestatus, reason
webhook.testYou asked for a test

Verify the signature

Do this before trusting anything. Header: X-Sendjade-Signature: t=<unix seconds>,v1=<hex> where v1 = HMAC-SHA256(secret, "<t>.<raw request body>"). Use the raw body bytes, not re-encoded JSON. Reject if t is more than 5 minutes old (replay protection). Other headers: X-Sendjade-Event and X-Sendjade-Delivery (the event id).

PHP / Laravel
public function handle(Request $request)
{
    $raw = $request->getContent();
    $header = (string) $request->header('X-Sendjade-Signature');
    parse_str(str_replace(',', '&', $header), $p);              // t=..., v1=...
    $expected = hash_hmac('sha256', ($p['t'] ?? '') . '.' . $raw, config('services.whatsapp.webhook_secret'));
    abort_unless(isset($p['t'], $p['v1']) && hash_equals($expected, $p['v1']) && abs(time() - (int) $p['t']) <= 300, 401);

    $event = json_decode($raw, true);
    // process idempotently on $event['id'] ... then answer fast:
    return response()->json(['ok' => true]);
}
Node
const crypto = require('crypto');
function verify(secret, header, raw) {
  const p = Object.fromEntries(header.split(',').map((x) => x.split('=')));
  const v1 = crypto.createHmac('sha256', secret).update(`${p.t}.${raw}`).digest('hex');
  return Math.abs(Date.now() / 1000 - Number(p.t)) <= 300 && crypto.timingSafeEqual(Buffer.from(v1), Buffer.from(p.v1));
}

Delivery guarantees

  • Answer any 2xx within 10 seconds. Anything else counts as a failure.
  • Failed deliveries are retried with exponential backoff (8 attempts, about an hour). After that the delivery shows failed and you can redeliver it or reconcile.
  • Delivery is at least once: de-duplicate on id. Retries and redeliveries keep the same id and body.
  • Events can arrive out of order. Use sequence (higher is newer) and never move a message status backwards (queued < sent < delivered < read; failed is final).
  • Webhooks are a convenience, not the source of truth. Reconcile from the API.

ReconciliationBeta

GET /messages lists your messages, oldest first, keyset-paginated (no row skipped or repeated while new messages arrive).

  • ?from=2026-11-01T00:00:00Z&to=2026-11-02T00:00:00Z enumerates everything created in a period.
  • ?updatedSince=<watermark> returns everything that changed since then: delivery receipts, billing flips. Use it to catch a missed webhook.
  • Filters: shop=<externalId>, status=, billable=true|false, referenceKey=saleId&referenceValue=8841.
  • Rows younger than 2 seconds are held back (settledUntil tells you the safe watermark), so a cursor never skips a late row.
Recommended job (every few minutes)
$since = Cache::get('wa:watermark', now()->subHour()->toIso8601String());
$cursor = null;
do {
    $r = Http::withToken(config('services.whatsapp.key'))->get("$base/messages", array_filter(['updatedSince' => $since, 'cursor' => $cursor, 'limit' => 200]))->json('data');
    foreach ($r['messages'] as $m) {
        // charge once per usageId: a unique index on usage_id makes this safe to repeat
        if ($m['usage']['billable']) { Charge::firstOrCreate(['usage_id' => $m['usage']['usageId']], [...]); }
        // update your message status from $m['status']
    }
    $cursor = $r['nextCursor'];
} while ($cursor);
Cache::put('wa:watermark', Carbon::parse($r['settledUntil'])->subSeconds(5)->toIso8601String());

GET /usage/summary?from=&to= gives counts by status and billing outcome for a period (max 93 days). GET /messages/{messageId} reads one message.

Warm-up and capsLive, phone check

WhatsApp restricts numbers that behave like bots. Every shop's number is held to these defaults (your account policy may be tuned by Sendjade support inside hard ceilings):

RuleDefaultHard ceiling
Daily cap (rolling 24h)3001000
Hourly cap (rolling hour)60200
Per recipient, per hour / per day3 / 85 / 20
Warm-up for a new number, first 7 days (never shorter)30 per day, 10 per hour100 / 30
Gap between two sends3 s + random 0 to 4 sgap at least 1.5 s
  • The warm-up clock starts at the first successful link. Linking a new number starts a new warm-up.
  • Over a limit: 429 with a specific code (warmup_limit_reached, daily_limit_reached, hourly_limit_reached, recipient_rate_limited) and retryAfterSeconds. Queue and retry on your side; do not retry immediately.
  • Messages leave a number one at a time with a small random gap, so a batch of due reminders drains smoothly instead of bursting.
  • STOP: a customer replying STOP is opted out.
  • Auto-pause on ban signals: the shop is paused (and its session stopped when that helps) if WhatsApp refuses the connection, the number drops repeatedly, most recent sends fail, or the number is logged out right after sending. You get instance.state with state: "suspected_ban" and shop.status paused_suspected_ban; sends return 403 shop_paused_suspected_ban and queued messages are cancelled. Check the phone, then POST /shops/{externalId}/resume.
  • Message hygiene still matters. Send messages the customer expects (receipts, order updates, reminders they asked for). No cold marketing.

Endpoint listBeta

MethodPathScopeSummary
GET/partner/v1/accountshops:readYour account: billing mode, safety policy, sending switch
POST/partner/v1/sending/suspendsending:controlStop ALL sending for every shop
POST/partner/v1/sending/resumesending:controlAllow sending again
POST/partner/v1/shopsshops:writeCreate a shop, idempotent on externalId
GET/partner/v1/shopsshops:readList your shops
GET/partner/v1/shops/{externalId}shops:readRead one shop, its state, warm-up and limits
GET/partner/v1/shops/{externalId}/stateshops:readConnection state only (cheap to poll)
POST/partner/v1/shops/{externalId}/suspendshops:writeSuspend a shop
POST/partner/v1/shops/{externalId}/resumeshops:writeResume a suspended or auto-paused shop
DELETE/partner/v1/shops/{externalId}shops:writeDelete a shop (soft)
POST/partner/v1/shops/{externalId}/token/rotateshops:writeRotate the shop's instance token
PATCH/partner/v1/shops/{externalId}/limitsshops:writeChange a shop's caps (never above your policy)
GET/partner/v1/shops/{externalId}/opt-outsshops:readPeople who replied STOP
POST/partner/v1/shops/{externalId}/connectconnectStart the shop's session
GET/partner/v1/shops/{externalId}/qrconnectShort-lived QR code to scan
POST/partner/v1/shops/{externalId}/pairing-codeconnectLink by typing a code on the phone
POST/partner/v1/shops/{externalId}/logoutconnectUnlink the number
POST/partner/v1/shops/{externalId}/messages/textmessages:sendSend a text message
POST/partner/v1/shops/{externalId}/messages/documentmessages:sendSend a PDF, document or image, by URL or upload
GET/partner/v1/messagesmessages:readList messages by date range (or by what changed)
GET/partner/v1/messages/{messageId}messages:readRead one message and its usage record
GET/partner/v1/usage/summaryusage:readCounts by status and billing outcome
GET/partner/v1/statementusage:readMonthly statement
GET/partner/v1/webhookwebhook:manageWebhook configuration and health
PUT/partner/v1/webhookwebhook:manageSet URL, event filter, enabled
POST/partner/v1/webhook/rotate-secretwebhook:manageNew signing secret (shown once)
POST/partner/v1/webhook/testwebhook:manageSend a signed webhook.test
GET/partner/v1/webhook/deliverieswebhook:manageRecent deliveries and outcome
POST/partner/v1/webhook/deliveries/{deliveryId}/redeliverwebhook:manageSend a delivery again
GET/partner/v1/openapi.jsonpublicOpenAPI 3.1 document

Error codesBeta

CodeHTTPMeaning
validation_error400The request body or query is invalid. details lists each problem.
idempotency_key_required400Sending needs an Idempotency-Key header (max 128 characters).
invalid_idempotency_key400The Idempotency-Key is too long.
invalid_chat_id400The recipient is not a valid phone number.
date_range_required400GET /messages needs from (or updatedSince).
invalid_phone400The phone number is not valid: use international format, digits only.
invalid_event400Unknown webhook event type in the filter.
range_too_large400Ask for at most 93 days of usage at a time.
invalid_cursor400The pagination cursor is not valid.
invalid_month400month must look like 2026-11.
https_required400The webhook URL must use https.
unauthorized401Missing, wrong, revoked or expired key.
missing_scope403The key does not carry the scope this endpoint needs.
ip_not_allowed403The key is restricted to other IP addresses.
partner_suspended403Your partner account is suspended.
sending_suspended403Sending is switched off for your whole account (see POST /sending/resume).
shop_suspended403This shop is suspended.
shop_paused_suspected_ban403The shop was paused automatically because WhatsApp may have restricted its number.
shop_not_found404No such shop for your account.
not_found404No such resource for your account.
external_id_deleted409A shop with this externalId was deleted. Use a new externalId.
instance_not_connected409The shop's number is not linked or not connected right now.
idempotency_key_reused409The Idempotency-Key was used before for a different message.
already_connected409The shop is already linked.
webhook_not_configured409Set the webhook URL first.
shop_deleted410The shop was deleted.
file_too_large413Files can be at most 25 MB.
unsupported_file_type415That file type cannot be sent.
no_file422Provide a url, or upload a file.
not_on_whatsapp422The recipient is not on WhatsApp. Nothing was queued or billed.
recipient_opted_out422The recipient replied STOP and must not be messaged.
recipient_not_allowed422Only direct messages to phone numbers are allowed (no groups).
file_host_not_allowed422The file URL is not https or its host is not in your allow-list. Upload the file instead.
url_blocked422The URL points at a private or internal address.
content_type_not_allowed422Only text and documents can be sent.
limit_above_policy422A shop limit cannot exceed your account policy.
warmup_limit_reached429A new number is limited during its first 7 days. Carries retryAfterSeconds.
daily_limit_reached429The number reached its 24-hour cap. Carries retryAfterSeconds.
hourly_limit_reached429The number reached its hourly cap. Carries retryAfterSeconds.
recipient_rate_limited429Too many messages to the same person. Carries retryAfterSeconds.
rate_limited429Too many API requests for this key.
number_check_failed503Could not check the number against WhatsApp. Retry; nothing was queued or billed.

Retry guidance: 5xx and 503 number_check_failed, retry with the same Idempotency-Key. 429, wait retryAfterSeconds. Any other 4xx: fix the request; do not retry unchanged.

Laravel / PHP clientBeta

app/Services/Whatsapp.php
<?php
// app/Services/Whatsapp.php
namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Http\Client\PendingRequest;

class Whatsapp
{
    private function http(): PendingRequest
    {
        return Http::withToken(config('services.whatsapp.key'))
            ->baseUrl(config('services.whatsapp.base'))      // https://api.sendjade.com/partner/v1
            ->acceptJson()->timeout(20)
            ->retry(3, 500, fn ($e) => $e instanceof \Illuminate\Http\Client\ConnectionException, throw: false);
    }

    /** Idempotent: safe to call on every shop save. Returns ['shop' => ..., 'token' => ?string]. */
    public function ensureShop(string $externalId, string $name): array
    {
        $r = $this->http()->post('/shops', ['externalId' => $externalId, 'name' => $name])->throw()->json('data');
        return ['shop' => $r, 'token' => $r['instanceToken'] ?? null];
    }

    public function qr(string $externalId): array
    {
        return $this->http()->get("/shops/{$externalId}/qr")->throw()->json('data');   // ['state','qr','expiresInSeconds']
    }

    public function sendText(string $externalId, string $to, string $text, string $idempotencyKey, array $reference): array
    {
        $r = $this->http()->withHeaders(['Idempotency-Key' => $idempotencyKey])
            ->post("/shops/{$externalId}/messages/text", ['to' => $to, 'text' => $text, 'reference' => $reference]);
        if ($r->status() === 422 && $r->json('error.code') === 'not_on_whatsapp') {
            return ['status' => 'not_on_whatsapp'];                  // not billed, nothing queued
        }
        return $r->throw()->json('data.message');
    }

    public function sendPdfByUrl(string $externalId, string $to, string $url, string $name, string $idem, array $reference): array
    {
        return $this->http()->withHeaders(['Idempotency-Key' => $idem])
            ->post("/shops/{$externalId}/messages/document", ['to' => $to, 'url' => $url, 'fileName' => $name, 'reference' => $reference])
            ->throw()->json('data.message');
    }

    public function sendPdfUpload(string $externalId, string $to, string $path, string $idem, array $reference): array
    {
        return $this->http()->withHeaders(['Idempotency-Key' => $idem])
            ->attach('file', file_get_contents($path), basename($path))
            ->post("/shops/{$externalId}/messages/document", ['to' => $to, 'reference' => json_encode($reference)])
            ->throw()->json('data.message');
    }

    public function suspendShop(string $externalId, string $reason): array
    {
        return $this->http()->post("/shops/{$externalId}/suspend", ['reason' => $reason])->throw()->json('data');
    }
}
config/services.php
// config/services.php
'whatsapp' => ['base' => env('WHATSAPP_BASE'), 'key' => env('WHATSAPP_KEY'), 'webhook_secret' => env('WHATSAPP_WEBHOOK_SECRET')],
cURL for the whole flow
curl -s -X POST $SJ/shops -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d '{"externalId":"shop_1042","name":"Mama Chidi Store"}'
curl -s $SJ/shops/shop_1042/qr -H "Authorization: Bearer $KEY"
curl -s -X POST $SJ/shops/shop_1042/messages/text -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -H 'Idempotency-Key: sale-1-receipt' \
  -d '{"to":"2348031234567","text":"Hello","reference":{"saleId":"1","eventType":"receipt","shopId":"shop_1042"}}'
curl -s "$SJ/messages?from=2026-11-01T00:00:00Z&limit=100" -H "Authorization: Bearer $KEY"
curl -s "$SJ/statement?month=2026-10" -H "Authorization: Bearer $KEY"

Before you go liveBeta

  • Your key is limited to your server IP addresses and stored in an environment variable, not in code.
  • Your file host allow-list and device name are set (ask support).
  • Your webhook URL is https, POST /webhook/test arrives and the signature verifies, and you de-duplicate on the event id.
  • Every send carries an Idempotency-Key derived from your own ids.
  • You charge your shops once per usageId and run the updatedSince reconciliation job.
  • You queue and retry on 429 with retryAfterSeconds, and show the QR again on logged_out.
  • You handle suspected_ban (tell the shop owner to check the phone) and not_on_whatsapp (nothing billed).
  • You have read the warm-up table and will not raise caps to speed up a new number.

Download the specification: openapi.json.