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 are no Subdomain prefixes or trailing v1 identifiers in active operations:
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.
- Store the generated **JWT Token** and handle automatic re-authentication when expired.
Quick Start Guide
Connect your codebase to MazBot in under 3 minutes following these three simple milestones:
-
1
Acquire API Credentials
Log in to the Client Panel and navigate to your user Profile to generate your secure, case-insensitive `apikey`.
-
2
Obtain Session JWT
Submit your login credentials alongside your `apikey` to generate an access Bearer Token.
-
3
Fire a WhatsApp Message
Call `POST /whatsapp/send-template` with your template details or `POST /send-message` for direct chats.
# 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"
}'
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`).
Layer 2: JWT Bearer Token
Generated dynamically by standard logins. Must be supplied as a `Authorization: Bearer
Token Lifespans & Expirations
- JWT Lifespan: Valid for exactly 60 minutes (1 hour).
- Refresh Token: Not supported. Upon expiration (resulting in HTTP `401 Unauthorized`), client systems must issue a new login call.
POST /login
Exchange platform credentials and a valid `apikey` for a session JWT.
| Parameter | Type | Requirement | Description |
|---|---|---|---|
| string | Required | Your registered MazBot account email. | |
| password | string | Required | Your primary MazBot account password. |
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": true,
"message": "Login successfully",
"data": {
"id": 5,
"name": "Migo Developer",
"role_id": 2,
"client_id": 1,
"phone": "201012345678",
"email": "[email protected]",
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
}
Rate Limiting & Error Management
MazBot implements rigorous traffic throttling thresholds on all router profiles to maintain high system availability.
Rate Throttling Details
- Limit Ceiling: Strictly throttled to **60 requests per minute** per resource.
- Tracking Key: Checked against the **User ID** for authorized calls. Non-authorized endpoints (like login) tracking matches the client's **IP Address**.
- HTTP Response: Exceeding this boundary raises a `429 Too Many Requests` block.
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 | Expired, invalid, or missing JWT Bearer Token in `Authorization` header. |
| 403 | Forbidden | Missing/invalid `apikey` header, or insufficient privileges (e.g. staff managing roster). |
| 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. |
{
"success": false,
"message": "Validation failed",
"data": {
"receiver_id": [
"The receiver id field is required."
]
}
}
{
"success": false,
"message": "Invalid reply message ID.",
"data": []
}
{
"success": false,
"message": "Token is expired",
"data": []
}
{
"success": false,
"message": "Unauthorized access",
"data": []
}
{
"success": false,
"message": "Contact not found",
"data": []
}
{
"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 room sync endpoints.
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:
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
Send Session (Normal) Message
Utilize this endpoint to send text or media documents directly to open chat sessions. This works dynamically outside of meta templates, provided a 24-hour customer service window is currently active.
24-HOUR CUSTOMER SERVICE WINDOW
Session messages (normal messages) can only be sent if the customer has initiated a chat or replied within the last 24 hours. If this window has expired, the server will block the request and return an HTTP 422 Unprocessable status. To resume messaging outside this window, you must initiate communication using a pre-approved template via the /whatsapp/send-template endpoint.
POST /send-message
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 | Yes | The integer ID of the contact in the database (`contacts.id`). |
| message | string | Optional* | Text string body. Required if image or document parameters are missing. |
| 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). |
Media Storage & Delivery Pipeline
- Binary Validation: The backend intercepts the multipart parameter and validates the file's MIME type extension.
- Storage Upload: The file is written to our local media directories or wasabi cloud space to generate a permanent static URL.
- Meta API Forwarding: The public asset URL is structured inside a dynamic message payload and pushed directly to Meta API servers for cellular delivery.
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--
{
"success": true,
"message": "Created successfully",
"data": ""
}
Send Template Message
Pushes registered Meta WhatsApp templates directly to targets. Supports rich media headers (images, documents, videos) and complex variable binding arrays.
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
| 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:
|
| body_values | array | No | The raw string parameters to map when using `input_value` matches. |
| document | file (binary) | No | Attach a binary PDF if your template header requires media. |
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="document"; filename="report.pdf"
Content-Type: application/pdf
[BINARY_PDF_DATA]
--boundary555--
{
"success": true,
"message": "Created successfully",
"data": {
"message_id": "ABEGkYZI4pQIDAgASkQw",
"status": "sent"
}
}
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). |
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
}
{
"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. |
| string | Yes | Unique workplace email address. | |
| password | string | Yes | Secure credential password (minimum 8 chars). |
| phone | string | No | Clean telephone number. |
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",
"phone": "201012345678"
}
{
"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 /contacts?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 /contacts
Query all system contacts with a standard 10-item limit pagination buffer.
POST /contacts
Create a new customer profile. Requires `phone` and `name` strings.
POST /block/{id}
Block/unblock the designated record identifier to intercept inbound traffic handlers.
{
"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/contacts?page=2",
"path": "https://mazbot.net/api/contacts"
}
}
}
Incoming Messages & Polling Flow
MazBot receives WhatsApp messages in real time inside the MazBot dashboard and mobile app using persistent WebSockets.
For external systems, incoming messages can currently be synchronized using the REST API by polling:
- Get Chat Rooms List:
GET /api/chat-rooms - Get Chat Room Messages:
GET /api/message/{chat_room_id}
NO EXTERNAL WEBHOOKS SUPPORTED
External real-time Webhooks for forwarding incoming WhatsApp messages to external URLs are not currently supported in our public API schema. Outgoing traffic is handled exclusively via WebSockets inside the official client apps.
To sync responses securely into external CRMs or dashboards, you must execute the recommended REST Polling strategy below.
Recommended Polling Architecture
- Pull Activity: Call `GET /chat-rooms` periodically.
-
Scan Timestamps: Compare the returned room
updated_attimestamp against your local stored variables. - Fetch Room Logs: If a room's timestamp indicates new traffic, trigger `GET /message/{chat_room_id}` to retrieve its full transcript.
-
Deduplicate & Write: Verify incoming values against your database by performing unique indices matches on the message
idparameter to filter out redundant records before writing.
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
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 | No | Filter seen (`1`) or unread (`0`) instances. |
GET /api/chat-rooms?type=whatsapp&is_seen=0 HTTP/1.1
Host: mazbot.net
apikey: YOUR_API_KEY_HERE
Authorization: Bearer YOUR_JWT_TOKEN_HERE
Accept: application/json
{
"success": true,
"message": "Chat retrieved successfully",
"data": {
"chat_rooms": [
{
"id": 12,
"name": "John Doe",
"phone": "201012345678",
"last_message": "Hello there",
"updated_at": "2026-05-18T12:00:00.000000Z"
}
],
"total_unread_messages": 3,
"next_page_url": "https://mazbot.net/api/chat-rooms?page=2"
}
}
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 /message/{chat_room_id}
Queries the transcripts inside a targeted conversation room. Returns standard message payloads.
| Query Parameter | Type | Required | Description |
|---|---|---|---|
| type | string | No |
Filters log records by attachment category. Accepts:
|
POST /assign-staff
Assigns a targeted chat room to a specific employee for direct inbox handling.
- Requires
global_inboxpermission 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.
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.
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
2signifies **Inbound** replies received from customers. Value1signifies **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 /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
{
"success": true,
"message": "Chat retrieved successfully",
"data": [
{
"id": 4825,
"type": 2,
"message": "Yes, please send the invoice pdf",
"header_document": null,
"is_seen": 1,
"created_at": "2026-05-18T12:05:00.000000Z"
},
{
"id": 4826,
"type": 1,
"message": "Here is your requested document",
"header_document": "https://mazbot.net/public/storage/media/invoice_4826.pdf",
"is_seen": 1,
"created_at": "2026-05-18T12:05:32.000000Z"
}
]
}
Media Requirements & FFmpeg
Ensure uploaded attachments fit within WhatsApp Cloud constraints. Files exceeding size or codec specifications fail cellular delivery.
Strict Media File Limits
| 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
MainorBaselineprofiles. Avoid H.265/HEVC entirely. - Audio Stream: AAC audio codec (Single stream, stereo or mono).
- Color Space:
yuv420pchroma subsampling (8-bit depth).
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
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 Sandbox Configuration
Import environment presets directly into Postman to expedite request testing without custom coding layers.
Required Environment Keys
| Variable Key | Value / Configuration | Scope |
|---|---|---|
| base_url | https://mazbot.net/api |
Global |
| api_key | Supply your verified account dashboard API Key. | Global / Login |
| jwt_token | Populated automatically via `/login` response hooks. | Bearer Auth |
Pre-Request Folder Hierarchy
- Authentication: holds `POST {{base_url}}/login` (Headers: `apikey: {{api_key}}`)
- WhatsApp Messages: holds templates and normal direct message dispatches.
- Chat Logs Polling: holds chat rooms listings and chat message queries.
// Automatically extract and assign JWT on successful login
const response = pm.response.json();
if (response.success && response.data.token) {
pm.environment.set("jwt_token", response.data.token);
console.log("JWT Session token updated successfully!");
}
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.
System Changelog
Review the latest API engine modifications and layout upgrades.
- 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.
- 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.