WhatsGate REST API v1

Developer Integration Guide

Connect your enterprise SaaS, CRM, e-commerce, or mobile app to WhatsApp in 3 simple steps.

1. Authentication

All requests to the WhatsGate REST API require Bearer token authorization using your active secret API key (starts with wsaas_live_...).

Authorization: Bearer wsaas_live_your_secret_key_here

2. 3-Step Integration Workflow

1

Generate API Key

Head to Dashboard > API Keys and click "Generate New API Key".

2

Pair WhatsApp Device

Scan QR in Dashboard > Devices. Note down your unique deviceId.

3

Dispatch Message

Send an HTTP POST request with your payload. Credits are deducted automatically.

3. Ready-to-Use Code Examples

app/Services/WhatsAppService.php
<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class WhatsAppService
{
    protected string $baseUrl;
    protected string $apiKey;
    protected string $defaultDeviceId;

    public function __construct()
    {
        $this->baseUrl = config('services.whatsgate.url', 'https://whatsgate.deskshala.in');
        $this->apiKey = config('services.whatsgate.api_key', 'wsaas_live_YOUR_API_KEY');
        $this->defaultDeviceId = config('services.whatsgate.device_id', 'dev_corporate_alpha');
    }

    /**
     * Connect a new WhatsApp device from your CRM (returns QR Base64 & Pairing Code)
     */
    public function connectDevice(string $deviceName, ?string $webhookUrl = null): array
    {
        return Http::withToken($this->apiKey)
            ->post("{$this->baseUrl}/api/v1/devices", [
                'name'       => $deviceName,
                'webhookUrl' => $webhookUrl
            ])->json();
    }

    /**
     * Disconnect / Log out a WhatsApp device session
     */
    public function disconnectDevice(string $deviceId): array
    {
        return Http::withToken($this->apiKey)
            ->post("{$this->baseUrl}/api/v1/devices/{$deviceId}/disconnect")
            ->json();
    }

    /**
     * Send a single direct WhatsApp message via anti-ban queue
     */
    public function sendMessage(string $recipientPhone, string $text, ?string $deviceId = null): array
    {
        $response = Http::withToken($this->apiKey)
            ->timeout(15)
            ->post("{$this->baseUrl}/api/v1/messages/send", [
                'deviceId'  => $deviceId ?? $this->defaultDeviceId,
                'recipient' => preg_replace('/\D/', '', $recipientPhone),
                'message'   => $text,
                'antiBan'   => true, // Enforces 4-12s randomized human jitter
            ]);

        if ($response->failed()) {
            Log::error('WhatsApp Dispatch Failed', ['body' => $response->json()]);
            throw new \Exception($response->json('error') ?? 'Failed to send WhatsApp message');
        }

        return $response->json();
    }

    /**
     * Send parameterized template (e.g., Invoice & Payment Reminder)
     */
    public function sendInvoiceReminder(string $phone, string $customerName, string $amount, string $dueDate): array
    {
        return Http::withToken($this->apiKey)
            ->post("{$this->baseUrl}/api/v1/messages/send-template", [
                'deviceId'   => $this->defaultDeviceId,
                'recipient'  => preg_replace('/\D/', '', $phone),
                'templateId' => 'tmpl_invoice_reminder',
                'variables'  => [
                    'customerName' => $customerName,
                    'amount'       => $amount,
                    'dueDate'      => $dueDate,
                ],
                'antiBan'    => true
            ])->json();
    }
}
GET/api/v1/devices

Retrieves all WhatsApp devices paired under your account, including their unique id, phone number, and connection state.

Response (200 OK)
{
  "success": true,
  "availableCredits": 5000,
  "devices": [
    {
      "id": "dev_corporate_alpha",
      "name": "Corporate Dispatch Gateway",
      "phone": "919876543210",
      "status": "CONNECTED",
      "webhookUrl": "https://crm.example.com/webhook",
      "createdAt": "2026-09-13T12:00:00.000Z"
    }
  ]
}
POST/api/v1/devicesConnect Device (QR / Pairing Code)

Initializes and provisions a new WhatsApp device directly from your external CRM or backend. Supports both QR Code Scan and Mobile Phone Pairing Code. If your CRM operates without camera access, provide your user's phone number with "method": "pairing_code" to immediately receive an 8-character pairing code.

Request Body (Phone Pairing Code - Recommended for CRM)
Payload
{
  "name": "CRM Sales Line 1",
  "method": "pairing_code",
  "phone": "919876543210",
  "webhookUrl": "https://your-crm.com/api/whatsapp-webhook"
}
Success Response (200 OK)
Response
{
  "success": true,
  "message": "Device initialized with phone pairing code. In WhatsApp, tap \"Link with phone number instead\" and enter the 8-digit pairing code.",
  "device": {
    "id": "dev_8f910a2b",
    "name": "CRM Sales Line 1",
    "phone": "919876543210",
    "status": "DISCONNECTED",
    "webhookUrl": "https://your-crm.com/api/whatsapp-webhook",
    "createdAt": "2026-09-21T12:00:00.000Z"
  },
  "connection": {
    "method": "pairing_code",
    "pairingCode": "CW4L-Z8H3",
    "base64": "data:image/png;base64,iVBORw0KGgo...",
    "code": "2@410a8c...",
    "instructions": "Open WhatsApp on your phone > Linked Devices > Link a Device > Tap \"Link with phone number instead\" > Enter this 8-digit code"
  }
}
POST/api/v1/devices/:id/pairingGenerate Pairing Code

Requests or refreshes an 8-character phone pairing code for an existing device. Useful when a user switches from QR code to pairing code inside your CRM, or if the pairing code timed out.

Request Body (JSON)
Payload
{
  "phone": "919876543210"
}
Success Response (200 OK)
Response
{
  "success": true,
  "deviceId": "dev_8f910a2b",
  "deviceName": "CRM Sales Line 1",
  "phone": "919876543210",
  "pairingCode": "CW4L-Z8H3",
  "code": "2@410a8c...",
  "base64": "data:image/png;base64,iVBORw0KGgo...",
  "instructions": "Open WhatsApp on your phone > Linked Devices > Link a Device > Tap \"Link with phone number instead\" at the bottom > Enter this 8-digit code"
}
GET/api/v1/devices/:id/qr

Retrieves the latest fresh QR code (in raw base64 and scan string) or pairing code for a specific device. You can also append ?phone=919876543210 to simultaneously request an 8-character mobile pairing code.

Response (200 OK)
{
  "success": true,
  "deviceId": "dev_8f910a2b",
  "deviceName": "CRM Support Desk 1",
  "status": "CONNECTING",
  "base64": "data:image/png;base64,iVBORw0KGgo...",
  "pairingCode": "CW4L-Z8H3",
  "code": "2@410a8c..."
}
GET/api/v1/devices/:id/status

Queries the live socket connection status directly from the WhatsApp server (CONNECTED, CONNECTING, or DISCONNECTED). Useful for CRM polling after displaying the QR code.

Response (200 OK)
{
  "success": true,
  "deviceId": "dev_8f910a2b",
  "name": "CRM Support Desk 1",
  "status": "CONNECTED",
  "connected": true
}
POST/api/v1/devices/:id/disconnectDisconnect Device

Disconnects and logs out a WhatsApp device session directly from your external CRM. Terminates the active connection and marks the device as disconnected.

Response (200 OK)
{
  "success": true,
  "message": "Device disconnected successfully from WhatsApp",
  "deviceId": "dev_8f910a2b",
  "status": "DISCONNECTED"
}
POST/api/v1/messages/send

Dispatches a raw text message. Automatically verifies and deducts 1 credit from your available balance.

Request Body (JSON)
Payload
{
  "deviceId": "dev_corporate_alpha",
  "recipient": "919876543210",
  "message": "Hello Alex, your monthly invoice #1042 is due.",
  "antiBan": true
}
Success Response (200 OK)
Response
{
  "success": true,
  "messageId": "msg_89f1a0b3c2",
  "status": "SENT",
  "creditsRemaining": 1999
}
POST/api/v1/messages/send-template

Sends a personalized message using your pre-configured templates (e.g. Login OTP, Sign-up, Invoice Reminder). Dynamic tags formatted as {{key}} are automatically replaced with your variables.

Request Body (JSON)
Payload
{
  "deviceId": "dev_corporate_alpha",
  "recipient": "919876543210",
  "templateId": "tmpl_otp_verification",
  "variables": {
    "customer_name": "Alex Rivera",
    "company_name": "WhatsGate",
    "otp_code": "849201",
    "valid_mins": "10"
  }
}
Success Response (200 OK)
Response
{
  "success": true,
  "messageId": "msg_3901bca72e",
  "status": "SENT",
  "renderedTemplate": "Hi Alex Rivera,\n\nYour verification code for *WhatsGate* is:\n*849201*\n\n⏱️ This OTP is valid for *10 minutes*.\n⚠️ Please do not share this code with anyone."
}

5. Chatbots & Automations API

Interactive AI / Rule Engine

Build 24/7 intelligent automated responders for incoming WhatsApp messages. Supports Keyword Matching (Exact / Contains / Starts With), First-time Welcome Greetings, After-Hours / Away Responders, and Dynamic CRM Webhook Relay for real-time live database queries (e.g. Student Fees, Exam Result, Seat Availability).

GET/api/v1/automations?deviceId=dev_xyz (optional)

Retrieves all automation rules configured under your account. Filter by deviceId to fetch rules bound to a specific WhatsApp instance.

Response (200 OK)
{
  "success": true,
  "count": 1,
  "automations": [
    {
      "id": "rule_fee_bot_01",
      "name": "Student Fees Query Relay",
      "triggerType": "KEYWORD",
      "keywords": "fee, fees, dues, balance",
      "matchType": "CONTAINS",
      "responseType": "WEBHOOK_RELAY",
      "webhookUrl": "https://crm.example.com/api/v1/webhooks/whatsapp-bot",
      "isActive": true,
      "hitCount": 142,
      "lastTriggeredAt": "2026-09-25T14:30:00.000Z"
    }
  ]
}
POST/api/v1/automations

Creates a new auto-reply rule programmatically from your CRM or dashboard.

Request Body (JSON)
Payload
{
  "name": "Student Fees Inquiry",
  "deviceId": "dev_corporate_alpha", // Optional (omitted applies to all devices)
  "triggerType": "KEYWORD",          // KEYWORD | WELCOME | AWAY
  "keywords": "fees, pending, dues", // Required for KEYWORD
  "matchType": "CONTAINS",           // EXACT | CONTAINS | STARTS_WITH
  "responseType": "WEBHOOK_RELAY",   // TEXT | TEMPLATE | WEBHOOK_RELAY
  "webhookUrl": "https://crm.example.com/api/v1/webhooks/whatsapp-bot"
}
Success Response (201 Created)
Response
{
  "success": true,
  "message": "Automation rule created successfully",
  "automation": {
    "id": "rule_cm123abc456",
    "name": "Student Fees Inquiry",
    "triggerType": "KEYWORD",
    "isActive": true,
    "createdAt": "2026-09-25T14:35:00.000Z"
  }
}
PATCH/api/v1/automations/:id

Toggle isActive: false or update keywords and responses.

// Body:
{
  "isActive": false,
  "replyText": "Updated holiday message..."
}
DELETE/api/v1/automations/:id

Permanently delete an automation rule.

// Response (200 OK):
{
  "success": true,
  "message": "Automation rule deleted successfully"
}
How Dynamic CRM Webhook Relay Works (Real-time Live DB Lookups)

When WEBHOOK_RELAY is selected, WhatsGate doesn't just send a canned text. Instead, it securely forwards the incoming WhatsApp message to your CRM endpoint via HTTP POST:

1. WhatsGate sends to your CRM:
{
  "event": "automation.inbound",
  "deviceId": "dev_corporate_alpha",
  "deviceName": "Lakshya Study Library #1",
  "sender": "919876543210",
  "message": "MY FEES",
  "timestamp": 1789305000000
}
2. Your CRM replies within 8s:
{
  "reply": "Hi Rahul! Your pending fee for Seat #14 is *₹500*. Due date: *30 Sep 2026*."
}
*WhatsGate immediately sends this message to the student on WhatsApp!

6. Real-time Delivery Webhooks

Configure your webhook callback URL in Dashboard > API Keys to receive real-time notifications for delivery ticks and incoming customer replies.

Webhook Payload Event
{
  "event": "message.status",
  "messageId": "msg_89f1a0b3c2",
  "remoteJid": "919876543210@s.whatsapp.net",
  "status": "DELIVERED", // QUEUED | SENT | DELIVERED | READ | FAILED
  "timestamp": 1789305000000
}