MSGLY
ID EN
Get Started
Developer Portal & Official SDKs

MSGLY WhatsApp API Documentation

Official integration guide for REST API and Official SDKs (Node.js, Go, Python, PHP, Java) covering WhatsApp OTP with automated template rotation, WhatsApp Blast campaigns, and real-time Webhook delivery callbacks.

Getting Started

MSGLY provides a high-throughput REST API with industry-standard OAuth 2.0 (Client Credentials) authentication. Message delivery is powered by asynchronous Redis queue clusters and dynamically rotated WhatsApp device pools (round-robin).

Configuration Production Value
Production Base URL https://api.msgly.id/api/v1
Authentication OAuth 2.0 (Bearer Token via Client Credentials)
Data Format JSON (Request Body & Response), URL-Encoded (OAuth Token)
Idempotency ID xid (Must be unique per dispatch transaction)

Integration Setup Workflow

  1. Log in to MSGLY Dashboard: Access dashboard.msgly.id using your Client account.
  2. Create API Client: Navigate to the API Client menu in the sidebar, then click Create New API Client. Enter your application name and register an optional Webhook URL for delivery callbacks.
  3. Save Credentials: Copy your client_id and client_secret. Always store them securely in your backend environment variables.
  4. Request Access Token: Exchange your Client ID & Secret for a Bearer Token via POST /api/v1/oauth/token.
  5. Send Messages: Dispatch WhatsApp OTP or individual messages via POST /api/v1/message.
Credential Security: Never store your client_secret in frontend code (React, Vue, mobile apps, or browser scripts). All interactions with the MSGLY API must be executed strictly from your server/backend.

Authentication (OAuth 2.0)

MSGLY uses the client_credentials grant type. The client_id and client_secret are exchanged for an Access Token valid for 24 hours (86,400 seconds).

POST https://api.msgly.id/api/v1/oauth/token

Obtain a Bearer access token for authenticating subsequent API requests.

Request Header & Body (application/x-www-form-urlencoded):

ParameterTypeRequiredDescription
grant_typestringRequiredMust be exactly client_credentials
client_idstringRequiredClient ID issued from MSGLY Dashboard
client_secretstringRequiredClient Secret issued from MSGLY Dashboard
cURL Request Example
curl -X POST https://api.msgly.id/api/v1/oauth/token \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET"
Response (200 OK)
{
  "success": true,
  "message": "token issued",
  "data": {
    "access_token": "msgly_tk_eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "token_type": "Bearer",
    "expires_in": 86400
  }
}
Best Practice Token Caching: Issued tokens are valid for 24 hours. We strongly recommend caching tokens in memory or Redis on your backend, refreshing only when expired (HTTP 401). Avoid calling /oauth/token on every message dispatch to avoid hitting rate limits.

Send Message (/message)

Outbound WhatsApp API messages are dispatched through the unified POST /api/v1/message endpoint with type otp. The system automatically selects an active WhatsApp sender device from the pool and enqueues the message into Redis with the highest priority.

Service Policy Note: To maintain sender device health and safeguard pool numbers against spam filters, the public external API is currently focused exclusively on WhatsApp OTP. Mass promotional broadcasts are handled through the WhatsApp Blast engine in the Dashboard.
POST https://api.msgly.id/api/v1/message

Request Parameters (JSON Body):

FieldTypeRequiredDescription
xid string Required Your unique transaction ID (Idempotency Key). Guarantees no duplicate messages are sent during network retries.
to string Required Destination WhatsApp number in international format (e.g. 628123456789). Local 08... prefixes are automatically normalized to 628....
type string Required Must be otp.
code string Required (Rotation Mode) Numeric or alphanumeric OTP code substituted into randomized templates by the server.
template object Optional (Manual Mode) Specific template object { "template_id": "UUID", "params": ["..."] } when not using automatic rotation.
Response Format (200 OK)
{
  "messages": {
    "id": "7c4817a5-d85c-48c0-845f-c9ab579899eb",
    "xid": "trx-unique-001",
    "status": "queued",
    "timestamp": 1718451123456
  }
}
Asynchronous Processing & Message ID: The initial HTTP response immediately returns status queued along with the id (MSGLY Message UUID) within < 50ms. Subsequent delivery lifecycle updates (sent, delivered, read, failed) and the WhatsApp Message ID (oid) are dispatched asynchronously via Webhook Callbacks.

WhatsApp OTP

Delivery of WhatsApp OTP verification codes is optimized for minimal latency and maximum deliverability. MSGLY supports two integration scenarios:

Scenario A: OTP Template Rotation (Recommended)

When OTP Rotation is enabled for your account in the Dashboard, the MSGLY server dynamically selects a randomized message template from whitelisted templates. You only supply the destination number and OTP code. This approach is proven to best safeguard sender numbers against WhatsApp spam filters.

POST /api/v1/message (OTP Rotation)
{
  "xid": "otp-trx-993",
  "to": "628123456789",
  "type": "otp",
  "code": "482019"
}

Scenario B: Manual Template Selection

If you need to use a specific template (e.g. customized login or registration templates), provide the template_id UUID and params array.

POST /api/v1/message (Manual Template)
{
  "xid": "otp-trx-992",
  "to": "628123456789",
  "type": "otp",
  "template": {
    "template_id": "c8f7a1b2-3c4d-5e6f-7a8b-9c0d1e2f3a4b",
    "params": ["482019"]
  }
}

WhatsApp Blast (Campaign)

For sending promotional messages and bulk broadcasts to thousands of contacts simultaneously, MSGLY provides an integrated Campaign Blast Engine in the MSGLY Dashboard:

Blast Protection FeatureMechanism
Device Pool Auto-Distribution Campaign recipient lists are distributed round-robin across all connected WhatsApp devices in your pool, balancing the sending load per device.
Dynamic Throttling & Delays Inter-message delays are randomized to eliminate robotic dispatch patterns detectable by WhatsApp.
Chat Presence Simulation Workers simulate human typing presence (composing) a few seconds before dispatching each message.
Realtime Stop & Pause Campaigns can be paused, canceled, or rescheduled in real time directly from the dashboard.
To execute high-volume blast campaigns, import contacts via CSV in Contacts > Import CSV on the Client Dashboard, then schedule your campaign under Campaigns.

Webhooks & Delivery Status

Register a Webhook URL in your API Client settings to receive real-time callback notifications when message delivery statuses change.

Delivery Lifecycle

  • queued: Message successfully accepted by API and queued in Redis workers.
  • sent: Message dispatched by the WhatsApp gateway device to WhatsApp servers.
  • delivered: Message delivered to the recipient device (two grey checkmarks).
  • read: Message opened and read by the recipient (two blue checkmarks).
  • failed: Message delivery failed (e.g. number not on WhatsApp or device gateway offline).
Webhook Payload Example (POST to your endpoint)
{
  "event": "message.status",
  "data": {
    "id": "7c4817a5-d85c-48c0-845f-c9ab579899eb",
    "xid": "trx-unique-001",
    "recipient": "628123456789",
    "status": "delivered",
    "oid": "3EB0B892819024D98A",
    "timestamp": 1718451125000,
    "error": ""
  }
}
Callback Retry Policy: The MSGLY server retries webhooks up to 3 times with exponential backoff if your server returns a non-2xx HTTP status or times out. Ensure your webhook endpoint responds with HTTP 200 OK promptly.

Error Codes & Response

In case of validation, authentication, or balance issues, the API returns standard HTTP status codes along with a JSON error payload:

JSON Error Response Format
{
  "error": {
    "message": "duplicate xid"
  }
}
HTTP StatusError MessageCause & Resolution
400 Bad Request duplicate xid This xid has already been used. Provide a fresh unique ID for each transaction.
400 Bad Request invalid phone number Destination phone number is invalid or formatted incorrectly.
400 Bad Request insufficient balance Account balance is insufficient to process this message. Top up wallet via dashboard.
400 Bad Request template not found Provided template_id UUID was not found or has not been approved.
401 Unauthorized The access token has expired OAuth 2.0 access token has expired. Request a new token via /oauth/token.
429 Too Many Requests rate limit exceeded Request rate exceeded your account limit (default: 100 req/min). Wait briefly before retrying.

Rate Limits

To ensure system stability and avoid unexpected traffic spikes, each API Client has rate limits applied:

Endpoint AreaDefault LimitControl Mechanism
POST /api/v1/message 100 requests / min per Client ID Redis distributed rate limiter (Sliding Window). Contact sales if higher throughput is required.
POST /api/v1/oauth/token 20 requests / min per IP Brute-force protection for token generation. Cache tokens for up to 24 hours.

Official SDKs & Libraries

MSGLY provides official client libraries (SDKs) to simplify backend integration without manual OAuth token refresh, JSON serialization, or error parsing.

LanguagePackage ManagerInstallation Command
Node.js (JS/TS) NPM npm install msgly-sdk
Go (Golang) Go Modules go get github.com/msgly-official/msgly-sdk-go
Python PyPI pip install msgly-sdk
PHP Composer composer require msgly/msgly-sdk-php
Java JitPack (Maven / Gradle) com.github.msgly-official:msgly-sdk-java:v1.0.0

Complete Integration Code Examples

Node.js (ESM / CommonJS)
import { MSGLYClient } from 'msgly-sdk';

const msgly = new MSGLYClient({
  baseUrl: 'https://api.msgly.id', // Optional, default https://api.msgly.id
  clientId: 'YOUR_CLIENT_ID',
  clientSecret: 'YOUR_CLIENT_SECRET'
});

// 1. Send WhatsApp OTP (Automatic Rotation Mode)
try {
  const otpResponse = await msgly.message.sendOTP({
    xid: 'otp_' + Date.now(),
    to: '6281234567890',
    code: '482910'
  });
  console.log('OTP Queued ID:', otpResponse.messages.id);
} catch (error) {
  console.error('Failed to send OTP:', error.message);
}

// 2. Send Single Message / Reminder
try {
  const singleResponse = await msgly.message.sendSingle({
    xid: 'rem_' + Date.now(),
    to: '6281234567890',
    message: 'Hello, your order #INV-1029 has been processed.'
  });
  console.log('Message Queued ID:', singleResponse.messages.id);
} catch (error) {
  console.error('Failed to send message:', error.message);
}

Need Integration Help or Custom Setup?

MSGLY support and developer engineers are available to assist with API and SDK implementation into your systems.

Consult an MSGLY Engineer