WhatsGate REST API v1

Developer Integration Guide

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

API Base URL

Production Environment

All REST API endpoints are relative to your current instance root URL. Use this base URL when dispatching HTTP requests:

BASE_URL:https://whatsgate.deskshala.in

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();
    }

    /**
     * Bulk Import Leads & Audience Groups with auto phone formatting
     */
    public function importContacts(array $contacts, ?string $groupId = null, ?string $newGroupName = null): array
    {
        return Http::withToken($this->apiKey)
            ->post("{$this->baseUrl}/api/v1/contacts/import", [
                'contacts'       => $contacts,
                'groupId'        => $groupId,
                'newGroupName'   => $newGroupName,
                'updateExisting' => true
            ])->json();
    }

    /**
     * Create and launch a Broadcast Marketing Campaign with dynamic tags & jitter
     */
    public function createCampaign(string $name, string $message, ?string $groupId = null, array $recipients = [], ?string $mediaUrl = null): array
    {
        return Http::withToken($this->apiKey)
            ->post("{$this->baseUrl}/api/v1/campaigns", [
                'name'       => $name,
                'deviceId'   => $this->defaultDeviceId,
                'message'    => $message,
                'groupId'    => $groupId,
                'recipients' => $recipients,
                'mediaUrl'   => $mediaUrl,
                'minDelayMs' => 4000,
                'maxDelayMs' => 12000,
            ])->json();
    }

    /**
     * Get Real-time Campaign Live Progress & Audit Breakdown
     */
    public function getCampaignProgress(string $campaignId): array
    {
        return Http::withToken($this->apiKey)
            ->get("{$this->baseUrl}/api/v1/campaigns/{$campaignId}")
            ->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"
}
GET/api/v1/devices/:id/groupsWhatsApp Groups & Communities

Retrieves all WhatsApp Groups, Community Announcement channels, and Channels associated with the connected phone session. Returns group JIDs (...@g.us), subject names, and participant counts.

Response (200 OK)
{
  "success": true,
  "deviceId": "dev_corporate_alpha",
  "deviceName": "Delhi Support Desk",
  "totalGroups": 2,
  "groups": [
    {
      "id": "120363041234567890@g.us",
      "subject": "Class 10 - Batch 2026",
      "size": 184,
      "isCommunity": false,
      "isCommunityAnnounce": false
    },
    {
      "id": "120363098765432100@g.us",
      "subject": "Lakshya Study Announcements",
      "size": 850,
      "isCommunity": false,
      "isCommunityAnnounce": true
    }
  ]
}
POST/api/v1/messages/send

Dispatches a text message to either an individual phone number (e.g. 919876543210) or a WhatsApp Group / Community Announcement JID (e.g. 120363041234567890@g.us). Each dispatch deducts only 1 credit from your available balance, even when broadcasting to an entire group!

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. Contacts & Leads API (CRM & Segmentation)

CRM & Lead Database

Manage high-value customer lead lists, sync external CRM databases, organize color-coded segmented audience groups, and bulk import up to 5,000 phone numbers per batch with automated WhatsApp number normalization and custom merge fields.

GET/api/v1/contacts

Query contacts with full-text search across name, phone, and email, with pagination and audience group filtering.

Query Parameters:
page: Page number (default: 1)
limit: Max items 1–200 (default: 50)
groupId: Filter group ID, 'all', or 'unassigned'
search: Search name, phone, email
cURL Request Example
Request
curl -X GET "https://whatsgate.deskshala.in/api/v1/contacts?page=1&limit=25&search=Rahul" \
  -H "Authorization: Bearer wsaas_live_YOUR_API_KEY"
Success Response (200 OK)
Response
{
  "contacts": [
    {
      "id": "cnt_9a8b7c6d5e",
      "phone": "919876543210",
      "name": "Rahul Verma",
      "email": "rahul@techcorp.in",
      "company": "Tech Corp Solutions",
      "groupId": "grp_vip_clients",
      "group": { "id": "grp_vip_clients", "name": "VIP Clients", "color": "#10b981" },
      "customFields": { "plan": "Enterprise Scale" },
      "createdAt": "2026-10-01T10:00:00.000Z"
    }
  ],
  "pagination": {
    "total": 1420,
    "page": 1,
    "limit": 25,
    "totalPages": 57
  }
}
POST/api/v1/contacts

Create or update an individual lead with custom variables and group tagging.

Request Body (JSON)
Payload
{
  "phone": "919876543210",
  "name": "Rahul Verma",
  "email": "rahul@techcorp.in",
  "company": "Tech Corp Solutions",
  "groupId": "grp_vip_clients",
  "customFields": {
    "plan": "Enterprise Scale",
    "renewalDate": "2026-10-15"
  }
}
Success Response (200 OK)
Response
{
  "success": true,
  "contact": {
    "id": "cnt_9a8b7c6d5e",
    "phone": "919876543210",
    "name": "Rahul Verma",
    "email": "rahul@techcorp.in",
    "company": "Tech Corp Solutions",
    "groupId": "grp_vip_clients",
    "customFields": { "plan": "Enterprise Scale", "renewalDate": "2026-10-15" },
    "createdAt": "2026-10-01T10:00:00.000Z"
  }
}
POST/api/v1/contacts/importMax 5,000 / Batch

High-speed batch import. Numbers with spaces, dashes, or missing country codes are automatically formatted to strict international E.164 WhatsApp specs.

Request Body (JSON)
Payload
{
  "newGroupName": "Diwali VIP Leads 2026",
  "updateExisting": true,
  "contacts": [
    {
      "phone": "+91 98765-43210",
      "name": "Rahul Verma",
      "email": "rahul@techcorp.in",
      "company": "Tech Corp",
      "customFields": { "seat": "A-12" }
    },
    {
      "phone": "919123456789",
      "name": "Priya Sharma",
      "email": "priya@apexlabs.com",
      "company": "Apex Labs",
      "customFields": { "seat": "B-04" }
    }
  ]
}
Success Response (200 OK)
Response
{
  "success": true,
  "message": "Successfully imported 2 contacts into 'Diwali VIP Leads 2026'",
  "imported": 2,
  "updated": 0,
  "skipped": 0,
  "invalid": 0,
  "group": {
    "id": "grp_diwali_2026",
    "name": "Diwali VIP Leads 2026"
  }
}
GET/api/v1/contacts/groups

List all audience segments with active contact counts and campaign broadcast usage.

// Response (200 OK):
{
  "groups": [
    {
      "id": "grp_diwali_2026",
      "name": "Diwali VIP Leads 2026",
      "description": "Premium festive leads",
      "color": "#10b981",
      "contactsCount": 450,
      "campaignsCount": 2,
      "createdAt": "2026-10-01T10:00:00.000Z"
    }
  ]
}
POST/api/v1/contacts/groups

Create a targeted color-coded audience group.

// Request Body (JSON):
{
  "name": "High Value Enterprise Clients",
  "description": "Accounts above $10,000 ARR",
  "color": "#8b5cf6"
}

// Response (201 Created):
{
  "success": true,
  "group": { "id": "grp_enterprise_vip", "name": "High Value Enterprise Clients", "color": "#8b5cf6" }
}

6. Broadcast Campaigns API (Mass Marketing)

Anti-Ban Broadcasting Engine

Broadcast marketing announcements and flyers to segmented audience groups or custom recipient lists. Built-in anti-ban queuing randomizes dispatch intervals (e.g. 4–12s human jitter) to prevent SIM blocking, with real-time live recipient delivery ticks.

POST/api/v1/campaigns1 Credit / Recipient

Create and initiate a marketing broadcast. Supports dynamic merge tags ({{name}}, {{company}}), image flyers, and custom humanized jitter delays.

Request Body (JSON)
Payload
{
  "name": "Diwali Flash Sale 2026",
  "deviceId": "dev_corporate_alpha",
  "groupId": "grp_vip_clients", // or "recipients": ["919876543210", ...]
  "message": "Namaste {{name}}! 🪔\n\nEnjoy an exclusive *40% OFF* on your {{company}} account.\nCoupon code: *FESTIVE2026*\n\nReply 'STOP' to unsubscribe.",
  "mediaUrl": "https://example.com/assets/diwali_special.jpg",
  "minDelayMs": 4000, // 4 seconds min jitter
  "maxDelayMs": 12000 // 12 seconds max jitter
}
Success Response (201 Created)
Response
{
  "success": true,
  "campaign": {
    "id": "cmp_89f1a0b3c2",
    "name": "Diwali Flash Sale 2026",
    "status": "RUNNING",
    "totalRecipients": 2450,
    "deviceId": "dev_corporate_alpha",
    "minDelayMs": 4000,
    "maxDelayMs": 12000,
    "createdAt": "2026-10-01T10:00:00.000Z"
  }
}
GET/api/v1/campaigns/:id

Retrieve real-time live dispatch metrics and recipient status audit breakdown.

Live Status Audit Response (200 OK)
{
  "success": true,
  "campaign": {
    "id": "cmp_89f1a0b3c2",
    "name": "Diwali Flash Sale 2026",
    "status": "RUNNING", // DRAFT | SCHEDULED | RUNNING | PAUSED | COMPLETED | CANCELLED
    "totalRecipients": 2450,
    "sentCount": 1820,
    "deliveredCount": 1740,
    "readCount": 1150,
    "failedCount": 12,
    "recipients": [
      {
        "phone": "919876543210",
        "name": "Rahul Verma",
        "status": "READ",
        "sentAt": "2026-10-01T10:05:22.000Z",
        "deliveredAt": "2026-10-01T10:05:24.000Z",
        "readAt": "2026-10-01T10:06:10.000Z"
      }
    ]
  }
}
POST/api/v1/campaigns/:id/action

Control live campaign execution: pause the queue, resume dispatch, cancel remaining messages with balance restore, or retry failed numbers.

Request Body (JSON)
Action Payload
{
  "action": "pause" // "pause" | "resume" | "cancel" | "retry_failed"
}
Success Response (200 OK)
Response
{
  "success": true,
  "message": "Campaign paused successfully",
  "campaign": {
    "id": "cmp_89f1a0b3c2",
    "status": "PAUSED"
  }
}

7. 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!

8. 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
}

9. Anti-Ban Architecture & Best Practices

WhatsGate includes built-in anti-ban safeguards. Follow these guidelines to maintain a high trust score on your connected WhatsApp numbers:

Human Jitter

Keep antiBan: true enabled to automatically randomize delays between dispatches (4–12s).

Warm-up Schedule

Start newly connected numbers at 50 messages/day, ramping up by 20–30% daily to build WhatsApp device trust score.

Opt-out Compliance

Always provide clear STOP or unsubscribe instructions in broadcast campaigns to prevent recipient spam reports.