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
- Log in to MSGLY Dashboard: Access dashboard.msgly.id using your Client account.
- 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 URLfor delivery callbacks. - Save Credentials: Copy your
client_idandclient_secret. Always store them securely in your backend environment variables. - Request Access Token: Exchange your Client ID & Secret for a Bearer Token via
POST /api/v1/oauth/token. - Send Messages: Dispatch WhatsApp OTP or individual messages via
POST /api/v1/message.
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).
Obtain a Bearer access token for authenticating subsequent API requests.
Request Header & Body (application/x-www-form-urlencoded):
| Parameter | Type | Required | Description |
|---|---|---|---|
grant_type | string | Required | Must be exactly client_credentials |
client_id | string | Required | Client ID issued from MSGLY Dashboard |
client_secret | string | Required | Client Secret issued from MSGLY Dashboard |
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"
{
"success": true,
"message": "token issued",
"data": {
"access_token": "msgly_tk_eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"token_type": "Bearer",
"expires_in": 86400
}
}
/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.
Request Parameters (JSON Body):
| Field | Type | Required | Description |
|---|---|---|---|
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. |
{
"messages": {
"id": "7c4817a5-d85c-48c0-845f-c9ab579899eb",
"xid": "trx-unique-001",
"status": "queued",
"timestamp": 1718451123456
}
}
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.
{
"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.
{
"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 Feature | Mechanism |
|---|---|
| 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. |
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).
{
"event": "message.status",
"data": {
"id": "7c4817a5-d85c-48c0-845f-c9ab579899eb",
"xid": "trx-unique-001",
"recipient": "628123456789",
"status": "delivered",
"oid": "3EB0B892819024D98A",
"timestamp": 1718451125000,
"error": ""
}
}
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:
{
"error": {
"message": "duplicate xid"
}
}
| HTTP Status | Error Message | Cause & 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 Area | Default Limit | Control 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.
| Language | Package Manager | Installation 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
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);
}
package main
import (
"context"
"fmt"
"log"
"time"
msgly "github.com/msgly-official/msgly-sdk-go"
)
func main() {
client := msgly.New(msgly.Config{
BaseURL: "https://api.msgly.id",
ClientID: "YOUR_CLIENT_ID",
ClientSecret: "YOUR_CLIENT_SECRET",
})
ctx := context.Background()
// 1. Send WhatsApp OTP (Automatic Rotation Mode)
otpResp, err := client.Message.SendOTP(ctx, msgly.SendOTPRequest{
XID: fmt.Sprintf("otp_%d", time.Now().Unix()),
To: "6281234567890",
Code: "482910",
})
if err != nil {
log.Fatalf("Error sending OTP: %v", err)
}
fmt.Printf("OTP Queued! ID: %s, Status: %s\n", otpResp.Messages.ID, otpResp.Messages.Status)
// 2. Send Single Message / Reminder
singleResp, err := client.Message.SendSingle(ctx, msgly.SendSingleRequest{
XID: fmt.Sprintf("rem_%d", time.Now().Unix()),
To: "6281234567890",
Message: "Hello! Your consultation schedule is confirmed for tomorrow at 10:00 WIB.",
})
if err != nil {
log.Fatalf("Error sending message: %v", err)
}
fmt.Printf("Message Queued! ID: %s\n", singleResp.Messages.ID)
}
import time
from msgly import MSGLYClient
client = MSGLYClient(
client_id="YOUR_CLIENT_ID",
client_secret="YOUR_CLIENT_SECRET",
base_url="https://api.msgly.id"
)
# 1. Send WhatsApp OTP (Automatic Rotation Mode)
try:
otp_resp = client.message.send_otp(
xid=f"otp_{int(time.time())}",
to="6281234567890",
code="482910"
)
print("OTP Queued ID:", otp_resp["messages"]["id"])
except Exception as e:
print("Error sending OTP:", e)
# 2. Send Single Message / Reminder
try:
single_resp = client.message.send_single(
xid=f"rem_{int(time.time())}",
to="6281234567890",
message="Hello John, your payment has been successfully verified."
)
print("Message Queued ID:", single_resp["messages"]["id"])
except Exception as e:
print("Error sending message:", e)
<?php
require_once 'vendor/autoload.php';
use MSGLY\MSGLYClient;
use MSGLY\Exceptions\MSGLYException;
$msgly = new MSGLYClient([
'base_url' => 'https://api.msgly.id',
'client_id' => 'YOUR_CLIENT_ID',
'client_secret' => 'YOUR_CLIENT_SECRET',
]);
// 1. Send WhatsApp OTP (Automatic Rotation Mode)
try {
$result = $msgly->message()->sendOTP([
'xid' => 'otp_' . time(),
'to' => '6281234567890',
'code' => '482910',
]);
echo "OTP Queued! ID: " . $result['messages']['id'] . PHP_EOL;
} catch (MSGLYException $e) {
echo "Failed to send OTP: " . $e->getMessage() . PHP_EOL;
}
// 2. Send Single Message / Reminder
try {
$single = $msgly->message()->sendSingle([
'xid' => 'rem_' . time(),
'to' => '6281234567890',
'message' => 'Hello, your order #ORD-998 has been dispatched via courier.',
]);
echo "Message Queued! ID: " . $single['messages']['id'] . PHP_EOL;
} catch (MSGLYException $e) {
echo "Failed to send message: " . $e->getMessage() . PHP_EOL;
}
?>
import id.msgly.MSGLYClient;
import id.msgly.message.SendMessageRequest;
import id.msgly.message.SendMessageResponse;
public class App {
public static void main(String[] args) {
MSGLYClient client = MSGLYClient.builder()
.baseUrl("https://api.msgly.id")
.clientId("YOUR_CLIENT_ID")
.clientSecret("YOUR_CLIENT_SECRET")
.build();
// 1. Send WhatsApp OTP (Automatic Rotation Mode)
try {
SendMessageResponse otpResp = client.message().sendOtp(
SendMessageRequest.builder()
.xid("otp_" + System.currentTimeMillis())
.to("6281234567890")
.code("482910")
.build()
);
System.out.println("OTP Queued ID: " + otpResp.getMessages().getId());
} catch (Exception e) {
e.printStackTrace();
}
}
}
