farinchan/chatery_whatsapp
소개
A powerful WhatsApp API backend built with Express.js and Baileys library. Supports multi-session management, real-time WebSocket events, group management, and media handling.
웹 및 앱 개발What you can do
- 📱 Multi-Session Support - Manage multiple WhatsApp accounts simultaneously
- 🔌 Real-time WebSocket - Get instant notifications for messages, status updates, and more
- 👥 Group Management - Create, manage, and control WhatsApp groups, including invite link preview
- 🏷️ Chat Labels - Label chats and messages for organization (WhatsApp Business)
측정된 스타 증가
- in 24h
- 0
- in 7 days
- 0
- in 15 days
- 0
- in 1 month
- 기록 수집 중
서로 겹치는 기간의 순증가량이며 일별 합계가 아닙니다. 측정값이 없으면 비워 둡니다. 스타는 관심도를 나타내며 품질을 보장하지 않습니다.
README.md
Original🚀 Chatery WhatsApp API
A powerful WhatsApp API backend built with Express.js and Baileys library. Supports multi-session management, real-time WebSocket events, group management, and media handling.
🏢 Official Sponsor
Special thanks to our official sponsor for supporting the development and infrastructure of Chatery WhatsApp API:
PT Nagari Sastra Group
https://nagastra.org/
✨ Features
- 📱 Multi-Session Support - Manage multiple WhatsApp accounts simultaneously
- 🔌 Real-time WebSocket - Get instant notifications for messages, status updates, and more
- 👥 Group Management - Create, manage, and control WhatsApp groups, including invite link preview
- 🏷️ Chat Labels - Label chats and messages for organization (WhatsApp Business)
- 📨 Rich Messaging - Send text, images, videos (with GIF playback), documents, audio/voice notes, stickers, locations, and contacts
- ↩️ Reply & Mentions - Quote specific messages with
replyToparameter and mention participants - 📊 Poll Messages - Send interactive polls with single or multiple choice
- 📌 Pin & Star Messages - Pin messages to chat top with custom duration and star important messages
- 🗃️ Chat Organization - Pin, archive, and mute individual chats
- 👤 Contact & Profile Privacy - Check bio status, business profile info, block/unblock, view blocklist, and update profile bio/display name
- 📤 Bulk Messaging - Send messages, images, and documents to multiple recipients with background processing
- 📥 Auto-Save Media - Automatically save incoming media to server
- 💾 Persistent Store - Message history with optimized LID mapping and in-memory caching
- 🔐 Session Persistence - Sessions survive server restarts
- 🎛️ Admin Dashboard - Web-based dashboard with real-time monitoring and interactive API tester
- 📄 Swagger UI - Interactive OpenAPI documentation at root URL
- 🧪 Automated Testing - Complete native test suite with 179+ unit, WebSocket, and integration tests
📖 Full Documentation
For complete and detailed documentation, please visit:
| 🌐 Documentation | Link |
|---|---|
| Primary Docs | https://docs.chatery.app |
| Mirror Docs | https://chatery-whatsapp-documentation.appwrite.network |
📚 The documentation includes complete API reference, examples, troubleshooting guides, and more.
📋 Table of Contents
- Official Sponsor
- Full Documentation
- Installation
- Configuration
- API Key Authentication
- Quick Start
- Dashboard
- API Documentation
- WebSocket Events
- Webhooks
- Testing
- Project Structure
- Examples
🛠 Installation
Option 1: Standard Installation
# Clone the repository
git clone https://github.com/farinchan/chatery_whatsapp.git
cd chatery_whatsapp
# Install dependencies
npm install
# Create environment file
cp .env.example .env
# Start the server
npm start
# Or development mode with auto-reload
npm run dev
Option 2: Docker Installation
# Clone the repository
git clone https://github.com/farinchan/chatery_whatsapp.git
cd chatery_whatsapp
# Create environment file
cp .env.example .env
# Build and run with Docker Compose
docker-compose up -d
# View logs
docker-compose logs -f
# Stop the container
docker-compose down
Docker Commands
| Command | Description |
|---|---|
docker-compose up -d |
Start container in background |
docker-compose down |
Stop and remove container |
docker-compose logs -f |
View live logs |
docker-compose restart |
Restart container |
docker-compose build --no-cache |
Rebuild image |
Docker Volumes & Data Persistence
Data sesi WhatsApp dan media disimpan langsung ke direktori host project (Host Bind Mounts) sehingga dapat dilihat, dicadangkan, dan diedit langsung di folder project:
| Host Directory | Container Path | Description |
|---|---|---|
./sessions |
/app/sessions |
WhatsApp session credentials, config.json, dan store.json (chat history) |
./public/media |
/app/public/media |
File media yang diunduh (foto, video, audio, dokumen) |
⚙ Configuration
Create a .env file in the root directory:
PORT=3000
CORS_ORIGIN=*
# Dashboard Authentication
DASHBOARD_USERNAME=admin
DASHBOARD_PASSWORD=securepassword123
# API Key Authentication (optional - leave empty or 'your_api_key_here' to disable)
API_KEY=your_secret_api_key_here
Note: Personal chat IDs use
@c.usformat (e.g.,[email protected]). Group IDs use@g.usformat. Phone numbers are automatically normalized (0 → 62).
🔐 API Key Authentication
All WhatsApp API endpoints are protected with API key authentication. Include the X-Api-Key header in your requests.
How to Enable
Set a strong API key in your
.envfile:API_KEY=your_super_secret_key_12345Include the header in all API requests:
curl -X GET http://localhost:3000/api/whatsapp/sessions \ -H "X-Api-Key: your_super_secret_key_12345"
Disable Authentication
To disable API key authentication, leave API_KEY empty or set it to your_api_key_here in .env:
API_KEY=
# or
API_KEY=your_api_key_here
Error Responses
| Status | Message | Description |
|---|---|---|
| 401 | Missing X-Api-Key header | API key not provided in request |
| 403 | Invalid API key | API key doesn't match |
Dashboard Integration
When logging into the dashboard, you'll be prompted to enter your API key (optional). This allows the dashboard to make authenticated API calls.
🚀 Quick Start
Start the server
npm startCreate a session
curl -X POST http://localhost:3000/api/whatsapp/sessions/mysession/connect \ -H "X-Api-Key: your_api_key" \ -H "Content-Type: application/json"Get QR Code - Open in browser or scan
http://localhost:3000/api/whatsapp/sessions/mysession/qr/imageNote: QR image endpoint also requires API key. Use curl or include header.
Send a message
curl -X POST http://localhost:3000/api/whatsapp/chats/send-text \ -H "X-Api-Key: your_api_key" \ -H "Content-Type: application/json" \ -d '{"sessionId": "mysession", "chatId": "628123456789", "message": "Hello!"}'
🎛️ Dashboard
Access the admin dashboard at http://localhost:3000/dashboard
🔐 Authentication
Dashboard requires login with username and password configured in .env file.
| Field | Default Value |
|---|---|
| Username | admin |
| Password | admin123 |
✨ Dashboard Features
| Feature | Description |
|---|---|
| 📊 Real-time Stats | Monitor total sessions, connected/disconnected status, and WebSocket clients |
| 📱 Session Management | Create, connect, reconnect, and delete WhatsApp sessions |
| 📷 QR Code Scanner | Scan QR codes directly from the dashboard |
| 📡 Live Events | Real-time WebSocket event viewer with filtering |
| 💬 Quick Send | Send messages quickly to any number |
| 🧪 API Tester | Test all 40+ API endpoints with pre-filled templates |
| 📤 Bulk Messaging | Send messages to multiple recipients with job tracking |
| 🔗 Webhook Manager | Add, remove, and configure webhooks per session |
| 🚪 Logout | Secure logout button in header |
📸 Screenshots

The dashboard provides a modern interface with light & dark themes:
- Light / Dark Theme - Toggle from the header (sun/moon icon); follows the OS setting until you pick one, and the choice is remembered per browser
- Session Cards - View all sessions with status indicators
- QR Modal - Full-screen QR code for easy scanning
- Event Log - Live scrolling event feed with timestamps
- API Tester - Dropdown with all endpoints and auto-generated request bodies
📚 API Documentation
Base URL: http://localhost:3000/api/whatsapp
Sessions
List All Sessions
GET /sessions
Response:
{
"success": true,
"message": "Sessions retrieved",
"data": [
{
"sessionId": "mysession",
"status": "connected",
"isConnected": true,
"phoneNumber": "628123456789",
"name": "John Doe",
"webhooks": [
{
"url": "https://your-server.com/webhook",
"events": ["message", "message_ack"]
}
],
"metadata": {
"userId": "user123",
"plan": "premium"
}
}
]
}
| Field | Type | Description |
|---|---|---|
sessionId |
string | Unique session identifier |
status |
string | Current status: disconnected, connecting, qr_ready, connected |
isConnected |
boolean | Whether session is currently connected |
phoneNumber |
string | Connected WhatsApp phone number |
name |
string | WhatsApp profile name |
webhooks |
array | Configured webhooks for this session |
metadata |
object | Custom metadata associated with this session |
Create/Connect Session
POST /sessions/:sessionId/connect
Body (Optional):
{
"metadata": {
"userId": "user123",
"plan": "premium",
"customField": "any value"
},
"webhooks": [
{ "url": "https://your-server.com/webhook", "events": ["all"] },
{ "url": "https://backup-server.com/webhook", "events": ["message"] }
]
}
| Parameter | Type | Description |
|---|---|---|
metadata |
object | Optional. Custom metadata to store with session |
webhooks |
array | Optional. Array of webhook configs [{ url, events }] |
Response:
{
"success": true,
"message": "Session created",
"data": {
"sessionId": "mysession",
"status": "qr_ready",
"qrCode": "data:image/png;base64,...",
"metadata": { "userId": "user123" },
"webhooks": [
{ "url": "https://your-server.com/webhook", "events": ["all"] }
]
}
}
Update Session Config
PATCH /sessions/:sessionId/config
Body:
{
"metadata": { "newField": "value" },
"webhooks": [
{ "url": "https://new-webhook.com/endpoint", "events": ["message", "connection.update"] }
]
}
Response:
{
"success": true,
"message": "Session config updated",
"data": {
"sessionId": "mysession",
"metadata": { "userId": "user123", "newField": "value" },
"webhooks": [
{ "url": "https://new-webhook.com/endpoint", "events": ["message", "connection.update"] }
]
}
}
Add Webhook
POST /sessions/:sessionId/webhooks
Body:
{
"url": "https://another-server.com/webhook",
"events": ["message", "connection.update"]
}
Remove Webhook
DELETE /sessions/:sessionId/webhooks
Body:
{
"url": "https://another-server.com/webhook"
}
Get Session Status
GET /sessions/:sessionId/status
Get QR Code (JSON)
GET /sessions/:sessionId/qr
Get QR Code (Image)
GET /sessions/:sessionId/qr/image
Returns a PNG image that can be displayed directly in browser or scanned.
Delete Session
DELETE /sessions/:sessionId
Messaging
💡 Typing Indicator: All messaging endpoints support
typingTimeparameter (in milliseconds) to simulate typing before sending the message. This makes the bot appear more human-like.↩️ Reply to Message: All messaging endpoints support
replyToparameter to reply to a specific message. Pass the message ID to quote/reply to that message.
Send Text Message
POST /chats/send-text
Body:
{
"sessionId": "mysession",
"chatId": "628123456789",
"message": "Hello, World!",
"typingTime": 2000,
"replyTo": "3EB0B430A2B52B67D0"
}
| Parameter | Type | Description |
|---|---|---|
sessionId |
string | Required. Session ID |
chatId |
string | Required. Phone number (628xxx) or group ID ([email protected]) |
message |
string | Required. Text message to send |
typingTime |
number | Optional. Typing duration in ms before sending (default: 0) |
replyTo |
string | Optional. Message ID to reply to |
Send Image
POST /chats/send-image
Body:
{
"sessionId": "mysession",
"chatId": "628123456789",
"imageUrl": "https://example.com/image.jpg",
"caption": "Check this out!",
"typingTime": 1500,
"replyTo": null
}
| Parameter | Type | Description |
|---|---|---|
sessionId |
string | Required. Session ID |
chatId |
string | Required. Phone number or group ID |
imageUrl |
string | Required. Direct URL to image file |
caption |
string | Optional. Image caption |
typingTime |
number | Optional. Typing duration in ms (default: 0) |
replyTo |
string | Optional. Message ID to reply to |
Send Video
POST /chats/send-video
Body:
{
"sessionId": "mysession",
"chatId": "628123456789",
"videoUrl": "https://example.com/video.mp4",
"caption": "Check out this video!",
"gifPlayback": false,
"typingTime": 2000,
"replyTo": null
}
| Parameter | Type | Description |
|---|---|---|
sessionId |
string | Required. Session ID |
chatId |
string | Required. Phone number or group ID |
videoUrl |
string | Required. Direct URL to video file (MP4) |
caption |
string | Optional. Video caption |
gifPlayback |
boolean | Optional. Play video as looping animated GIF without audio (default: false) |
typingTime |
number | Optional. Upload/recording simulation in ms (default: 0) |
replyTo |
string | Optional. Message ID to reply to |
Send Document
POST /chats/send-document
Body:
{
"sessionId": "mysession",
"chatId": "628123456789",
"documentUrl": "https://example.com/document.pdf",
"filename": "document.pdf",
"mimetype": "application/pdf",
"caption": "Here is the document you requested",
"typingTime": 1000,
"replyTo": null
}
| Parameter | Type | Description |
|---|---|---|
sessionId |
string | Required. Session ID |
chatId |
string | Required. Phone number or group ID |
documentUrl |
string | Required. Direct URL to document |
filename |
string | Required. Filename to display |
mimetype |
string | Optional. MIME type (default: application/pdf) |
caption |
string | Optional. Caption text for the document |
typingTime |
number | Optional. Typing duration in ms (default: 0) |
replyTo |
string | Optional. Message ID to reply to |
Send Audio
POST /chats/send-audio
⚠️ Important: Audio must be in OGG format (.ogg). WhatsApp only supports OGG audio files with Opus codec.
Convert audio using FFmpeg:
ffmpeg -i input.mp3 -c:a libopus output.ogg
Body:
{
"sessionId": "mysession",
"chatId": "628123456789",
"audioUrl": "https://example.com/audio.ogg",
"ptt": true,
"typingTime": 1000,
"replyTo": null
}
| Parameter | Type | Description |
|---|---|---|
sessionId |
string | Required. Session ID |
chatId |
string | Required. Phone number or group ID |
audioUrl |
string | Required. Direct URL to OGG audio file (.ogg format only) |
ptt |
boolean | Optional. Push to talk mode - true = voice note, false = audio file (default: false) |
typingTime |
number | Optional. Recording simulation in ms (default: 0) |
replyTo |
string | Optional. Message ID to reply to |
Send Sticker
POST /chats/send-sticker
💡 Tip: WhatsApp stickers must be in WebP format (.webp). Supports both static and animated stickers.
Body:
{
"sessionId": "mysession",
"chatId": "628123456789",
"stickerUrl": "https://example.com/sticker.webp",
"replyTo": null
}
| Parameter | Type | Description |
|---|---|---|
sessionId |
string | Required. Session ID |
chatId |
string | Required. Phone number or group ID |
stickerUrl |
string | Required. Direct URL to WebP sticker file |
replyTo |
string | Optional. Message ID to reply to |
Send Location
POST /chats/send-location
Body:
{
"sessionId": "mysession",
"chatId": "628123456789",
"latitude": -6.2088,
"longitude": 106.8456,
"name": "Jakarta, Indonesia",
"typingTime": 1000,
"replyTo": null
}
| Parameter | Type | Description |
|---|---|---|
sessionId |
string | Required. Session ID |
chatId |
string | Required. Phone number or group ID |
latitude |
number | Required. GPS latitude |
longitude |
number | Required. GPS longitude |
name |
string | Optional. Location name |
typingTime |
number | Optional. Typing duration in ms (default: 0) |
replyTo |
string | Optional. Message ID to reply to |
Send Contact
POST /chats/send-contact
Body:
{
"sessionId": "mysession",
"chatId": "628123456789",
"contactName": "John Doe",
"contactPhone": "628987654321",
"typingTime": 500,
"replyTo": null
}
| Parameter | Type | Description |
|---|---|---|
sessionId |
string | Required. Session ID |
chatId |
string | Required. Phone number or group ID |
contactName |
string | Required. Contact display name |
contactPhone |
string | Required. Contact phone number |
typingTime |
number | Optional. Typing duration in ms (default: 0) |
replyTo |
string | Optional. Message ID to reply to |
Send Poll Message
POST /chats/send-poll
Body:
{
"sessionId": "mysession",
"chatId": "628123456789",
"question": "What is your favorite color?",
"options": ["Red", "Blue", "Green", "Yellow"],
"selectableCount": 1,
"typingTime": 2000,
"replyTo": null
}
| Parameter | Type | Description |
|---|---|---|
sessionId |
string | Required. Session ID |
chatId |
string | Required. Phone number or group ID |
question |
string | Required. Poll question |
options |
array | Required. Array of options (2-12 items) |
selectableCount |
number | Optional. Number of selectable options (default: 1) |
typingTime |
number | Optional. Typing duration in ms (default: 0) |
replyTo |
string | Optional. Message ID to reply to |
Send Button Message (DEPRECATED)
POST /chats/send-button
⚠️ Note: WhatsApp deprecated button messages in 2022. This endpoint now uses Poll as an alternative. For actual interactive buttons, you need WhatsApp Business API (Cloud API).
Body:
{
"sessionId": "mysession",
"chatId": "628123456789",
"text": "Please choose an option:",
"footer": "Powered by Chatery",
"buttons": ["Option 1", "Option 2", "Option 3"],
"typingTime": 2000,
"replyTo": null
}
| Parameter | Type | Description |
|---|---|---|
sessionId |
string | Required. Session ID |
chatId |
string | Required. Phone number or group ID |
text |
string | Required. Poll question (combined with footer) |
footer |
string | Optional. Additional text |
buttons |
array | Required. Array of options (poll choices) |
typingTime |
number | Optional. Typing duration in ms (default: 0) |
replyTo |
string | Optional. Message ID to reply to |
Send Reaction
POST /chats/send-reaction
Body:
{
"sessionId": "mysession",
"chatId": "628123456789",
"messageId": "3EB0B430A2B52B67D0",
"emoji": "👍",
"fromMe": false
}
| Parameter | Type | Description |
|---|---|---|
sessionId |
string | Required. Session ID |
chatId |
string | Required. Phone number or group ID |
messageId |
string | Required. Target message ID to react to |
emoji |
string | Optional. Emoji reaction (empty string "" to remove reaction) |
fromMe |
boolean | Optional. Whether the target message was sent by yourself (default: false) |
Delete (Revoke) Message
POST /chats/delete-message
Deletes/revokes a message for everyone in personal or group chat.
Body:
{
"sessionId": "mysession",
"chatId": "628123456789",
"messageId": "3EB0B430A2B52B67D0"
}
| Parameter | Type | Description |
|---|---|---|
sessionId |
string | Required. Session ID |
chatId |
string | Required. Phone number or group ID |
messageId |
string | Required. ID of the message to revoke/delete |
Pin / Unpin Message
POST /chats/pin-message
Pin a message to the top of a conversation. Supports 24 hours, 7 days, 30 days, or unpinning.
Body:
{
"sessionId": "mysession",
"chatId": "628123456789",
"messageId": "3EB0B430A2B52B67D0",
"time": 604800,
"fromMe": false
}
| Parameter | Type | Description |
|---|---|---|
sessionId |
string | Required. Session ID |
chatId |
string | Required. Phone number or group ID |
messageId |
string | Required. Target message ID to pin/unpin |
time |
number | Optional. Pin duration in seconds (86400 = 24h, 604800 = 7d, 2592000 = 30d, 0 = unpin, default: 604800) |
fromMe |
boolean | Optional. Whether the message was sent by yourself (default: false) |
Star / Unstar Message
POST /chats/star-message
Star or unstar a message for easy reference and bookmarking.
Body:
{
"sessionId": "mysession",
"chatId": "628123456789",
"messageId": "3EB0B430A2B52B67D0",
"star": true,
"fromMe": false
}
| Parameter | Type | Description |
|---|---|---|
sessionId |
string | Required. Session ID |
chatId |
string | Required. Phone number or group ID |
messageId |
string | Required. Target message ID |
star |
boolean | Optional. true to star message, false to unstar (default: true) |
fromMe |
boolean | Optional. Whether the message was sent by yourself (default: false) |
Pin / Unpin Chat
POST /chats/pin
Pin or unpin an entire chat to the top of your chat list.
Body:
{
"sessionId": "mysession",
"chatId": "628123456789",
"pin": true
}
| Parameter | Type | Description |
|---|---|---|
sessionId |
string | Required. Session ID |
chatId |
string | Required. Phone number or group ID |
pin |
boolean | Optional. true to pin chat, false to unpin (default: true) |
Archive / Unarchive Chat
POST /chats/archive
Archive or unarchive a chat thread.
Body:
{
"sessionId": "mysession",
"chatId": "628123456789",
"archive": true
}
| Parameter | Type | Description |
|---|---|---|
sessionId |
string | Required. Session ID |
chatId |
string | Required. Phone number or group ID |
archive |
boolean | Optional. true to archive chat, false to unarchive (default: true) |
Mute / Unmute Chat
POST /chats/mute
Mute or unmute notifications for a specific chat.
Body:
{
"sessionId": "mysession",
"chatId": "628123456789",
"duration": 28800000
}
| Parameter | Type | Description |
|---|---|---|
sessionId |
string | Required. Session ID |
chatId |
string | Required. Phone number or group ID |
duration |
number | null | Optional. Mute duration in ms (28800000 = 8h, 604800000 = 1 week, -1 = indefinitely, null = unmute) |
Send Presence Update
POST /chats/presence
Body:
{
"sessionId": "mysession",
"chatId": "628123456789",
"presence": "composing"
}
| Parameter | Type | Description |
|---|---|---|
sessionId |
string | Required. Session ID |
chatId |
string | Required. Phone number or group ID |
presence |
string | Required. composing, recording, paused, available, unavailable |
Check Phone Number
POST /chats/check-number
Body:
{
"sessionId": "mysession",
"phone": "628123456789"
}
Get Profile Picture
POST /chats/profile-picture
Body:
{
"sessionId": "mysession",
"phone": "628123456789"
}
Bulk Messaging (Background Jobs)
Bulk messaging runs in the background and returns immediately with a job ID. You can track progress using the status endpoint.
⚡ Background Processing: All bulk endpoints return immediately with a
jobId. Messages are sent in background to avoid request timeouts. Track progress with the status endpoint.
Send Bulk Text Message
POST /chats/send-bulk
Body:
{
"sessionId": "mysession",
"recipients": ["628123456789", "628987654321", "628111222333"],
"message": "Hello! This is a bulk message.",
"delayBetweenMessages": 1000,
"typingTime": 0
}
| Parameter | Type | Description |
|---|---|---|
sessionId |
string | Required. Session ID |
recipients |
array | Required. Array of phone numbers (max 100) |
message |
string | Required. Text message to send |
delayBetweenMessages |
number | Optional. Delay between messages in ms (default: 1000) |
typingTime |
number | Optional. Typing indicator duration in ms (default: 0) |
Response:
{
"success": true,
"message": "Bulk message job started. Check status with jobId.",
"data": {
"jobId": "bulk_1704326400000_abc123def",
"total": 3,
"statusUrl": "/api/whatsapp/chats/bulk-status/bulk_1704326400000_abc123def"
}
}
Send Bulk Image
POST /chats/send-bulk-image
Body:
{
"sessionId": "mysession",
"recipients": ["628123456789", "628987654321"],
"imageUrl": "https://example.com/image.jpg",
"caption": "Check out this image!",
"delayBetweenMessages": 1000,
"typingTime": 0
}
| Parameter | Type | Description |
|---|---|---|
sessionId |
string | Required. Session ID |
recipients |
array | Required. Array of phone numbers (max 100) |
imageUrl |
string | Required. Direct URL to image file |
caption |
string | Optional. Image caption |
delayBetweenMessages |
number | Optional. Delay between messages in ms (default: 1000) |
typingTime |
number | Optional. Typing indicator duration in ms (default: 0) |
Send Bulk Document
POST /chats/send-bulk-document
Body:
{
"sessionId": "mysession",
"recipients": ["628123456789", "628987654321"],
"documentUrl": "https://example.com/document.pdf",
"filename": "document.pdf",
"mimetype": "application/pdf",
"delayBetweenMessages": 1000,
"typingTime": 0
}
| Parameter | Type | Description |
|---|---|---|
sessionId |
string | Required. Session ID |
recipients |
array | Required. Array of phone numbers (max 100) |
documentUrl |
string | Required. Direct URL to document |
filename |
string | Required. Filename to display |
mimetype |
string | Optional. MIME type (default: application/pdf) |
delayBetweenMessages |
number | Optional. Delay between messages in ms (default: 1000) |
typingTime |
number | Optional. Typing indicator duration in ms (default: 0) |
Get Bulk Job Status
GET /chats/bulk-status/:jobId
Response:
{
"success": true,
"data": {
"sessionId": "mysession",
"type": "text",
"status": "processing",
"total": 50,
"sent": 25,
"failed": 2,
"progress": 54,
"details": [
{
"recipient": "628123456789",
"status": "sent",
"messageId": "ABC123",
"timestamp": "2026-01-04T10:00:00.000Z"
},
{
"recipient": "628987654321",
"status": "failed",
"error": "Number not registered",
"timestamp": "2026-01-04T10:00:01.000Z"
}
],
"createdAt": "2026-01-04T10:00:00.000Z",
"completedAt": null
}
}
| Field | Type | Description |
|---|---|---|
status |
string | processing or completed |
progress |
number | Progress percentage (0-100) |
sent |
number | Successfully sent count |
failed |
number | Failed count |
details |
array | Per-recipient status with timestamps |
Get All Bulk Jobs
POST /chats/bulk-jobs
Body:
{
"sessionId": "mysession"
}
Response:
{
"success": true,
"data": [
{
"jobId": "bulk_1704326400000_abc123def",
"type": "text",
"status": "completed",
"total": 50,
"sent": 48,
"failed": 2,
"progress": 100,
"createdAt": "2026-01-04T10:00:00.000Z",
"completedAt": "2026-01-04T10:02:30.000Z"
}
]
}
Chat History
Get Chats Overview
POST /chats/overview
Body:
{
"sessionId": "mysession",
"limit": 50,
"offset": 0,
"type": "all"
}
| Parameter | Type | Description |
|---|---|---|
sessionId |
string | Required. Session ID |
limit |
number | Optional. Max results (default: 50) |
offset |
number | Optional. Pagination offset (default: 0) |
type |
string | Optional. Filter: all, personal, group |
Get Contacts
POST /contacts
Body:
{
"sessionId": "mysession",
"limit": 100,
"offset": 0,
"search": "john"
}
Get Chat Messages
POST /chats/messages
Body:
{
"sessionId": "mysession",
"chatId": "[email protected]",
"limit": 50,
"cursor": null
}
Get Chat Info
POST /chats/info
Body:
{
"sessionId": "mysession",
"chatId": "[email protected]"
}
Mark Chat as Read
POST /chats/mark-read
Mark all unread messages in a chat as read. Works for both personal and group chats.
Body:
{
"sessionId": "mysession",
"chatId": "628123456789"
}
| Parameter | Type | Description |
|---|---|---|
sessionId |
string | Required. Session ID |
chatId |
string | Required. Phone number or group ID (@c.us or @g.us) |
Response:
{
"success": true,
"message": "Chat marked as read",
"data": {
"chatId": "[email protected]",
"isGroup": false,
"markedCount": 5
}
}
| Field | Type | Description |
|---|---|---|
chatId |
string | Chat ID that was marked as read |
isGroup |
boolean | Whether the chat is a group |
markedCount |
number | Number of messages marked as read |
Note: Messages must be received after the server starts to be in the store. If
markedCountis 0, there were no unread messages in the store.
Contacts & Profile
Get Contacts
POST /contacts
Get all contacts stored in the session store with optional pagination and search filter.
Body:
{
"sessionId": "mysession",
"limit": 100,
"offset": 0,
"search": "john"
}
| Parameter | Type | Description |
|---|---|---|
sessionId |
string | Required. Session ID |
limit |
number | Optional. Max results (default: 100) |
offset |
number | Optional. Pagination offset (default: 0) |
search |
string | Optional. Search query for contact name, phone number, or ID |
Add / Save Contact
POST /contacts/add
Add or update a contact in the WhatsApp address book. Supports syncing contact to the primary phone's native address book (Google Contacts / iCloud) via syncContactToPhone (default is false).
Note: Endpoint alias
/contacts/saveis also supported.
Body:
{
"sessionId": "mysession",
"phone": "628123456789",
"name": "Budi Santoso",
"firstName": "Budi",
"syncContactToPhone": false
}
| Parameter | Type | Description |
|---|---|---|
sessionId |
string | Required. Session ID |
phone |
string | Required. Phone number (e.g. 628123456789) |
name |
string | Required. Contact full name or display name |
firstName |
string | Optional. Contact first name |
syncContactToPhone |
boolean | Optional. Whether to sync contact to primary phone native address book (default: false). Alias: syncToPhone |
Response:
{
"success": true,
"message": "Contact added successfully",
"data": {
"id": "[email protected]",
"phone": "628123456789",
"name": "Budi Santoso",
"syncContactToPhone": false
}
}
Get Contact Status / Bio
POST /contacts/status
Fetch the WhatsApp "About" (bio / status) text of a given phone number.
Body:
{
"sessionId": "mysession",
"phone": "628123456789"
}
| Parameter | Type | Description |
|---|---|---|
sessionId |
string | Required. Session ID |
phone |
string | Required. Phone number (e.g. 628123456789) |
Response:
{
"success": true,
"data": {
"status": "Hey there! I am using WhatsApp.",
"setAt": "2026-01-01T12:00:00.000Z"
}
}
Get WhatsApp Business Profile
POST /contacts/business-profile
Fetch business profile details for a WhatsApp Business account (description, address, email, websites, category).
Body:
{
"sessionId": "mysession",
"phone": "628123456789"
}
| Parameter | Type | Description |
|---|---|---|
sessionId |
string | Required. Session ID |
phone |
string | Required. Phone number |
Response:
{
"success": true,
"data": {
"wid": "[email protected]",
"description": "Official Support for MyApp",
"address": "Jakarta, Indonesia",
"email": "[email protected]",
"websites": ["https://example.com"],
"category": "Customer Support"
}
}
Block or Unblock Contact
POST /contacts/block
Block or unblock a contact from sending messages and calling.
Body:
{
"sessionId": "mysession",
"phone": "628123456789",
"action": "block"
}
| Parameter | Type | Description |
|---|---|---|
sessionId |
string | Required. Session ID |
phone |
string | Required. Phone number to block or unblock |
action |
string | Optional. Action: block or unblock (default: block) |
Response:
{
"success": true,
"message": "Contact blocked successfully",
"data": {
"phone": "628123456789",
"action": "block"
}
}
Get Blocklist
POST /contacts/blocklist
Get the list of all blocked contacts for the current session.
Body:
{
"sessionId": "mysession"
}
Response:
{
"success": true,
"data": [
"[email protected]",
"[email protected]"
]
}
Update Profile Status (Bio)
POST /profile/status
Update your WhatsApp account's "About" bio status text.
Body:
{
"sessionId": "mysession",
"status": "Available on WhatsApp"
}
| Parameter | Type | Description |
|---|---|---|
sessionId |
string | Required. Session ID |
status |
string | Required. New bio/status text |
Update Profile Display Name
POST /profile/name
Update your WhatsApp account's public display name.
Body:
{
"sessionId": "mysession",
"name": "My Support Bot"
}
| Parameter | Type | Description |
|---|---|---|
sessionId |
string | Required. Session ID |
name |
string | Required. New display name |
Group Management
Get All Groups
POST /groups
Body:
{
"sessionId": "mysession"
}
Response:
{
"success": true,
"data": {
"count": 5,
"groups": [
{
"id": "[email protected]",
"subject": "My Group",
"participantsCount": 25,
"creation": 1609459200
}
]
}
}
Create Group
POST /groups/create
Body:
{
"sessionId": "mysession",
"name": "My New Group",
"participants": ["628123456789", "628987654321"]
}
Get Group Metadata
POST /groups/metadata
Body:
{
"sessionId": "mysession",
"groupId": "[email protected]"
}
Response:
{
"success": true,
"data": {
"id": "[email protected]",
"subject": "My Group",
"description": "Group description",
"participants": [
{ "id": "[email protected]", "admin": "superadmin" },
{ "id": "[email protected]", "admin": null }
],
"size": 25
}
}
Add Participants
POST /groups/participants/add
Body:
{
"sessionId": "mysession",
"groupId": "[email protected]",
"participants": ["628111222333", "628444555666"]
}
Remove Participants
POST /groups/participants/remove
Body:
{
"sessionId": "mysession",
"groupId": "[email protected]",
"participants": ["628111222333"]
}
Promote to Admin
POST /groups/participants/promote
Body:
{
"sessionId": "mysession",
"groupId": "[email protected]",
"participants": ["628111222333"]
}
Demote from Admin
POST /groups/participants/demote
Body:
{
"sessionId": "mysession",
"groupId": "[email protected]",
"participants": ["628111222333"]
}
Update Group Subject (Name)
POST /groups/subject
Body:
{
"sessionId": "mysession",
"groupId": "[email protected]",
"subject": "New Group Name"
}
Update Group Description
POST /groups/description
Body:
{
"sessionId": "mysession",
"groupId": "[email protected]",
"description": "This is the new group description"
}
Update Group Settings
POST /groups/settings
Body:
{
"sessionId": "mysession",
"groupId": "[email protected]",
"setting": "announcement"
}
| Setting | Description |
|---|---|
announcement |
Only admins can send messages |
not_announcement |
All participants can send messages |
locked |
Only admins can edit group info |
unlocked |
All participants can edit group info |
Update Group Picture
POST /groups/picture
Body:
{
"sessionId": "mysession",
"groupId": "[email protected]",
"imageUrl": "https://example.com/group-pic.jpg"
}
Leave Group
POST /groups/leave
Body:
{
"sessionId": "mysession",
"groupId": "[email protected]"
}
Join Group via Invite
POST /groups/join
Body:
{
"sessionId": "mysession",
"inviteCode": "https://chat.whatsapp.com/AbCdEfGhIjKlMn"
}
Get Invite Code
POST /groups/invite-code
Body:
{
"sessionId": "mysession",
"groupId": "[email protected]"
}
Response:
{
"success": true,
"data": {
"groupId": "[email protected]",
"inviteCode": "AbCdEfGhIjKlMn",
"inviteLink": "https://chat.whatsapp.com/AbCdEfGhIjKlMn"
}
}
Revoke Invite Code
POST /groups/revoke-invite
Body:
{
"sessionId": "mysession",
"groupId": "[email protected]"
}
Get Group Invite Info (Preview Group)
POST /groups/invite-info
Inspect and preview group information (subject, description, creator, participant count) from an invite link or code without joining.
Body:
{
"sessionId": "mysession",
"inviteCode": "https://chat.whatsapp.com/AbCdEfGhIjKlMn"
}
| Parameter | Type | Description |
|---|---|---|
sessionId |
string | Required. Session ID |
inviteCode |
string | Required. Group invite code or full WhatsApp invite link |
Response:
{
"success": true,
"data": {
"id": "[email protected]",
"subject": "Community Discussion",
"owner": "[email protected]",
"creation": 1704326400,
"size": 42,
"desc": "Official community discussion group"
}
}
🏷️ Labels (WhatsApp Business)
WhatsApp Business labels help you organize and categorize chats. Available only for WhatsApp Business accounts.
Get All Labels
POST /labels
Body:
{
"sessionId": "mysession"
}
Response:
{
"success": true,
"data": {
"labels": [
{ "id": "1", "name": "New Customer", "color": 0 },
{ "id": "2", "name": "VIP", "color": 5 }
],
"count": 2
}
}
Create/Update Label
POST /labels/create
Body:
{
"sessionId": "mysession",
"name": "My Label",
"colorId": 3,
"labelId": null
}
| Parameter | Type | Description |
|---|---|---|
sessionId |
string | Required. Session ID |
name |
string | Required. Label name |
colorId |
number | Optional. Color ID (0-19), default: 0 |
labelId |
string | Optional. Existing label ID to update |
Response:
{
"success": true,
"message": "Label created successfully",
"data": {
"labelId": "3",
"name": "My Label",
"color": 3
}
}
Delete Label
POST /labels/delete
Body:
{
"sessionId": "mysession",
"labelId": "3"
}
Add Label to Chat
POST /labels/chat/add
Body:
{
"sessionId": "mysession",
"chatId": "628123456789",
"labelId": "3"
}
Remove Label from Chat
POST /labels/chat/remove
Body:
{
"sessionId": "mysession",
"chatId": "628123456789",
"labelId": "3"
}
Get Labels for Chat
POST /labels/chat
Body:
{
"sessionId": "mysession",
"chatId": "628123456789"
}
Response:
{
"success": true,
"data": {
"chatId": "[email protected]",
"labels": [
{ "id": "3", "name": "My Label", "color": 3 }
]
}
}
Note: Labels are only available for WhatsApp Business accounts. Personal accounts cannot use labels.
🔌 WebSocket Events
Connect to WebSocket server at ws://localhost:3000
Connection
When API_KEY is configured in your .env, WebSocket clients must authenticate at connection time using either the auth object, the x-api-key header, or a valid session cookie.
import { io } from 'socket.io-client';
const socket = io('http://localhost:3000', {
auth: {
apiKey: 'your_api_key_here'
}
});
// Subscribe to a session (requires authenticated connection)
socket.emit('subscribe', 'mysession');
// Unsubscribe from a session
socket.emit('unsubscribe', 'mysession');
Events
| Event | Description | Payload |
|---|---|---|
qr |
QR code generated | { sessionId, qrCode, timestamp } |
connection.update |
Connection status changed | { sessionId, status, phoneNumber?, name?, timestamp } |
message |
New message received | { sessionId, message, timestamp } |
message.sent |
Message sent confirmation | { sessionId, message, timestamp } |
message.update |
Message status update (read, delivered) | { sessionId, update, timestamp } |
message.reaction |
Message reaction added | { sessionId, reactions, timestamp } |
message.revoke |
Message deleted/revoked | { sessionId, key, participant, timestamp } |
chat.update |
Chat updated | { sessionId, chats, timestamp } |
chat.upsert |
New chat created | { sessionId, chats, timestamp } |
chat.delete |
Chat deleted | { sessionId, chatIds, timestamp } |
contact.update |
Contact updated | { sessionId, contacts, timestamp } |
presence.update |
Typing, online status | { sessionId, presence, timestamp } |
group.participants |
Group members changed | { sessionId, update, timestamp } |
group.update |
Group info changed | { sessionId, update, timestamp } |
call |
Incoming call | { sessionId, call, timestamp } |
labels |
Labels updated (business) | { sessionId, labels, timestamp } |
logged.out |
Session logged out | { sessionId, message, timestamp } |
Example: Listen for Messages
const socket = io('http://localhost:3000', {
auth: {
apiKey: 'your_api_key_here'
}
});
socket.on('connect', () => {
console.log('Connected to WebSocket');
socket.emit('subscribe', 'mysession');
});
socket.on('message', (data) => {
console.log('New message:', data.message);
// {
// sessionId: 'mysession',
// message: {
// id: 'ABC123',
// from: '[email protected]',
// text: 'Hello!',
// timestamp: 1234567890,
// ...
// },
// timestamp: '2024-01-15T10:30:00.000Z'
// }
});
socket.on('qr', (data) => {
console.log('Scan QR Code:', data.qrCode);
});
socket.on('connection.update', (data) => {
console.log('Connection status:', data.status);
if (data.status === 'connected') {
console.log(`Connected as ${data.name} (${data.phoneNumber})`);
}
});
Live WebSocket Event Monitoring
Open http://localhost:3000/dashboard or http://localhost:3000/wa-web and click on the Activity Drawer icon to stream live WebSocket events.
🪝 Webhooks
You can configure multiple webhook URLs to receive events from your WhatsApp session. Each webhook can subscribe to specific events.
Setup Multiple Webhooks
Set webhooks when creating or updating a session:
# When creating session with multiple webhooks
curl -X POST http://localhost:3000/api/whatsapp/sessions/mysession/connect \
-H "Content-Type: application/json" \
-d '{
"metadata": { "userId": "123" },
"webhooks": [
{ "url": "https://primary-server.com/webhook", "events": ["all"] },
{ "url": "https://analytics.example.com/webhook", "events": ["message"] },
{ "url": "https://backup.example.com/webhook", "events": ["connection.update"] }
]
}'
# Add a webhook to existing session
curl -X POST http://localhost:3000/api/whatsapp/sessions/mysession/webhooks \
-H "Content-Type: application/json" \
-d '{
"url": "https://new-webhook.com/endpoint",
"events": ["message", "connection.update"]
}'
# Remove a webhook
curl -X DELETE http://localhost:3000/api/whatsapp/sessions/mysession/webhooks \
-H "Content-Type: application/json" \
-d '{
"url": "https://new-webhook.com/endpoint"
}'
# Update all webhooks
curl -X PATCH http://localhost:3000/api/whatsapp/sessions/mysession/config \
-H "Content-Type: application/json" \
-d '{
"webhooks": [
{ "url": "https://only-this-one.com/webhook", "events": ["all"] }
]
}'
Webhook Payload
All configured webhook endpoints will receive POST requests with this format:
{
"event": "message",
"sessionId": "mysession",
"metadata": {
"userId": "123",
"customField": "value"
},
"data": {
"id": "ABC123",
"from": "[email protected]",
"text": "Hello!",
"timestamp": 1234567890
},
"timestamp": "2024-01-15T10:30:00.000Z"
}
Webhook Headers
| Header | Value |
|---|---|
Content-Type |
application/json |
X-Webhook-Source |
chatery-whatsapp-api |
X-Session-Id |
Session ID |
X-Webhook-Event |
Event name |
Available Webhook Events
| Event | Description |
|---|---|
connection.update |
Connection status changed (connected, disconnected) |
message |
New message received |
message.sent |
Message sent confirmation |
Set events: ["all"] to receive all events, or specify individual events per webhook.
WebSocket Stats
Requires X-Api-Key header (if configured in .env) or active dashboard session.
GET /api/websocket/stats
X-Api-Key: your_api_key_here
Response:
{
"success": true,
"data": {
"totalConnections": 5,
"sessionRooms": {
"mysession": 2,
"othersession": 1
}
}
}
🧪 Testing
Chatery WhatsApp comes equipped with a comprehensive automated test suite powered by the Node.js native test runner (node:test and node:assert). No heavy test runners or external mocking dependencies are needed.
Running Tests
# Run all tests (Unit, WebSocket, Integration) - 160+ passing tests
npm test
# Run only unit tests (Store, Formatter, Auth Middleware)
npm run test:unit
# Run only WebSocket tests (Rooms, Event Emitters, Broadcasts)
npm run test:websocket
# Run only REST API integration tests (All endpoints & validation)
npm run test:integration
📁 Project Structure
chatery_whatsapp/
├── index.js # Application entry point
├── package.json # Dependencies and test scripts
├── .env # Environment variables
├── README.md # Documentation
├── public/
│ ├── dashboard.html # Admin dashboard & interactive API tester
│ ├── wa-web.html # Authentic WhatsApp Web chat interface
│ └── media/ # Auto-saved media files
│ └── {sessionId}/
│ └── {chatId}/
├── sessions/ # WhatsApp multi-device authentication & stores
│ └── {sessionId}/
│ ├── creds.json
│ └── store.json
├── src/
│ ├── config/
│ │ └── swagger-paths.js # OpenAPI / Swagger specification
│ ├── routes/
│ │ └── whatsapp.js # REST API route handlers
│ └── services/
│ ├── websocket/
│ │ └── WebSocketManager.js # Socket.IO room manager & event broadcaster
│ └── whatsapp/
│ ├── index.js
│ ├── WhatsAppManager.js # Multi-session orchestrator
│ ├── WhatsAppSession.js # Baileys client wrapper & business logic
│ ├── BaileysStore.js # In-memory store with LID identity mapping
│ └── MessageFormatter.js # Universal Baileys message parser
└── tests/
├── unit/
│ ├── api-key-auth.test.js # Middleware authentication tests
│ ├── baileys-store.test.js # Store caching & LID resolution tests
│ └── message-formatter.test.js # Multi-format message parser tests
├── websocket/
│ └── websocket-manager.test.js # Socket.IO connection & event tests
└── integration/
├── test-helper.js # Mock session & lightweight test server
├── server-endpoints.test.js # Health, OpenAPI, login & WS stats tests
├── sessions-api.test.js # Session lifecycle & webhook tests
├── messaging-bulk-api.test.js# Send messages, reactions, pins & bulk jobs
└── groups-labels-api.test.js # Group admin actions & labels tests
📝 Examples
Node.js Client
const axios = require('axios');
const API_URL = 'http://localhost:3000/api/whatsapp';
// Create session
async function createSession(sessionId) {
const response = await axios.post(`${API_URL}/sessions/${sessionId}/connect`);
return response.data;
}
// Send message
async function sendMessage(sessionId, to, message) {
const response = await axios.post(`${API_URL}/chats/send-text`, {
sessionId,
to,
message
});
return response.data;
}
// Get all groups
async function getGroups(sessionId) {
const response = await axios.post(`${API_URL}/groups`, { sessionId });
return response.data;
}
Python Client
import requests
API_URL = 'http://localhost:3000/api/whatsapp'
# Create session
def create_session(session_id):
response = requests.post(f'{API_URL}/sessions/{session_id}/connect')
return response.json()
# Send message
def send_message(session_id, to, message):
response = requests.post(f'{API_URL}/chats/send-text', json={
'sessionId': session_id,
'to': to,
'message': message
})
return response.json()
# Get all groups
def get_groups(session_id):
response = requests.post(f'{API_URL}/groups', json={
'sessionId': session_id
})
return response.json()
🤝 Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
☕ Support & Donate
If you find this project helpful, consider supporting the development:
Your support helps me maintain and improve this project! ❤️
🏢 Official Sponsor
Proudly sponsored by PT Nagari Sastra Group — Empowering digital transformation & enterprise software development.
👨💻 Author
Fajri Rinaldi Chan (Farin Chan)
🔗 Quick Links
| Resource | URL |
|---|---|
| 📄 Swagger UI (API Docs) | http://localhost:3000 |
| 🎛️ Dashboard | http://localhost:3000/dashboard |
| 💬 WhatsApp Web | http://localhost:3000/wa-web |
| 📚 API Base URL | http://localhost:3000/api/whatsapp |
| 📊 WebSocket Stats | http://localhost:3000/api/websocket/stats |
| ❤️ Health Check | http://localhost:3000/api/health |
| 📋 OpenAPI JSON | http://localhost:3000/api-docs.json |
⚠️ Disclaimer
This project is not affiliated with WhatsApp or Meta. Use at your own risk. Make sure to comply with WhatsApp's Terms of Service.
관련 프로젝트 살펴보기
불러오는 중…