MazBot Logo MazBot Docs

Introduction

Welcome to the official MazBot Developer Hub. Our unified RESTful API empowers developers to establish robust integrations between their external CRMs, ticket modules, and WhatsApp Cloud accounts.

Unified API Standards

All requests must target our verified subdomain endpoints. The system enforces strict dual-layer authentication (API Key & JSON Web Token), structured validation error schemas, and standard JSON response envelopes.

Base Domain & Versioning

The API is deployed globally on the primary server. There is no /v1 prefix in route paths. Documentation is hosted at https://api.mazbot.net/ (read-only); always call the API at https://mazbot.net/api, not the docs subdomain.

OFFICIAL BASE URL: https://mazbot.net/api

Developer Quick Checklist

  • Verify your account **API Key** from your Profile dashboard page.
  • Use clean numbers without `+` symbols (**International Format**).
  • Manage high-throughput requests within the **60 req/min** limit.
  • Re-login when JWT returns 401 (token expired or invalid).
  • Confirm locale prefix if routes return 404 (see Locale Prefix).
  • Template variable arrays start at index 1, not 0.

Quick Start Guide

Connect your codebase to MazBot in under 3 minutes following these three simple milestones:

  1. 1
    Acquire API Credentials

    Log in to the Client Panel and navigate to your user Profile to generate your secure, case-insensitive `apikey`.

  2. 2
    Obtain Session JWT

    Submit your login credentials alongside your `apikey` to generate an access Bearer Token.

  3. 3
    Fire a WhatsApp Message

    Call `POST /whatsapp/send-template` with your template details or `POST /send-message` for direct chats.

Quick Start Authentication
# Step 1: Exchange credentials and apikey for JWT Access Token

curl -X POST "https://mazbot.net/api/login" \

  -H "apikey: YOUR_API_KEY_HERE" \

  -H "Content-Type: application/json" \

  -d '{

    "email": "[email protected]",

    "password": "your_secure_password"

  }'

Locale Prefix

Routes are registered under an optional locale segment. When your MazBot instance default language is English, paths are:

https://mazbot.net/api/login

When the default language is not English (e.g. Arabic), the same route may be:

https://mazbot.net/ar/api/login

404 troubleshooting

If a call to /api/... returns 404, retry with /{locale}/api/... using your dashboard default locale (or the locale in your browser URL when logged in).

Examples

  • EN: POST /api/login
  • AR: POST /ar/api/login
  • AR: GET /ar/api/chat-rooms

Authentication Flow

MazBot enforces a Dual-Layer Authentication Scheme to insulate system routes. All private endpoints verify access authorization tokens sequentially:

Layer 1: apiKey Header

Required for every single API request, including logins. This header is evaluated in a case-insensitive manner (you can pass `apikey`, `apiKey`, or `APIKEY`).

Situation HTTP Message
Header missing401api_key_missing
Invalid key403API key invalid
Layer 2: JWT Bearer Token

Generated dynamically by standard logins. Must be supplied as a `Authorization: Bearer ` header in all state-changing endpoints (sending messages, pulling staff details).

Token Lifespans & Expirations

  • JWT Lifespan: Token TTL is configured server-side (JWT_TTL). Many installs use 60 minutes; some may use non-expiring tokens if unset.
  • Refresh Token: Not supported. Re-login via POST /login when you receive HTTP 401.
  • Login rate limit: POST /login is limited to 5 requests/minute per IP (independent of the 60/min API limit).

POST /login

Exchange platform credentials and a valid `apikey` for a session JWT.

Staff-Only Authentication:

This endpoint authenticates client-staff users only. Account owners (client-admin) must use the dashboard to access the system. Attempting to login with an owner account will return 401 Unauthorized.

Parameter Type Requirement Description
email string Required Your registered MazBot account email.
password string Required Your primary MazBot account password.
Session Login Endpoint
POST /api/login HTTP/1.1

Host: mazbot.net

apikey: YOUR_API_KEY_HERE

Accept: application/json

Content-Type: application/json

{

  "email": "[email protected]",

  "password": "your_secure_password"

}
Success Response Format 200 OK
{

  "success": true,

  "message": "login_successfully",

  "data": {

    "id": 5,

    "name": "Migo Developer",

    "role_id": 2,

    "client_id": 1,

    "phone": "201012345678",

    "email": "[email protected]",

    "openai_api_key": "...",

    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."

  }

}
Security:

Treat the login response as sensitive. It may include openai_api_key and the session JWT. Do not log full responses in production.

Common Integration Mistakes

Mistake Correct approach
Using is_seen backwardsis_seen=1 = unread; is_seen=0 = read / no unread
Confusing contact ID with chat room IDGET /message/{id} uses contacts.id
Expecting a flat message arrayMessages are grouped by date in data.messages
Session messages outside 24hCheck GET /whatsapp/window-status first; handle 422 outside_24h_window by sending a template
Treating 200 on send as "delivered"It means WhatsApp accepted it. Subscribe to message.failed to hear about later failures
Template variables starting at 0Use body_values[1], not [0]
Missing password_confirmationRequired on POST /team-store (min 6 chars)
Owner account API loginOnly client-staff can use API login
Ignoring success: false on HTTP 200Always parse JSON body for subscription/limit errors
Wrong API hostCall mazbot.net/api, not api.mazbot.net
Missing locale prefixTry /{locale}/api/login if 404
Polling too aggressively10–30s interval; not faster than every 5s
API key error status codesMissing key → 401; invalid key → 403

Rate Limiting & Error Management

MazBot implements rigorous traffic throttling thresholds on all router profiles to maintain high system availability.

Rate Throttling Details

Limiter Limit Keyed by
api 60 / minute User ID (authenticated routes)
login_api 5 / minute IP address
auth_public_api 10 / minute IP address (forgot/reset password)

When exceeded: 429 Too Many Requests

Throttler Response Headers

Header Title Description
X-RateLimit-Limit Total capacity allocation assigned to the endpoint (60).
X-RateLimit-Remaining Remaining permissible transactions inside the current timeframe.
X-RateLimit-Reset Epoch UNIX timestamp indicating when the counter resets back to full.
Retry-After Number of seconds to hold off before attempting requests again (HTTP 429).

HTTP Response Reference

The API returns standard HTTP status envelopes. Every error response uses a consistent, structured payload:

HTTP Code Meaning Typical Triggers / Response Payloads
200 / 201 Success Request executed successfully. Returns `success: true` and the requested data wrapper.
400 Bad Request Malformed JSON, invalid message parameters, or invalid reply ID triggers.
401 Unauthorized Missing API key; expired, invalid, or missing JWT Bearer token.
403 Forbidden Invalid API key; insufficient permissions; conversation limit.
404 Not Found Target database records (like contact ID or room ID) do not exist or belong to another client.
422 Validation Error Missing required fields, or invalid phone layout parameters.
429 Too Many Requests Exceeded the maximum permitted limit of 60 requests per minute.
500 Server Error Internal system exception, or failure communicating with Meta's Graph API.

HTTP 200 with success: false

Some business-rule failures return HTTP 200 with success: false (not 4xx). This applies especially to no active subscription or insufficient campaign/conversation limits on template send. Always check the success field, not only the status code.

Structured Error Envelope (422) 422 Unprocessable
{

  "success": false,

  "message": "Validation failed",

  "data": {

    "receiver_id": [

      "The receiver id field is required."

    ]

  }

}
Common Error Payloads (400, 401, 403, 404, 429) Error Reference
HTTP 400 Bad Request:
{

  "success": false,

  "message": "Invalid reply message ID.",

  "data": []

}
HTTP 401 Unauthorized:
{

  "success": false,

  "message": "Token is expired",

  "data": []

}
HTTP 403 Forbidden:
{

  "success": false,

  "message": "API key invalid",

  "data": []

}
HTTP 404 Not Found:
{

  "success": false,

  "message": "Contact not found",

  "data": []

}
HTTP 429 Too Many Requests:
{

  "success": false,

  "message": "Too many requests. Please wait before retrying.",

  "data": []

}

Meta Graph API Errors

In addition to internal validation checks, our backend intercepts callbacks directly from Meta (e.g. WhatsApp code 131060 "Message unavailable"). When such a transaction failure is caught, the descriptive Meta payload is appended directly into the message's database error field, visible when calling GET /message/{contact_id}.

Phone Number Formatting

MazBot integrates high-durability, automated sanitization algorithms via its core WhatsApp engine traits before passing records to Meta.

Backend Regex Sanitization

When numbers are processed, the system executes double regex normalization matches under the hood:

Laravel Clean Regex Normalizer
$phone = preg_replace('/\D+/', '', (string) $phone); // Strips all non-digit chars
$phone = preg_replace('/^0{2,}/', '', $phone); // Trims extra leading double zeros

Formatting Guidelines

We highly recommend sending sanitized, clean parameters directly in international format:

  • Clean Layout (Preferred): `201012345678` (Egypt), `966512345678` (Saudi Arabia)
  • Sanitized Automatically: `+20 101-234-5678` is fully parsed by the backend to `201012345678`

Sanitization Lifecycle

Input String: +20 10-123-45-678
Database State: 201012345678

Send Session (Normal) Message

Utilize this endpoint to send text, an image or a document directly to open chat sessions. This works dynamically outside of meta templates, provided a 24-hour customer service window is currently active. The response includes meta_response, WhatsApp's own answer to your request.

24-HOUR CUSTOMER SERVICE WINDOW

Session messages (normal messages) can only be sent when the customer is inside the messaging window:

  • Customer messaged or replied within the last 24 hours, or
  • A Click-to-WhatsApp referral message exists within the last 72 hours

Only messages from the customer count. Messages you send (session, template, campaign, inbox) never open or extend the window.

Before sending, call GET /whatsapp/window-status: can_send_message: true → send with POST /send-message; false → use POST /whatsapp/send-template instead. (data.can_not_reply from GET /message/{contact_id} follows the same rule.)

For WhatsApp contacts, send-message refuses a request outside the window with HTTP 422 and data.error_code: "outside_24h_window", before anything is sent or charged. A mobile with no contact yet is refused the same way. Telegram contacts have no window.

RECOMMENDED FLOW

  1. GET /whatsapp/window-status?mobile=… (or ?receiver_id=…).
  2. can_send_message: true → POST /send-message. false → POST /whatsapp/send-template.
  3. Keep the message_id from the response.
  4. Subscribe a webhook endpoint to message.failed (and optionally message.delivered / message.read) to learn the final result of that message_id. "Sent" only means WhatsApp accepted it. See Outbound message status.
  5. Still handle 422 outside_24h_window: the window can close between steps 1 and 2.

POST /send-message

Required MIME-Type Encoding:

Requests to this endpoint **must** be sent as multipart/form-data binary uploads rather than standard JSON objects if you are attaching images or documents.

Field Type Required Description
receiver_id integer Conditional* contacts.id — required if mobile is omitted.
mobile string Conditional* Customer phone (digits). Lookup or create contact — required if receiver_id is omitted.
name string No Used when creating a contact from mobile.
message string Optional* Text string body. Required if image or document parameters are missing. Sent with an image or document, it is the file's caption, shown under the file (max 1024 characters).
image file (binary) Optional* Upload a JPEG/PNG image binary (Max 5MB).
document file (binary) Optional* Upload a PDF invoice or doc sheet binary (Max 10MB). The customer sees the uploaded file's own name (e.g. Invoice-1042.pdf).
Contact targeting

Pass receiver_id for a known contact, or mobile to lookup/create automatically (same as send-template). To resolve an ID first, use POST /contact/resolve-by-phone.

Headers

HeaderValueRequired
apikeyYour API key from the MazBot dashboardYes
AuthorizationBearer YOUR_JWT (token returned by POST /login)Yes
Content-Typemultipart/form-data (required when attaching a file); a text-only request may also use application/x-www-form-urlencoded. Your HTTP client sets it for you.Yes
Success Response Format (text) 200 OK
{
  "success": true,
  "message": "Message sent successfully",
  "data": {
    "message_id": 9822,
    "message_type": "text",
    "receiver_id": 142,
    "conversation_id": 47,
    "remaining_conversations": 249,
    "meta_response": {
      "messaging_product": "whatsapp",
      "contacts": [{ "input": "201012345678", "wa_id": "201012345678" }],
      "messages": [{ "id": "wamid.HBgMMjAxMDEyMzQ1Njc4FQIAERgSQTFCMkMzRDRFNUY2QTdCOAA=" }]
    }
  }
}

message_id is the internal message ID (same as send-template). data.message_type is text, image or document. "Sent" means WhatsApp accepted the message; delivery is asynchronous. To learn that it was delivered, read or failed later, subscribe to message.delivered / message.read / message.failed, or read status on the message from GET /message/{contact_id}.

Meta's own answer: data.meta_response

meta_response is WhatsApp's original response body, unchanged: the accepted body on success (the WhatsApp message id is messages[0].id), or Meta's {"error": {...}} on a rejection. It is null for Telegram contacts. A text longer than 1500 characters is split into several messages: you get the first part's reply on success, the failing part's reply on failure. Full contract and error codes: meta_response.

Outside the 24-hour window 422
{
  "success": false,
  "message": "This contact has not messaged you in the last 24 hours (72 hours after a click-to-WhatsApp ad), so WhatsApp only accepts template messages. Use whatsapp/send-template instead.",
  "data": {
    "error_code": "outside_24h_window",
    "receiver_id": 142,
    "template_endpoint": "whatsapp/send-template",
    "window": {
      "applies": true,
      "is_open": false,
      "expires_at": "2026-11-14T09:12:40+00:00",
      "seconds_remaining": 0,
      "last_inbound_at": "2026-11-13T09:12:40+00:00",
      "via_referral": false
    }
  }
}

Match on data.error_code (stable), not on message (translated). receiver_id is null when the mobile had no contact (the customer has never written to you). Nothing is created and remaining_conversations is unchanged. Requests refused before reaching WhatsApp (422, 403, 404) have no meta_response.

Other error responses

Validation failed (nothing sent) 422
{
  "success": false,
  "message": "Validation Failed",
  "data": {
    "message": ["The message field is required when none of image / document are present."]
  }
}
Conversation quota used up (no subscription: "No active subscription") 403
{
  "success": false,
  "message": "Insufficient Conversation Limit",
  "data": []
}

An unknown receiver_id (or a contact of another account) answers 404 with "message": "Contact not found.".

WhatsApp rejected the message (conversation not charged) 500
{
  "success": false,
  "message": "(#131026) Message undeliverable",
  "data": {
    "message_id": 9823,
    "meta_response": {
      "error": {
        "message": "(#131026) Message undeliverable",
        "type": "OAuthException",
        "code": 131026,
        "fbtrace_id": "AbC123"
      }
    }
  }
}

Applies to text, image and document. message is Meta's error text, data.meta_response is Meta's error body. Exception: a failed text whose WhatsApp reply could not be captured answers 500 with "data": [], so read success and message first. See the error code table for what each code means.

WhatsApp is throttling you: retry later (not charged) 503
{
  "success": false,
  "message": "(#130429) Rate limit hit",
  "data": {
    "error_code": "meta_rate_limited",
    "message_id": 9824,
    "meta_response": {
      "error": {
        "message": "(#130429) Rate limit hit",
        "type": "OAuthException",
        "code": 130429,
        "fbtrace_id": "AbC123"
      }
    }
  }
}

A throughput limit such as Meta error 130429, 131048, 80007, or Meta's temporary 131000 means WhatsApp asked you to slow down. The API answers 503 with data.error_code: "meta_rate_limited", marks the message failed, does not charge a conversation, and you send it again a little later.

A long text is sent in parts (see Long text is split). If a later part is throttled (503) or rejected (500), the earlier parts were already delivered, so retrying the whole text sends them again.

Media Storage & Delivery Pipeline

  1. Binary Validation: The backend intercepts the multipart parameter and validates the file's MIME type extension.
  2. Storage Upload: The file is written to our local media directories or wasabi cloud space to generate a permanent static URL.
  3. Meta API Forwarding: The public asset URL is structured inside a dynamic message payload and pushed directly to Meta API servers for cellular delivery.
Send Message (Multipart)
POST /api/send-message HTTP/1.1

Host: mazbot.net

apikey: YOUR_API_KEY_HERE

Authorization: Bearer YOUR_JWT_TOKEN_HERE

Accept: application/json

Content-Type: multipart/form-data; boundary=boundary123

--boundary123

Content-Disposition: form-data; name="receiver_id"

142

--boundary123

Content-Disposition: form-data; name="message"

Hello from the REST API!

--boundary123

Content-Disposition: form-data; name="document"; filename="invoice.pdf"

Content-Type: application/pdf

[BINARY_DATA]

--boundary123--
Send text: curl
curl -X POST "https://mazbot.net/api/send-message" \
  -H "apikey: YOUR_API_KEY_HERE" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN_HERE" \
  -H "Accept: application/json" \
  -F "receiver_id=142" \
  -F "message=Hello, how can I help?"
Send text: raw HTTP
POST /api/send-message HTTP/1.1
Host: mazbot.net
apikey: YOUR_API_KEY_HERE
Authorization: Bearer YOUR_JWT_TOKEN_HERE
Accept: application/json
Content-Type: application/x-www-form-urlencoded

receiver_id=142&message=Hello%2C+how+can+I+help%3F
Send media: curl (image / document)
# Image with a caption
curl -X POST "https://mazbot.net/api/send-message" \
  -H "apikey: YOUR_API_KEY_HERE" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN_HERE" \
  -H "Accept: application/json" \
  -F "receiver_id=101" \
  -F "message=Your order photo" \
  -F "image=@/path/to/photo.jpg"

# Document to a phone number
curl -X POST "https://mazbot.net/api/send-message" \
  -H "apikey: YOUR_API_KEY_HERE" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN_HERE" \
  -H "Accept: application/json" \
  -F "mobile=201012345678" \
  -F "document=@/path/to/Invoice-1042.pdf"

24-Hour Window Status

Check the 24-hour customer service window for one contact before sending, to choose between send-message and whatsapp/send-template. It never creates a contact and costs nothing.

GET /whatsapp/window-status

Query Type Required Description
receiver_id integer Conditional* contacts.id — required if mobile is omitted.
mobile string Conditional* Phone in international format (see Phone sanitization) — required if receiver_id is omitted.
Response field Meaning
can_send_messagetrue → send-message will be delivered now. false → only whatsapp/send-template.
allowedEndpoints you can use for this contact right now.
window.expires_atWhen the window closes (ISO 8601). null if the customer never wrote to you.
window.seconds_remainingSeconds until it closes (0 when closed).
window.last_inbound_atLast message from the customer.
window.via_referraltrue when the window is open because of a Click-to-WhatsApp ad (72 hours).
window.appliesfalse for channels without a window (e.g. Telegram): always open.
  • A mobile with no contact yet returns 200 with receiver_id: null and can_send_message: false (the customer has never written to you).
  • Unknown receiver_id (or a contact of another account) → 404. Neither field → 422.
  • The window only reopens when the customer writes again. Sending a template does not reopen it, but the customer's reply to it does.
Request
GET /api/whatsapp/window-status?mobile=201012345678 HTTP/1.1
Host: mazbot.net
apikey: YOUR_API_KEY_HERE
Authorization: Bearer YOUR_JWT_TOKEN_HERE
Accept: application/json
Success Response Format 200 OK
{
  "success": true,
  "message": "24-hour messaging window status loaded.",
  "data": {
    "receiver_id": 142,
    "can_send_message": true,
    "allowed": ["send-message", "whatsapp/send-template"],
    "window": {
      "applies": true,
      "is_open": true,
      "expires_at": "2026-11-15T21:40:05+00:00",
      "seconds_remaining": 41520,
      "last_inbound_at": "2026-11-14T21:40:05+00:00",
      "via_referral": false
    }
  }
}

Send Template Message

Pushes registered Meta WhatsApp templates directly to targets. Supports rich media headers (images, documents, videos) and complex variable binding arrays. The response includes meta_response (Meta's original answer), so a rejection such as a wrong parameter count is visible immediately.

CRITICAL PAYLOAD REQUIREMENT

Both body_values and body_matchs arrays **MUST** use indexes starting at 1 (e.g. body_values[1] instead of body_values[0]).

Why? The local preview renderer and Laravel dashboard log-sync services fail to compile, truncate, or substitute custom attributes if index 0 is present.

POST /whatsapp/send-template

Headers

HeaderValueRequired
apikeyYour API key from the MazBot dashboardYes
AuthorizationBearer YOUR_JWT (token returned by POST /login)Yes
Content-Typeapplication/json when there is no header file; multipart/form-data when uploading header mediaYes
Field Name Type Required Description
template_id integer Yes The template configuration ID registered in your client dashboard.
mobile string Optional* Clean target number (`201002345678`). Required if `contact_id` is blank.
contact_id integer Optional* Existing database contact ID (`contacts.id`). Required if `mobile` is blank.
body_matchs array No Maps dynamic placeholders (e.g. `{{1}}`). Accepts:
  • "input_value": Use custom manual input.
  • "contact_name": Replace with database contact name.
  • "contact_phone": Replace with database contact number.
body_values array No The raw string parameters to map when using `input_value` matches.
button_matchs array No Used to bind dynamic buttons (e.g. dynamic URL or copy code buttons). Accepts "input_value". Array key represents the variable index (e.g. "1" for the first button).
button_values array No The actual value (text or code) to pass to the dynamic button when using "input_value".
image file (binary) No Header image — max 2 MB (jpeg, png, jpg).
document file (binary) No Header PDF — max 5 MB. The customer sees the uploaded file's own name, so name it clearly (e.g. Invoice-1042.pdf).
video file (binary) No Header MP4 — max 10 MB.
audio file (binary) No Header MP3 — max 5 MB.

JSON Payload Example (Without Media Header)

If your template does not require media headers (e.g., a simple OTP template with dynamic buttons or text body values), you can send the request using application/json encoding:

{

  "template_id": 42,

  "mobile": "201012345678",

  "body_matchs": {

    "1": "input_value"

  },

  "body_values": {

    "1": "123456"

  },

  "button_matchs": {

    "1": "input_value"

  },

  "button_values": {

    "1": "123456"

  }

}

What the response tells you

The API makes one attempt to send the template to WhatsApp while your request is open, and returns the result together with meta_response (Meta's original response body):

ResultMeaningmeta_response
200, status: "sent"WhatsApp accepted the template.Meta's accepted body
200, status: "scheduled"Not confirmed yet: WhatsApp was busy or unreachable, or a campaign of yours is sending at that moment. MazBot keeps the message and retries it automatically. The final result arrives through the message.failed / message.delivered webhooks, or read status from GET /message/{contact_id}.Meta's first reply, or null
422WhatsApp rejected the template (for example #132000: wrong number of parameters). The conversation is not charged (refunded).Meta's error body, or null when MazBot refused it before calling WhatsApp
500Internal failure: the send could neither be made nor queued. The conversation is refunded. Retry.null
200, success: falseQuota or subscription error (as before). Always check success, not only the status code.not present

message_id is the internal message ID. Sending a template does not open the 24-hour window: can_not_reply stays true until the customer replies.

Response time: set your timeout to 65 s or more

The call waits for WhatsApp's answer, usually under 2 seconds but up to about 60 seconds when WhatsApp is slow. Set your HTTP client timeout to 65 seconds or more. If your client times out anyway, the template may still have been sent or queued: check the message's status with GET /message/{contact_id} before retrying, otherwise the customer can receive it twice.

Send Template (Multiparts Headers)
POST /api/whatsapp/send-template HTTP/1.1

Host: mazbot.net

apikey: YOUR_API_KEY_HERE

Authorization: Bearer YOUR_JWT_TOKEN_HERE

Accept: application/json

Content-Type: multipart/form-data; boundary=boundary555

--boundary555

Content-Disposition: form-data; name="template_id"

42

--boundary555

Content-Disposition: form-data; name="mobile"

201012345678

--boundary555

Content-Disposition: form-data; name="body_matchs[1]"

input_value

--boundary555

Content-Disposition: form-data; name="body_values[1]"

Ahmed Mohamed

--boundary555

Content-Disposition: form-data; name="button_matchs[1]"

input_value

--boundary555

Content-Disposition: form-data; name="button_values[1]"

123456

--boundary555

Content-Disposition: form-data; name="document"; filename="report.pdf"

Content-Type: application/pdf

[BINARY_PDF_DATA]

--boundary555--
Send template: curl (JSON, no header media)
curl -X POST "https://mazbot.net/api/whatsapp/send-template" \
  -H "apikey: YOUR_API_KEY_HERE" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN_HERE" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json" \
  -d '{
    "template_id": 5,
    "contact_id": 123,
    "body_values": { "1": "Ahmed Mohamed", "2": "ORD-12345" },
    "body_matchs": { "1": "input_value", "2": "input_value" }
  }'
Send template: curl (PDF header, multipart)
curl -X POST "https://mazbot.net/api/whatsapp/send-template" \
  -H "apikey: YOUR_API_KEY_HERE" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN_HERE" \
  -H "Accept: application/json" \
  -F "template_id=6" \
  -F "mobile=201012345678" \
  -F "body_values[1]=INV-2026-001" \
  -F "body_matchs[1]=input_value" \
  -F "document=@/path/to/Invoice-1042.pdf"
Send template: raw HTTP (JSON)
POST /api/whatsapp/send-template HTTP/1.1
Host: mazbot.net
apikey: YOUR_API_KEY_HERE
Authorization: Bearer YOUR_JWT_TOKEN_HERE
Content-Type: application/json
Accept: application/json

{
  "template_id": 5,
  "contact_id": 123,
  "body_values": { "1": "Ahmed Mohamed", "2": "ORD-12345" },
  "body_matchs": { "1": "input_value", "2": "input_value" }
}
Success: sent (status "sent") 200 OK
{
  "success": true,
  "message": "Message sent successfully",
  "data": {
    "message_id": 5001,
    "remaining_conversations": 95,
    "message_details": {
      "template": {
        "id": 5,
        "name": "order_confirmation",
        "components": [{ "type": "BODY", "text": "Hello {{1}}, your order {{2}} is ready" }]
      },
      "contact": { "id": 123, "name": "Ahmed Mohamed", "phone": "201234567890", "type": "whatsapp" },
      "message": {
        "type": "template",
        "status": "sent",
        "created_at": "2026-11-20T10:15:00.000000Z",
        "schedule_at": "2026-11-20T10:15:00.000000Z",
        "components": {
          "header": [],
          "body": [
            { "type": "text", "text": "Ahmed Mohamed" },
            { "type": "text", "text": "ORD-12345" }
          ],
          "buttons": []
        }
      },
      "subscription": { "remaining_conversations": 95, "remaining_campaigns": 48 }
    },
    "meta_response": {
      "messaging_product": "whatsapp",
      "contacts": [{ "input": "201234567890", "wa_id": "201234567890" }],
      "messages": [{ "id": "wamid.HBgMMjAxMjM0NTY3ODkwFQIAERgSQTFCMkMzRDRFNUY2QTdCOAA=" }]
    }
  }
}
Not confirmed yet: status "scheduled" (same shape, other values) 200 OK
"message": {
  "type": "template",
  "status": "scheduled",
  ...
},
...
"meta_response": {
  "error": {
    "message": "(#130429) Rate limit hit",
    "type": "OAuthException",
    "code": 130429,
    "fbtrace_id": "AbC123"
  }
}
WhatsApp rejected the template (not charged) 422
{
  "success": false,
  "message": "(#132000) Number of parameters does not match the expected number of params",
  "data": {
    "message_id": 5003,
    "meta_response": {
      "error": {
        "message": "(#132000) Number of parameters does not match the expected number of params",
        "type": "OAuthException",
        "code": 132000,
        "error_data": {
          "messaging_product": "whatsapp",
          "details": "body: number of localizable_params (4) does not match the expected number of params (5)"
        },
        "fbtrace_id": "AbC123"
      }
    }
  }
}
Validation failed 422
{
  "success": false,
  "message": "Validation Failed",
  "data": { "template_id": ["The template id field is required."] }
}
Internal failure (refunded) 500
{
  "success": false,
  "message": "Queue connection refused",
  "data": {
    "message_id": 5004,
    "meta_response": null
  }
}
Limit / subscription errors

Still answer HTTP 200 with success: false, for example "message": "Insufficient Conversation Limit" and "data": []. Check success, not only the status code. An unknown template or contact answers 404.

Meta Response (meta_response)

Every send response from POST /send-message and POST /whatsapp/send-template carries data.meta_response: WhatsApp's (Meta's) original response body, unchanged. Log it, or read Meta's error code, without guessing. All other fields keep their names and meaning.

  • On success it is Meta's accepted body; the WhatsApp message id is in messages[0].id.
  • On a rejection it is Meta's error body: { "error": { "message", "type", "code", "fbtrace_id", ... } }.

WHEN IT IS null

  • The contact is a Telegram contact.
  • WhatsApp could not be reached, or answered something that is not JSON.
  • A template was queued before WhatsApp answered (status: "scheduled").

Requests refused before reaching WhatsApp (validation 422, quota or subscription 403, contact not found 404, outside the 24-hour window 422) do not contain the field, because nothing was sent.

LONG TEXT IS SPLIT

A text longer than 1500 characters is sent as several WhatsApp messages, but you still get one object. On success it is the reply for the first part. On failure it is the reply for the part that failed. The parts before it were already delivered: if a later part is throttled (503) or rejected (500), retrying the whole text sends those earlier parts again.

Template results

ResultMeaningmeta_response
200, status: "sent"WhatsApp accepted the template.Meta's accepted body
200, status: "scheduled"Not confirmed yet: WhatsApp was busy or unreachable, or a campaign of yours is sending at that moment. MazBot keeps the message and retries it automatically. The final result arrives through the message.failed / message.delivered webhooks, or read status from GET /message/{contact_id}.Meta's first reply, or null
422WhatsApp rejected the template (for example #132000: wrong number of parameters). The conversation is not charged (refunded).Meta's error body, or null when MazBot refused it before calling WhatsApp
500Internal failure: the send could neither be made nor queued. The conversation is refunded. Retry.null
200, success: falseQuota or subscription error (as before). Always check success, not only the status code.not present

Common Meta error codes

CodeMeaningWhat to do
131026Message undeliverable: the number is not on WhatsApp, or cannot receive this message.Check the number. Nothing to retry.
131047Re-engagement: more than 24 hours since the customer's last message.Send a template instead (Send Template).
131051Unsupported message type.Send a supported type (text, image, PDF document).
132000Template parameter count does not match the template.Send exactly as many values as the template has variables.
132001Template does not exist in that language, or is not approved.Check the template ID, language and approval status in the dashboard.
132012Template parameter format does not match the template.Fix the value format (e.g. text where a number or date is expected).
130429Throughput rate limit hit.Retry later. MazBot answers 503 meta_rate_limited for session messages and queues templates (scheduled).
100Invalid parameter in the request.Read error.message / error_data.details for the field to fix.
190Access token expired or invalid.Reconnect the WhatsApp connection in the MazBot panel.
meta_response on success 200 OK
"meta_response": {
  "messaging_product": "whatsapp",
  "contacts": [{ "input": "201012345678", "wa_id": "201012345678" }],
  "messages": [{ "id": "wamid.HBgMMjAxMDEyMzQ1Njc4FQIAERgSQTFCMkMzRDRFNUY2QTdCOAA=" }]
}
meta_response on a rejection 500
"meta_response": {
  "error": {
    "message": "(#131026) Message undeliverable",
    "type": "OAuthException",
    "code": 131026,
    "fbtrace_id": "AbC123"
  }
}

WhatsApp Integration

Enhanced WhatsApp features: native location pins, interactive buttons/lists, and outbound webhooks to your application. Version 1.3.0 (July 2026).

RequirementDetails
AuthenticationAPI key + JWT (same as Messaging)
WhatsApp channelContact must be a WhatsApp contact
Webhook URLSettings → Webhook (requires Integration permission)
Queue workerOutbound messages and webhook delivery use queues

POST /whatsapp/send-location

Sends a native WhatsApp map pin (not a text URL). Provide receiver_id or mobile.

FieldRequiredDescription
receiver_idYes*Contact ID
mobileYes*International phone (creates contact if needed)
latitudeYes-90 to 90
longitudeYes-180 to 180
location_nameNoPin title
addressNoAddress line

POST /whatsapp/send-interactive

type: "button" — 1–3 buttons; each buttons[].id is returned in webhooks when tapped. type: "list" — list menu with sections, button_text, and row id values.

Field (button)RequiredNotes
typeYesbutton
bodyYesMain message text
header / footerNoMax 60 characters each
buttons[].idYesAction key (e.g. confirm_reservation)
buttons[].textYesLabel on button (max 20 chars)
{
  "receiver_id": 142,
  "type": "button",
  "body": "Please confirm your reservation.",
  "buttons": [
    { "id": "confirm_reservation", "text": "Confirm" },
    { "id": "reschedule_reservation", "text": "Reschedule" },
    { "id": "cancel_reservation", "text": "Cancel" }
  ]
}

Outbound webhooks

When configured, MazBot POSTs signed JSON events to your webhook URL (whatsapp_external_webhook_url).

  1. Go to Settings → Webhook
  2. Enter WhatsApp external webhook URL
  3. Choose subscribed event types (empty = all events, except the opt-in events below)
  4. Save — a signing secret is generated automatically
  5. Verify requests using X-Mazbot-Signature: sha256=<hmac>
HeaderDescription
X-Mazbot-Event-TypeEvent type string
X-Mazbot-Delivery-IdSame as payload id
X-Mazbot-Signaturesha256= + HMAC-SHA256 of raw JSON body
EventWhen fired
message.receivedCustomer sends text/media
interactive.selectedCustomer taps button or list option
appointment.createdReservation created via API
appointment.updatedReservation rescheduled
appointment.cancelledReservation cancelled
user.registeredEmit manually via /webhooks/emit
password.reset_requestedEmit manually
password.reset_completedEmit manually
custom.<name>Your custom business events
message.deliveredOpt-in. A message you sent was delivered to the customer
message.readOpt-in. A message you sent was read
message.failedOpt-in. WhatsApp failed a message you sent, also after it was accepted (e.g. 131047, outside the 24h window)
whatsapp_form.submittedOpt-in. A customer submitted a WhatsApp form

Opt-in events are only delivered to an endpoint that ticks them explicitly in Settings → Webhooks. "All events" does not include them, so existing endpoints don't start receiving them.

Outbound message status events

message.delivered, message.read and message.failed report the status of messages you sent (API send-message / send-template, inbox, campaigns, bots). Each status is sent once, even if WhatsApp repeats it; sent has no event.

data.message.id is the message_id returned by POST /send-message and POST /whatsapp/send-template. error_code / error_message are filled for message.failed only (WhatsApp error codes).

{
  "id": "0b9e4c1e-6a1d-4d55-9a57-3f1f2b0e7c11",
  "type": "message.failed",
  "created_at": "2026-11-15T10:00:05+00:00",
  "client_id": 12,
  "data": {
    "message": {
      "id": 9822,
      "wamid": "wamid.HBgMMjAxMDEyMzQ1Njc4FQIAERgSM0Y...",
      "status": "failed",
      "error_code": 131047,
      "error_message": "Re-engagement message",
      "message_type": "text",
      "status_at": "2026-11-15T10:00:04+00:00"
    },
    "contact": { "id": 142, "phone": "201012345678" }
  }
}

On interactive.selected, read data.selection.id — not display text. Map stable button ids (e.g. confirm_reservation, reschedule_reservation, cancel_reservation) to your business handlers.

POST /webhooks/emit

Emit custom or built-in events from your integration. Fields: event_type (required), data (required object), contact_id (optional — attaches contact info).

{
  "event_type": "custom.register",
  "contact_id": 142,
  "data": {
    "user_id": 501,
    "email": "[email protected]",
    "registered_at": "2026-07-10T15:00:00Z"
  }
}

Built-in types (without custom. prefix): user.registered, password.reset_requested, password.reset_completed.

End-to-end reservation flow

  1. Your app calls POST /whatsapp/send-interactive (Confirm / Reschedule / Cancel buttons)
  2. MazBot delivers interactive buttons to WhatsApp
  3. Customer taps a button
  4. MazBot POSTs interactive.selected to your webhook with data.selection.id
  5. Your handler updates booking status

Related endpoints

EndpointPurpose
POST /send-messageText, image, document
POST /whatsapp/send-templateTemplate messages
POST /appointmentsCreate reservation
POST /appointments/{id}/rescheduleUpdate reservation
POST /appointments/{id}/cancelCancel reservation
POST /contact/resolve-by-phoneGet receiver_id from phone
Limits & notes: Max 3 buttons per message; button/list label max 20 chars; header/footer max 60 chars; webhook delivery queued with 5 retries (exponential backoff). If no events are checked in webhook settings, all event types are sent. Inbound messages still appear in the MazBot inbox and support REST polling.
Send location — success
{
  "success": true,
  "message": "message_sent_successfully",
  "data": {
    "message_id": 9821,
    "message_type": "location",
    "receiver_id": 142,
    "conversation_id": 47
  }
}
Webhook payload example
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "type": "interactive.selected",
  "created_at": "2026-07-10T15:00:00Z",
  "client_id": 12,
  "data": {
    "contact": { "id": 142, "phone": "201012345678", "name": "Ahmed" },
    "message": { "id": 9821, "message_type": "interactive", "value": "Confirm", "meta_type": "interactive" },
    "selection": { "id": "confirm_reservation", "text": "Confirm" }
  }
}
Verify signature (PHP)
$secret = 'your_webhook_secret';
$body = file_get_contents('php://input');
$signature = $_SERVER['HTTP_X_MAZBOT_SIGNATURE'] ?? '';
$expected = 'sha256=' . hash_hmac('sha256', $body, $secret);
if (!hash_equals($expected, $signature)) {
    http_response_code(401);
    exit('Invalid signature');
}
$event = json_decode($body, true);
// Process $event['type'] and $event['data']

AI Auto-Reply Configuration

Connect external scripts to toggle your OpenAI automated responders or prioritize auto-replies across global channels.

POST /ai/contact/toggle-auto-reply

Enable, disable, or reverse the current AI responder status for a designated contact ID.

Field Type Required Description
contact_id integer Yes Target integer contact ID.
ai_reply_enabled boolean No Set `true` to enable or `false` to turn off. If omitted, the server will switch the current state to the opposite values.

POST /ai/reply-priority

Set responder routing priority order (AI Agent vs Local Flow Builder rules).

Field Type Required Description
reply_priority string Yes Accepts strictly: "ai_first" (route to AI Agent first) or "flow_first" (route to local keywords flows first).
Toggle AI Auto-Reply
POST /api/ai/contact/toggle-auto-reply HTTP/1.1

Host: mazbot.net

apikey: YOUR_API_KEY_HERE

Authorization: Bearer YOUR_JWT_TOKEN_HERE

Accept: application/json

Content-Type: application/json

{

  "contact_id": 125,

  "ai_reply_enabled": true

}
Toggle Success Response 200 OK
{

  "success": true,

  "message": "AI auto-reply enabled for this contact",

  "ai_reply_enabled": true,

  "contact_id": 125

}

Team Management & Access Limits

Query team rosters or register new organizational workers. These routes enforce tight plan boundaries and role permissions.

ROLE-BASED PERMISSION GATE

Only the primary Client Owner is permitted to access write endpoints (POST /api/team-store & POST /api/team-update/{id}).

If an API request is initiated by a worker account with a client-staff role, the server halts execution automatically, throwing an HTTP 403 Forbidden alongside an unauthorized_access error message wrapper.

PRIVILEGE ESCALATION PREVENTION

To ensure system integrity and prevent Privilege Escalation, the backend strictly ignores any custom role parameters passed during employee creation. All new records created via POST /api/team-store are hardcoded to the worker role (role_id: 3, user type: client-staff) and locked to the current client tenant account.

Plan Limits Enforcement

Adding team members triggers automated checks against your subscription plan boundary (team_limit). If your roster size matches or exceeds this, the server rejects inputs, returning a 422 Unprocessable status with an insufficient_team_limit validation error message.

POST /team-store

Parameter Type Required Description
first_name string Yes Employee's first name.
last_name string Yes Employee's last name.
email string Yes Unique workplace email address.
password string Yes Secure credential password (minimum 6 chars).
password_confirmation string Yes Must match the password exactly.
phone string No Clean telephone number.

GET /team

Paginated staff list for the client.

GET /staffs-by-client

Simple list of active staff for assignment UIs.

Team Performance & QA (panel)

Response-time KPIs and rule-based conversation scoring are available in the client web panel (not via a separate public API yet).

Panel path Purpose
Team → Team Performance & KPIsPer-agent response time + QA rollups
Team → QA SettingsGreeting phrases, forbidden words, sale detection
Team → QA ScoresPer-conversation scores

User guide

Managers and client admins: see the full setup guide, KPI definitions, and weekly workflow at Team Performance & QA Guide (also linked from the panel View User Guide button).

Add Team Member
POST /api/team-store HTTP/1.1

Host: mazbot.net

apikey: YOUR_API_KEY_HERE

Authorization: Bearer YOUR_JWT_TOKEN_HERE

Accept: application/json

Content-Type: application/json

{

  "first_name": "Ahmed",

  "last_name": "Mohamed",

  "email": "[email protected]",

  "password": "securePassword123",

  "password_confirmation": "securePassword123",

  "phone": "201012345678"

}
Success Response Format 200 OK
{

  "success": true,

  "message": "Created successfully",

  "data": ""

}

Contact Records & Pagination

Query, register, or block active platform customer profiles. List endpoints return robust metadata layouts mapping standard page listings.

Laravel LengthAware Pagination

Query listings (e.g. `GET /whatsapp-contact?page=2`) response envelopes feature a robust, nested `paginate` metadata object mapping the full listing boundary indices:

Metadata Field Type Description
total integer Total record instances available inside the query database.
current_page integer Current active page view index returned.
per_page integer Number of records packaged inside each single page response block.
last_page integer Maximum page threshold indices computed dynamically.
next_page_url string | null API endpoint string URL mapping to pull the immediate next dataset, or `null` if boundary is hit.

GET /whatsapp-contact

Query all system contacts with a standard 10-item limit pagination buffer.

POST /whatsapp-contact-store

Create a new customer profile. Requires phone (numeric, min 11 digits) and country_id (integer). The name field is optional.

POST /whatsapp-contact-update/{id}

Update an existing contact profile. Accepts same parameters: phone (required, numeric min 11 digits), country_id (required), name (optional).

GET /contact/add-blacklist/{id}

Block/unblock the designated record identifier to intercept inbound traffic handlers.

POST /contact/resolve-by-phone

Resolve a WhatsApp contact ID (receiver_id) from a phone number. Creates the contact if it does not exist (same behavior as send-template with mobile).

Field Type Required Description
phone string Yes International digits, e.g. 201012345678
name string No Contact display name when creating
create boolean No Default true — set false to lookup only

Use receiver_id with POST /send-message, or pass mobile directly to send-message / send-template.

Get Contacts Response 200 OK
{

  "success": true,

  "message": "data_retrieved_successfully",

  "data": {

    "contacts": [

      {

        "id": 101,

        "name": "Ahmed Mohamed",

        "phone": "201012345678",

        "email": "[email protected]",

        "type": "whatsapp",

        "status": 1

      }

    ],

    "paginate": {

      "total": 35,

      "current_page": 1,

      "per_page": 10,

      "last_page": 4,

      "prev_page_url": null,

      "next_page_url": "https://mazbot.net/api/whatsapp-contact?page=2",

      "path": "https://mazbot.net/api/whatsapp-contact"

    }

  }

}
Resolve by Phone Response 200 OK
{
  "success": true,
  "message": "data_retrieved_successfully",
  "data": {
    "receiver_id": 142,
    "contact_id": 142,
    "phone": "201012345678",
    "name": "Ahmed",
    "created": false,
    "conversation_id": 47,
    "conversation_unique_id": "uuid-here",
    "is_over_limit": false
  }
}

Incoming Messages & Polling Flow

MazBot receives WhatsApp messages in real time inside the MazBot dashboard and mobile app using persistent WebSockets.

Outbound webhooks (optional)

Configure under Settings → Webhook in the client panel to receive real-time events: message.received, interactive.selected, reservation events, and custom events. See WhatsApp Integration.

Without webhooks, external systems should synchronize using REST polling:

  • Get Chat Rooms List: GET /api/chat-rooms
  • Get Chat Room Messages: GET /api/message/{contact_id}

Polling vs webhooks

Webhooks push events to your URL in real time (recommended when you can host an HTTPS endpoint). Polling below is the fallback when no webhook URL is configured. Inbound messages always appear in the MazBot inbox either way.

Recommended Polling Architecture

  1. Pull Activity: Call `GET /chat-rooms` periodically.
  2. Scan Timestamps: Compare the returned last_conversation_at timestamp against your local stored variables.
  3. Fetch Room Logs: If a room's timestamp indicates new traffic, trigger GET /message/{contact_id} to retrieve its full transcript.
  4. Deduplicate & Write: Verify incoming values against your database by performing unique indices matches on the message id parameter to filter out redundant records before writing.
Polling Frequencies & Rate Blocks

Set a moderate polling frequency interval of 10 to 30 seconds.

STRICT LIMIT: Do not pool more than once every 5 seconds. Triggering faster cycles will saturate resources, instantly kicking off rate limiters and returning persistent `429` status exceptions.

Polling Flowchart

[1] GET /chat-rooms (Every 15s)
[2] Compare last_conversation_at values
[3] GET /message/{contact_id} (Active Rooms)
[4] Unique Index Check & Save Local

Retrieve Chat Rooms

Queries active conversation profiles, providing search filters, assignee constraints, and overall unread status counts.

GET /chat-rooms

Query Field Type Required Description
q string No Filter rooms by matching names or phone digits.
type string No Filter by system network type (e.g. "whatsapp", "telegram").
assignee_id integer No Filter conversations assigned to specific staff ID.
tag_id integer No Filter rooms matching custom categorization tag IDs.
is_seen boolean/int No Unread filter — 1 = has unread inbound messages; 0 = no unread.
is_blacklist boolean No Filter blacklisted contacts.
Get Chat Rooms
GET /api/chat-rooms?type=whatsapp&is_seen=1 HTTP/1.1

Host: mazbot.net

apikey: YOUR_API_KEY_HERE

Authorization: Bearer YOUR_JWT_TOKEN_HERE

Accept: application/json
Chat Rooms Response 200 OK
{

  "success": true,

  "message": "chat_retrieved_successfully",

  "data": {

    "chat_rooms": [

      {

        "id": 12,

        "receiver_id": 12,

        "name": "John Doe",

        "phone": "201012345678",

        "last_conversation_at": "2026-06-12T12:00:00.000000Z",

        "has_unread_conversation": true,

        "assignee_id": 5,

        "assignee_name": "Staff Name",

        "type": "whatsapp",

        "message": {

          "title": "Hello there",

          "is_seen": false,

          "created_at": "2 minutes ago"

        },

        "tags": []

      }

    ],

    "total_unread_messages": 3,

    "next_page_url": true,

    "user_permissions": ["global_inbox"]

  }

}

Retrieve Chat Messages

Queries the transcript logs inside a targeted conversation room. Supports content category filters and provides granular payload keys.

CRITICAL ROUTING NOTICE

In previous versions, documentation listed the messages log path as `/api/chatroom-messages/{id}`.

The **only valid, active endpoint** in our Laravel backend routing engine is strictly:

GET https://mazbot.net/api/message/{contact_id}

Path parameter is contacts.id (contact ID). id and receiver_id in chat room list items are also the contact ID — there is no separate chat-room primary key.

GET /message/{contact_id}

Fetch messages for a contact. Returns messages grouped by date (Today, Yesterday, or dd/mm/yyyy) plus data.user and data.can_not_reply. Each message has a status (scheduled, sending, sent, delivered, read, failed). can_not_reply is true when the customer has not written in the last 24 hours (72h after a Click-to-WhatsApp ad); your own sends and templates do not change it.

Query Parameter Type Required Description
type string No Filters log records by attachment category. Accepts:
  • "media": Retrieve images, audios, and videos.
  • "files": Retrieve PDF, doc, and sheet files.
  • "links": Filter messages holding web URLs.

POST /assign-staff

Assigns a targeted chat room to a specific employee for direct inbox handling.

Assigning Permissions Gate:
  • Requires global_inbox permission to assign conversations freely to any registered worker.
  • If a staff member holds only assign_chat_to_self, they are strictly restricted to assigning conversations to themselves, and cannot reassign active rooms from other operators.
Body Parameter Type Required Description
contact_id integer Yes Database ID representing the conversation contact.
staff_id integer Yes Database User ID representing the employee assignee.

GET /chat/clear/{contact_id}

Clears the message records history for the designated contact profile.

Security Constraint:

Requires room control permissions. This endpoint enforces strict tenant isolation, preventing any cross-client history modification.

DELETE /chat/delete/{message_id}

Deletes a specific message instance permanently from the platform database.

Tenant Isolated:

Access is strictly guarded; users can only delete message records belonging directly to their own client tenant identity.

Granular API Response Mappings

  • type (Direction Key): Maps direct message directions. Value 2 signifies **Inbound** replies received from customers. Value 1 signifies **Outbound** payloads delivered by your team or AI system.
  • is_seen: Boolean state showing if the conversation was viewed.
  • header_document / header_image: Active URLs mapping to uploaded message media assets.
Get Room Messages
GET /api/message/12?type=media HTTP/1.1

Host: mazbot.net

apikey: YOUR_API_KEY_HERE

Authorization: Bearer YOUR_JWT_TOKEN_HERE

Accept: application/json
Chat Messages Response 200 OK
{

  "success": true,

  "message": "messages_retrieved_successfully",

  "data": {

    "messages": [

      {

        "date": "Today",

        "items": [

          {

            "id": 4825,

            "type": 2,

            "message": "Yes, please send the invoice",

            "header_document": null,

            "is_seen": 1,

            "status": "read",

            "created_at": "2026-06-12T12:05:00.000000Z"

          }

        ]

      }

    ],

    "user": {

      "id": 12,

      "receiver_id": 12,

      "name": "John Doe",

      "phone": "201012345678",

      "last_conversation_at": "2026-06-12T12:05:00.000000Z",

      "ai_reply_enabled": true

    },

    "can_not_reply": false,

    "next_page_url": false

  }

}

Media Requirements & FFmpeg

Ensure uploaded attachments fit within WhatsApp Cloud constraints. Files exceeding size or codec specifications fail cellular delivery.

Template Header Limits (POST /whatsapp/send-template)

Type Max Formats
image2 MBjpeg, png, jpg
document5 MBpdf
video10 MBmp4
audio5 MBmp3

WhatsApp Cloud (General)

Media Category Max Permitted Size Recommended Format Standards
Images 5 MB JPEG, PNG, JPG, WebP.
Documents 10 MB PDF (highly recommended), DOCX, XLSX, XLS.
Audio 16 MB MP3, AAC, OGG, AMR.
Videos 16 MB MP4 or 3GP only. Under strict 16MB file limit. Requires H.264 (Main or Baseline profile) video codec and AAC audio codec encoding.

VIDEO BLACK-SCREEN FIX

Issue: High-definition video attachments, HEVC/H.265 encoding, H.264 High Profile, or multiple audio streams will fail to play (displaying a black screen) or fail delivery on mobile devices.

Requirements:

  • Container Format: MP4 or 3GP container.
  • File Size Cap: Strict 16 MB maximum ceiling.
  • Video Stream: H.264 video codec encoded on Main or Baseline profiles. Avoid H.265/HEVC entirely.
  • Audio Stream: AAC audio codec (Single stream, stereo or mono).
  • Color Space: yuv420p chroma subsampling (8-bit depth).
FFmpeg Compression Commands
# Standard Recode (H.264 & AAC standard profile):
ffmpeg -i input.mp4 -c:v libx264 -profile:v main -level 3.1 -pix_fmt yuv420p -preset veryfast -crf 28 -c:a aac -b:a 128k -ac 2 -movflags +faststart output.mp4
# High Compression (Scale dimensions and cap bitrate):
ffmpeg -i input.mp4 -vf "scale='min(720,iw)':-2" -c:v libx264 -profile:v main -level 3.1 -pix_fmt yuv420p -b:v 900k -maxrate 1000k -bufsize 2000k -c:a aac -b:a 96k -ac 2 -movflags +faststart output_small.mp4

Postman Collection

Download the ready-made collection with every endpoint, including all send examples (text, image, document, template) and their success and error responses. It is generated from the same OpenAPI spec as the API Playground, so it always matches this page.

Download MazBot-API.postman_collection.json

Set up in 4 steps

  1. In Postman choose Import and select the downloaded .json file.
  2. Open the collection MazBot API, tab Variables, and put your API key in api_key (the Current value column). base_url is already https://mazbot.net/api.
  3. Run Authentication / User Login with your email and password. Its test script stores the token in jwt_token automatically.
  4. Run Messaging / Send Message or Send WhatsApp Template. Pick one of the saved examples, then press Send. The response shows meta_response.

Collection Variables

Variable Key Value / Configuration Used for
base_url https://mazbot.net/api Every request
api_key Your account API key (sent as the apikey header). Every request
jwt_token Filled automatically by the Login request. Bearer auth

Folders

  • Authentication: POST {{base_url}}/login and logout.
  • Messaging: Send Message (text, image, document), 24-hour window status, Send WhatsApp Template.
  • Chat Management, Contact Management and the rest: chat rooms, messages, contacts, AI toggle, tickets.

Prefer your browser? The API Playground lets you try the same requests without installing anything.

Postman Login Tests (Auto-Set Token) JavaScript Test Script
pm.collectionVariables.set("jwt_token", pm.response.json().data.token);

Developer FAQ & Coexistence

Review core operational architectural limitations to prevent synchronization bottlenecks.

Business Coexistence Mode

If your cellular line simultaneously operates active sessions inside both the WhatsApp Business Application and MazBot Dashboard:

  • Inbound Replies Routing: Cellular incoming messages are pushed directly and instantly to your physical WhatsApp mobile application device.
  • REST Database Latency: MazBot synchronizes message items programmatically, but Meta Graph replication limits might introduce a slight lag (1 to 3 seconds). Rely strictly on the Polling strategies checklist to fetch absolute states.

Interactive Developer FAQ

Integration Execution Checklist

  • H Base URL updates & Session token generation.
  • H REST message polling flows & deduplication checks.
  • M Template variable array indexes starting from 1.
  • M Video Recoding standards (FFmpeg).
  • L AI toggling routes & team owner permission gates.

Endpoint Index

Quick reference. Private routes need apikey + Authorization: Bearer. Rate limit: 60/min per user; login: 5/min per IP.

Method Path Auth Summary
POST/loginapikeyStaff JWT login
POST/logoutbothLogout
GET/profilebothUser profile
POST/profile-updatebothUpdate profile
GET/whatsapp-contactbothList contacts
POST/contact/resolve-by-phonebothResolve contact ID from phone
GET/whatsapp/window-statusboth24h window: can send-message be used now, until when
POST/send-messagebothSession message (receiver_id or mobile)
POST/whatsapp/send-locationbothNative location pin
POST/whatsapp/send-interactivebothButtons or list menu
POST/webhooks/emitbothEmit custom/business webhook
POST/whatsapp/send-templatebothTemplate message
GET/chat-roomsbothInbox list
GET/message/{contact_id}bothMessage history
POST/team-storebothAdd staff (owner only)
POST/ai/contact/toggle-auto-replybothToggle AI per contact
POST/flow-builder/triggerbothTrigger flow
POST/appointmentsbothCreate appointment
POST/contacts/{id}/capi-eventbothMeta CAPI event
GET/country/listapikeyCountries lookup

See Additional Endpoints for the full list including Telegram, segments, notes, tags, and Fawaterk.

Additional Endpoints Reference

The following endpoints are active and supported in the platform but not covered in the main guides above. All require dual-layer authentication (apikey + Authorization: Bearer token).

WhatsApp Enhanced

POST /whatsapp/send-location, POST /whatsapp/send-interactive, POST /webhooks/emit — see WhatsApp Integration.

POST /contact/resolve-by-phone

Resolve receiver_id from a phone number. Optional name and create (default true). See Contact Records.

GET /contacts-by-client

Returns a paginated list of active contacts with optional filters: type, assignee_id, q (search), tag_id, is_seen.

GET /contacts-details/{id}

Returns the full profile details of a contact by ID, including notes, tags, and Meta CAPI attribution events.

GET /staffs-by-client

Returns a list of all active staff members/employees for the authenticated client.

GET /whatsapp/get-template

Retrieve single template details. Pass template_id as a query parameter.

GET /whatsapp-templates

Returns all approved WhatsApp templates for the client.

GET /shared-files/{id}

Returns shared media/files for a contact ID. Optional query parameter type: media, files, links.

DELETE /delete-file/{id}

Permanently deletes a specific shared file by its message ID.

POST /send-forward-message

Forward an existing message to one or more contacts.

Auth & Profile

POST /logout, GET /profile, POST /profile-update, POST /forgot-password, POST /verify-otp, POST /reset-password (password reset routes: 10/min per IP).

Flow Builder

GET /flow-builder/list, POST /flow-builder/trigger

Appointments

POST /appointments, POST /appointments/{id}/reschedule, POST /appointments/{id}/cancel, GET /appointments/{id}, GET /conversations/{conversationId}/appointments

Meta CAPI

POST /contacts/{id}/capi-event — dispatch conversion event (throttled).

Payments (Fawaterk)

GET, POST /fawaterk/manual-verify — apikey only, no JWT.

Reference / Lookup Endpoints

These endpoints require only the apikey header (no JWT Bearer token needed):

Method Endpoint Description
GET /country/list Returns all supported countries (used with contact country_id).
GET /department/list Returns all support departments (used with ticket department_id).
GET /timezone/list Returns all available timezones for profile configuration.
GET /currency/list Returns all supported currencies.

send-template: Additional Fields

The following optional fields are supported on template dispatches:

Field Type Description
mobilestringPhone number (alternative to contact_id). Creates contact if not found.
body_valuesarrayCustom values for body placeholders.
body_matchsarrayMapping of keys to sources: input_value, contact_name, contact_phone.
button_valuesarrayCustom dynamic values for templates button URLs.
imagefileHeader image — max 2 MB (jpeg, png, jpg).
documentfileHeader PDF — max 5 MB.
videofile (mp4)Upload video header media (max 10MB).
audiofile (mp3)Upload audio header media (max 5MB).

System Changelog

Review the latest API engine modifications and layout upgrades.

v1.5.0 Stable Released: November 2026
  • New data.meta_response on POST /send-message and POST /whatsapp/send-template: WhatsApp's original response body, unchanged (null when WhatsApp was not called). Existing fields are unchanged.
  • POST /whatsapp/send-template now makes one attempt to send the template to WhatsApp during the request, so message.status is sent when WhatsApp accepted it. If WhatsApp is busy or unreachable, or a campaign of yours is sending at that moment, it stays scheduled and is retried automatically; the final result arrives through the message.failed / message.delivered webhooks. The call now waits for WhatsApp (usually under 2 seconds, up to about 60 seconds): set your HTTP client timeout to 65 seconds or more, and after a timeout check GET /message/{contact_id} before retrying.
  • Behaviour fix: a template that WhatsApp rejects (for example #132000, wrong number of parameters) now answers HTTP 422 with success: false, data.message_id and data.meta_response, and the conversation is refunded. Before, it answered HTTP 200 as "scheduled". Quota and subscription errors are unchanged (HTTP 200, success: false).
  • Behaviour fix: when WhatsApp rate-limits a session message (throughput limits such as 130429, 131048, 80007, or Meta's temporary 131000), POST /send-message now answers HTTP 503 with data.error_code: "meta_rate_limited", does not charge a conversation, and you retry later. Before, an image or document answered HTTP 200 "sent" and was never delivered.
  • A failed text send now returns data.message_id and data.meta_response (HTTP 500) when WhatsApp's reply was captured.
  • New API Playground: try every endpoint from your browser.
  • New downloadable Postman collection with all send examples, plus a new Meta error code table and curl / raw HTTP examples for text, media and template sends.
v1.4.0 Stable Released: November 15, 2026
  • POST /send-message to a WhatsApp contact outside the 24-hour window (72h after a Click-to-WhatsApp ad) now returns HTTP 422 with data.error_code: "outside_24h_window", before anything is sent or charged. Use POST /whatsapp/send-template for these contacts.
  • New GET /whatsapp/window-status: whether the 24-hour window is open, expires_at, seconds_remaining, last_inbound_at. The 422 above includes the same window object.
  • POST /send-message success response now includes message_id (same as send-template).
  • can_not_reply only counts messages from the customer: your own sends and templates no longer make it false.
  • New opt-in webhook events message.delivered, message.read, message.failed (including failures after WhatsApp accepted the message, e.g. 131047).
  • Messages in GET /message/{contact_id} include status (sent, delivered, read, failed, …).
  • POST /send-message with an image or document: message is now sent as the file's caption (it was dropped before).
  • If WhatsApp rejects an image or document immediately, send-message returns HTTP 500 with the error and data.message_id instead of a false success; the conversation is not charged.
  • Template PDF headers show the uploaded file's name to the customer instead of "Untitled".
v1.3.0 Stable Released: July 10, 2026
  • Added POST /whatsapp/send-location for native map pins.
  • Added POST /whatsapp/send-interactive for buttons and list menus.
  • Documented outbound webhooks (Settings → Webhook) and POST /webhooks/emit.
  • Expanded WhatsApp Integration guide: setup steps, webhook headers, reservation flow, related endpoints.
  • Updated polling docs: webhooks optional, polling as fallback.
v1.2.1 Stable Released: June 12, 2026
  • Fixed rate limit documentation: 60 req/min (authenticated API), 5/min login, 10/min password reset.
  • Corrected is_seen filter semantics (unread vs read).
  • Documented GET /message/{contact_id} real response shape and contact ID parameter.
  • Documented 24-hour window: use can_not_reply before session sends; 72h referral exception.
  • Fixed team-store: password_confirmation, minimum password 6 characters.
  • Separated API key errors: missing → 401, invalid → 403.
  • Removed duplicate/conflicting send-message success examples.
  • Updated template media limits (image 2 MB, document 5 MB, video 10 MB).
  • Added locale prefix guidance, endpoint index, common mistakes, and expanded additional endpoints.
  • Documented POST /send-message mobile and name fields for contact lookup/create.
  • Added POST /contact/resolve-by-phone endpoint reference.
  • Published Team Performance & QA Guide for client panel KPIs and conversation scoring.
v1.2.0 Stable Released: May 18, 2026
  • Unified base domain reference paths to `https://mazbot.net/api`, deprecating old `api.` subdomain routes.
  • Stabilized `POST /send-message` to upload documents and validate MIME types dynamically.
  • Enforced strict 16MB file limit validations on WhatsApp campaign video parameters.
  • Standardized localized template preview compilers to handle indexes starting at 1.
  • Created `/ai/contact/toggle-auto-reply` and `/ai/reply-priority` API routes.
v1.1.5 Beta Released: April 10, 2026
  • Upgraded JWT token expiration ceiling limits to 60 minutes.
  • Implemented standard validation response formats under `ApiReturnFormatTrait`.

Integration Complete!

You are fully prepared to orchestrate powerful CRM systems with MazBot! Connect with our developer assistance staff via [email protected] if you require real-time pipeline troubleshooting.