REST API v1.0 Single API Key Meta Cloud Drop-In Compatible

API Documentation & Integration Guide

Integrate your applications with WhatsGateway to programmatically send WhatsApp messages, broadcast rich media, receive verified delivery receipts via HMAC webhooks, and automate conversational responses — with zero per-message markup.

1. Overview & Key Capabilities

WhatsGateway provides a developer-friendly HTTP interface layered on top of the open-source Baileys library and PHP 8.2 backend. Unlike commercial cloud brokers that charge $0.05 to $0.15+ per message conversation, WhatsGateway is completely self-hosted with zero licensing or subscription fees.

1

Dual Format Compatibility

Accepts clean flat JSON or official Meta WhatsApp Cloud API payloads without changing existing application code.

2

Persistent Queue Buffer

Incoming API requests are immediately acknowledged with an HTTP 200 response and buffered into MySQL/TiDB for reliable asynchronous dispatch.

3

HMAC-Signed Webhooks

Outbound webhooks sign every status event using HMAC-SHA256 so your receivers can verify cryptographic authenticity.

2. System Architecture Flow

The platform decouples HTTP message ingestion from the WebSocket connection to guarantee sub-millisecond response times and eliminate network timeouts:

# Ingestion to Delivery Pipeline:
1. Your App (cURL / Python / SDK) → POST /api/send.php (Authenticated with X-API-Key)
2. PHP Gateway → Validates schema, checks rate limits, enqueues record → Returns 200 OK & {message_id, status: "queued"}
3. Node.js Worker → Claims pending messages from queue → Transmits 'composing' presence to WhatsApp
4. Baileys Engine → Dispatches payload across WhatsApp Web Noise-encrypted socket
5. Handset → Renders message to recipient → Acknowledges delivery receipt
6. Webhook Worker → Dispatches HMAC-SHA256 signed event (message.delivered) to your URL

3. Base URLs & Environments

All API endpoints are relative to your deployment's base URL. Replace the host below with your own private domain or local server address:

Environment Base URL Primary Endpoints
Local (XAMPP / Dev) http://localhost/whatsapp-api/public/ api/send.php
Production / VPS https://your-domain.com/ api/send.php, api/messages.php

4. Authentication & Single API Key

Every API request requires an active API Key generated from your dashboard under API Keys. We support two standard header formats interchangeably:

# Option 1: Dedicated Custom Header (Standard)
X-API-Key: wa_live_3f98c21a48e7...

# Option 2: Bearer Authorization Header (Meta Cloud API style)
Authorization: Bearer wa_live_3f98c21a48e7...
Zero Plaintext Storage: API keys are hashed with modern cryptographic SHA-256 before storage in the database. The secret token is shown only once at generation time.

5. Rate Limits & Burst Policies

Rate limits can be customized per API key directly in your dashboard (default: 60 requests per minute). If a client exceeds the threshold, the gateway responds with HTTP 429:

{
  "ok": false,
  "error": "Rate limit exceeded.",
  "request_id": "req_6718a209b...",
  "rate": {
    "allowed": false,
    "limit": 60,
    "current": 61,
    "remaining": 0,
    "reset_in_seconds": 45
  },
  "meta_error": {
    "message": "Rate limit hit.",
    "type": "OAuthException",
    "code": 80007
  }
}
POST /api/send.php

Send Message (Clean REST Format)

Dispatches a text message, document, image, audio, or video file to any international WhatsApp recipient.

Field Type Requirement Description
to string Required Recipient's full phone number with country code (e.g., 919876543210, +15551234567). Spaces and special characters are stripped automatically.
message string Conditional The message copy or media caption. Optional if a media URL/file is provided. Supports native WhatsApp markdown (*bold*, _italic_, ~strike~, ```mono```).
media_url string (URL) Optional Direct public HTTPS link to an image (JPG, PNG, WEBP), document (PDF, DOCX), video (MP4), or audio (MP3, OGG). Downloaded with SSRF protections. Max 20MB.
media_base64 string (Base64) Optional Direct Base64 data string (e.g., data:image/png;base64,...) or raw base64 data.
type string Optional text, image, document, video, or audio. Auto-detected from attachment MIME type if omitted.
filename string Optional Custom filename presented to the recipient in WhatsApp for document attachments (e.g., Monthly-Invoice-Oct2026.pdf).
humanize boolean Optional Defaults to true. Adds human typing indicators (sendPresenceUpdate('composing')) and paces delivery queue to prevent spam bans.
ptt boolean Optional Send audio attachments as a playable voice note (Push-to-Talk waveform) instead of a standard audio file.
campaign_id integer Optional Attach the message to an existing marketing or notification campaign for aggregated dashboard metrics.
Request Body (JSON)
{
  "to": "919876543210",
  "message": "Hello from WhatsGateway! ๐Ÿš€\nYour order *#84920* is confirmed.",
  "humanize": true
}
Response (HTTP 200 OK)
{
  "ok": true,
  "status": "queued",
  "message_id": 142,
  "request_id": "req_6718a9ef38...",
  "recipient": "919876543210",
  "type": "text",
  "has_media": false,
  "messaging_product": "whatsapp",
  "contacts": [
    {
      "input": "919876543210",
      "wa_id": "919876543210"
    }
  ],
  "messages": [
    {
      "id": "wamid.b29f430ca0489...",
      "message_status": "accepted"
    }
  ]
}
POST /api/messages.php

Meta WhatsApp Cloud API (Drop-In Compatibility)

If your existing codebase was built for the official Meta WhatsApp Cloud API (Graph API v17+), you can point your HTTP client directly at WhatsGateway without altering your request payload structure.

# Meta Cloud API Drop-In Request:
curl -X POST "https://whatsapp-api-xepo.onrender.com/api/messages.php" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_API_KEY_HERE" \ -d '{ "messaging_product": "whatsapp", "recipient_type": "individual", "to": "919876543210", "type": "text", "text": { "preview_url": false, "body": "Hello via Meta Cloud API format! ๐ŸŒ" } }'
Supported Meta Types: text, image, document, video, audio, and template. Parameter components in templates are automatically concatenated into the final message body.

8. Media & Binary File Uploads

WhatsGateway supports three methods for sending attachments up to 20MB:

Method A: Remote Public HTTPS URL

The server downloads the file from the provided URL, validates MIME boundaries, and dispatches it over WhatsApp.

curl -X POST "https://whatsapp-api-xepo.onrender.com/api/send.php" \
  -H "Content-Type: application/json" \
  -H "X-API-Key: YOUR_API_KEY_HERE" \
  -d '{
    "to": "919876543210",
    "type": "image",
    "media_url": "https://images.unsplash.com/photo-1579202673506-ca3ce28943ef?w=800",
    "caption": "Photo dispatch verified! ๐Ÿ“ธ"
  }'

Method B: Direct File Upload from Terminal (Multipart/form-data)

Ideal for local PDF invoices, documents, and spreadsheets without needing a separate CDN upload step.

curl -X POST "https://whatsapp-api-xepo.onrender.com/api/send.php" \
  -H "X-API-Key: YOUR_API_KEY_HERE" \
  -F "to=919876543210" \
  -F "file=@/path/to/invoice-84920.pdf" \
  -F "caption=Attached is your monthly billing statement."

Method C: In-Memory Base64 Data URI

Send dynamically generated charts or receipts directly from memory.

curl -X POST "https://whatsapp-api-xepo.onrender.com/api/send.php" \
  -H "Content-Type: application/json" \
  -H "X-API-Key: YOUR_API_KEY_HERE" \
  -d '{
    "to": "919876543210",
    "media_base64": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==",
    "filename": "pixel.png",
    "caption": "Rendered via Base64"
  }'

9. Voice Notes & Push-to-Talk (PTT)

By default, audio files are delivered as standard media players. To render audio as an authentic WhatsApp voice message with waveform playback, pass "ptt": true:

curl -X POST "https://whatsapp-api-xepo.onrender.com/api/send.php" \
  -H "Content-Type: application/json" \
  -H "X-API-Key: YOUR_API_KEY_HERE" \
  -d '{
    "to": "919876543210",
    "type": "audio",
    "media_url": "https://example.com/audio/voice-memo.ogg",
    "ptt": true
  }'
GET /api/health.php

Gateway & Worker Health Check

Monitor uptime and connectivity for automated uptime pings (UptimeRobot, Datadog, Prometheus):

curl -X GET "https://whatsapp-api-xepo.onrender.com/api/health.php"
{
  "ok": true,
  "status": "healthy",
  "timestamp": "2026-10-23T15:10:00+05:30",
  "service": "whatsgateway",
  "worker": {
    "ok": true,
    "status_code": 200,
    "service": "baileys-worker"
  }
}

11. Anti-Ban Architecture & Humanize Delays

WhatsApp monitors sudden high-frequency bursts of unsolicited traffic. WhatsGateway embeds multiple safeguards to keep your linked numbers healthy:

Built-in Anti-Ban Safeguards
  • Human Typing Presence: Passing "humanize": true triggers a realistic typing presence update (sendPresenceUpdate('composing')) before payload transmission.
  • Configurable Pacing Delay: Managed by SEND_DELAY_MS in your .env (defaults to 2500ms between consecutive dispatches).
  • Consented Communication Only: Send notifications, verification OTPs, and receipts strictly to customers who have given prior verifiable opt-in consent.

12. Webhooks & Real-Time Delivery Notifications

Configure your HTTPS webhook endpoint in the Dashboard under Webhooks. Whenever a message transitions states or your phone link updates, WhatsGateway executes an asynchronous HTTP POST callback:

Cryptographic HMAC-SHA256 Signature Verification

Every webhook request includes an X-Hub-Signature-256 header computed using your private webhook secret:

Verification in Node.js (Express / Fastify):
const crypto = require('crypto');

function verifyWebhook(rawBody, signatureHeader, secret) {
    const expected = 'sha256=' + crypto.createHmac('sha256', secret).update(rawBody).digest('hex');
    return crypto.timingSafeEqual(Buffer.from(signatureHeader), Buffer.from(expected));
}
Verification in Python (Flask / FastAPI):
import hmac, hashlib

def verify_webhook(raw_body_bytes, signature_header, secret_key):
    expected = "sha256=" + hmac.new(secret_key.encode(), raw_body_bytes, hashlib.sha256).hexdigest()
    return hmac.compare_digest(signature_header, expected)

Event Payloads

Event: message.delivered
{
  "event": "message.delivered",
  "message_id": 142,
  "to": "919876543210",
  "status": "delivered",
  "timestamp": "2026-10-23T15:12:00Z"
}
Event: message.read
{
  "event": "message.read",
  "message_id": 142,
  "to": "919876543210",
  "status": "read",
  "timestamp": "2026-10-23T15:12:05Z"
}

13. Google Contacts Integration & Limited Use

WhatsGateway supports one-click address book synchronization powered by Google People API OAuth 2.0 PKCE:

Strict Limited Use Disclosure

WhatsGatewayโ€™s use and transfer to any other app of information received from Google APIs adheres to the Google API Services User Data Policy, including the Limited Use requirements.

  • Read-Only Scope: Uses only contacts.readonly to import opted-in phone numbers.
  • Zero Third-Party Sharing: Synced contact records are stored locally and never sold to advertisers or data brokers.

14. Multi-Language Quickstart Code

Production-grade implementations in popular programming languages:

curl -X POST "https://whatsapp-api-xepo.onrender.com/api/send.php" \
  -H "Content-Type: application/json" \
  -H "X-API-Key: wa_live_YOUR_API_KEY_HERE" \
  -d '{
    "to": "919876543210",
    "message": "Hello from WhatsGateway! ๐Ÿš€\nYour order *#84920* has been shipped.",
    "humanize": true
  }'

15. Interactive Terminal CLI Tool

Send messages directly from your developer terminal without writing code using our included interactive Python CLI tool:

# Run directly from repository root:
python send_whatsapp.py
# Prompts interactively for API Key, Recipient Number, Message text, and optional media link.

16. HTTP Status Codes & Error Dictionary

All HTTP error responses return a standardized JSON envelope with both generic and Meta-compatible error structures:

Status Code Error Cause Meta Code Recommended Solution
200 OK Message Accepted & Queued — Payload validated; buffered into persistent queue for delivery.
401 Unauthorized Invalid or Missing API Key 190 Verify that your X-API-Key or Bearer token is active in the Dashboard.
403 Forbidden IP Not Whitelisted — Your API Key has an IP restriction enabled that does not match your caller IP address.
405 Method Not Allowed Non-POST Request Used — Dispatch requests using HTTP POST.
422 Unprocessable Missing Required Fields 100 Ensure recipient (to) and either message or media attachment are present.
429 Too Many Requests Rate Limit Exceeded 80007 Pace your requests or increase your API Key rate limit quota in the dashboard.

Legal Notices & MIT License

WhatsGateway is an independent open-source project maintained by Navneet Kumar Yadav and released under the permissive MIT License.

This project is not affiliated, endorsed, sponsored, or certified by Meta Platforms, Inc., WhatsApp Inc., or Google LLC. "WhatsApp" is a registered trademark of Meta Platforms, Inc. "Google" is a registered trademark of Google LLC.