### Clone Repository and Install Dependencies Source: https://github.com/avoylenko/wwebjs-api/blob/main/README.md Clone the repository and install project dependencies using npm. ```bash git clone https://github.com/avoylenko/wwebjs-api.git cd wwebjs-api npm install ``` -------------------------------- ### Start a Session with API Key Source: https://context7.com/avoylenko/wwebjs-api/llms.txt Use this command to start a new session. Ensure you replace 'your-production-secret' with your actual API key. ```bash curl -H "x-api-key: your-production-secret" \ http://localhost:3000/session/start/prod-session-1 ``` -------------------------------- ### Example Code Block Formatting Source: https://github.com/avoylenko/wwebjs-api/blob/main/CONTRIBUTING.md Demonstrates how to format code examples and error messages using triple backticks for clear presentation in documentation. ```markdown ``` // Example code block const hello = "Hello, world!"; console.log(hello); ``` ``` -------------------------------- ### Run the Application Source: https://github.com/avoylenko/wwebjs-api/blob/main/README.md Start the wwebjs-api application using npm. ```bash npm run start ``` -------------------------------- ### Webhook Events Receiver Example Source: https://context7.com/avoylenko/wwebjs-api/llms.txt Example of how to set up an Express.js server to receive and handle webhook events from the wwebjs-api. ```javascript const express = require('express') const app = express() app.use(express.json()) app.post('/webhook', (req, res) => { const { event, sessionId, payload } = req.body switch (event) { case 'qr': console.log(`QR for session ${sessionId}:`, payload.qr) break case 'authenticated': console.log(`Session ${sessionId} authenticated successfully`) break case 'ready': console.log(`Session ${sessionId} is ready to send/receive messages`) break case 'message': const msg = payload.message console.log(`[${sessionId}] From ${msg.from}: ${msg.body}`) if (msg.hasMedia) { console.log('Message has media attachment') } break case 'media': const { messageMedia, message } = payload console.log(`Media type: ${messageMedia.mimetype}, size: ${messageMedia.data.length}`) break case 'message_ack': console.log(`Message ${payload.message.id._serialized} ack: ${payload.ack}`) break case 'message_reaction': console.log(`Reaction ${payload.reaction.reaction} on message from ${payload.reaction.senderId}`) break case 'disconnected': console.log(`Session ${sessionId} disconnected: ${payload.reason}`) break case 'group_join': console.log(`New member joined group in session ${sessionId}`) break case 'vote_update': console.log(`Poll vote update:`, payload.vote) break } res.sendStatus(200) }) app.listen(3001) ``` -------------------------------- ### WebSocket Client Example Source: https://context7.com/avoylenko/wwebjs-api/llms.txt Example of a Node.js WebSocket client connecting to the wwebjs-api to receive real-time events. ```javascript const WebSocket = require('ws') const sessionId = 'acme-support' const ws = new WebSocket(`ws://localhost:3000/ws/${sessionId}`) ws.on('open', () => { console.log('WebSocket connected for session:', sessionId) }) ws.on('message', (raw) => { const { dataType, data, sessionId } = JSON.parse(raw) if (dataType === 'message') { console.log(`New message from ${data.message.from}: ${data.message.body}`) } else if (dataType === 'qr') { console.log('Scan this QR code:', data.qr) } else if (dataType === 'ready') { console.log(`Session ${sessionId} is ready`) } }) ws.on('error', (err) => console.error('WebSocket error:', err)) ws.on('close', () => console.log('WebSocket connection closed')) ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/avoylenko/wwebjs-api/blob/main/README.md Copy the example environment file and update required variables. ```bash cp .env.example .env ``` -------------------------------- ### Browser/Node.js WebSocket Client Example Source: https://context7.com/avoylenko/wwebjs-api/llms.txt Example of a WebSocket client for Node.js or browser environments to connect to the wwebjs-api for real-time event notifications. Handles connection, message parsing, and error events. ```javascript const WebSocket = require('ws') const sessionId = 'acme-support' const ws = new WebSocket(`ws://localhost:3000/ws/${sessionId}`) ws.on('open', () => { console.log('WebSocket connected for session:', sessionId) // Keep connection alive with ping/pong (handled automatically by ws library) }) ws.on('message', (raw) => { const { dataType, data, sessionId } = JSON.parse(raw) if (dataType === 'message') { console.log(`New message from ${data.message.from}: ${data.message.body}`) } else if (dataType === 'qr') { console.log('Scan this QR code:', data.qr) } else if (dataType === 'ready') { console.log(`Session ${sessionId} is ready`) } }) ws.on('error', (err) => console.error('WebSocket error:', err)) ws.on('close', () => console.log('WebSocket connection closed')) ``` -------------------------------- ### Docker Compose Configuration for wwebjs-api Source: https://context7.com/avoylenko/wwebjs-api/llms.txt Example docker-compose.yml file for deploying wwebjs-api. Includes port mapping, volume for session persistence, and environment variables for configuration. ```yaml # docker-compose.yml version: '3.8' services: wwebjs-api: image: avoylenko/wwebjs-api:latest ports: - "3000:3000" volumes: - ./sessions:/app/sessions # Persist session auth data environment: API_KEY: "your-production-secret" BASE_WEBHOOK_URL: "https://api.yourapp.com/whatsapp/webhook" ENABLE_LOCAL_CALLBACK_EXAMPLE: "FALSE" SET_MESSAGES_AS_SEEN: "TRUE" DISABLED_CALLBACKS: "message_ack|unread_count|message_ciphertext" RECOVER_SESSIONS: "TRUE" LOG_LEVEL: "warn" restart: unless-stopped ``` -------------------------------- ### Express.js Webhook Receiver Example Source: https://context7.com/avoylenko/wwebjs-api/llms.txt Example of an Express.js application set up to receive and process webhook events from the wwebjs-api. Handles various event types like 'qr', 'message', and 'disconnected'. ```javascript const express = require('express') const app = express() app.use(express.json()) app.post('/webhook', (req, res) => { const { event, sessionId, payload } = req.body switch (event) { case 'qr': // Display QR code to the user for scanning console.log(`QR for session ${sessionId}:`, payload.qr) break case 'authenticated': console.log(`Session ${sessionId} authenticated successfully`) break case 'ready': console.log(`Session ${sessionId} is ready to send/receive messages`) break case 'message': // Incoming message const msg = payload.message console.log(`[${sessionId}] From ${msg.from}: ${msg.body}`) if (msg.hasMedia) { console.log('Message has media attachment') } break case 'media': // Auto-downloaded media attachment (requires SET_MESSAGES_AS_SEEN=TRUE // and media size < MAX_ATTACHMENT_SIZE) const { messageMedia, message } = payload console.log(`Media type: ${messageMedia.mimetype}, size: ${messageMedia.data.length}`) break case 'message_ack': // Delivery/read receipt update (ack: 1=sent, 2=delivered, 3=read) console.log(`Message ${payload.message.id._serialized} ack: ${payload.ack}`) break case 'message_reaction': console.log(`Reaction ${payload.reaction.reaction} on message from ${payload.reaction.senderId}`) break case 'disconnected': console.log(`Session ${sessionId} disconnected: ${payload.reason}`) break case 'group_join': console.log(`New member joined group in session ${sessionId}`) break case 'vote_update': console.log(`Poll vote update:`, payload.vote) break } res.sendStatus(200) }) app.listen(3001) ``` -------------------------------- ### Start WhatsApp Session Source: https://context7.com/avoylenko/wwebjs-api/llms.txt Initiates a new WhatsApp session by launching a browser client. If a saved session exists, it will be reloaded; otherwise, a QR code event will be emitted. Requires an API key. ```bash # Start session named "acme-support" curl -H "x-api-key: my-secret-key" \ http://localhost:3000/session/start/acme-support # Response: {"success":true,"message":"Session initiated successfully"} ``` -------------------------------- ### Run Docker Compose for WWebJS API Source: https://github.com/avoylenko/wwebjs-api/blob/main/README.md Pull the latest Docker images and start the WWebJS API services using Docker Compose. This command initiates the API in a Dockerized environment. ```bash docker compose pull && docker compose up ``` -------------------------------- ### Docker Deployment Command Source: https://context7.com/avoylenko/wwebjs-api/llms.txt Command to pull the latest wwebjs-api image and start the containers in detached mode. ```bash docker compose pull && docker compose up -d ``` -------------------------------- ### Basic Kong Route Setup Source: https://github.com/avoylenko/wwebjs-api/blob/main/REVERSE_PROXY_SETUP.md Configure Kong to route traffic to your WWebJS API service. Ensure strip_path is true to remove the base path before forwarding. ```yaml # Kong route configuration routes: - name: wwebjs-api paths: ["/api/v1/whatsapp"] strip_path: true # Important: removes the prefix before forwarding preserve_host: false protocols: ["http", "https"] service: wwebjs-service services: - name: wwebjs-service url: http://wwebjs-api:3000 connect_timeout: 60000 write_timeout: 60000 read_timeout: 60000 ``` -------------------------------- ### Get Sessions Source: https://context7.com/avoylenko/wwebjs-api/llms.txt Lists all active session IDs. ```APIDOC ## GET /session/getSessions — List all active session IDs ### Method GET ### Endpoint /session/getSessions ``` -------------------------------- ### Get Contacts Source: https://context7.com/avoylenko/wwebjs-api/llms.txt Retrieves all contacts associated with a session. ```APIDOC ## GET /client/getContacts/:sessionId — Retrieve all contacts ### Method GET ### Endpoint /client/getContacts/:sessionId ### Parameters #### Path Parameters - **sessionId** (string) - Required - The ID of the session to retrieve contacts from. ``` -------------------------------- ### Get Group Invite Link Code Source: https://context7.com/avoylenko/wwebjs-api/llms.txt Retrieves the invite link code for a group. Requires chatId. ```bash curl -X POST \ -H "x-api-key: my-secret-key" \ -H "Content-Type: application/json" \ -d '{"chatId":"XXXXXXXXXX@g.us"}' \ http://localhost:3000/groupChat/getInviteCode/acme-support # Response: {"success":true,"inviteCode":"ABCxyz123"} # Link: https://chat.whatsapp.com/ABCxyz123 ``` -------------------------------- ### Get Page Screenshot Source: https://context7.com/avoylenko/wwebjs-api/llms.txt Captures a screenshot of the current browser page for debugging purposes. ```APIDOC ## GET /session/getPageScreenshot/:sessionId — Capture browser screenshot for debugging Returns a PNG image of the current browser page, useful for diagnosing authentication or connection issues. ### Method GET ### Endpoint /session/getPageScreenshot/:sessionId ### Parameters #### Path Parameters - **sessionId** (string) - Required - The ID of the session to capture a screenshot from. ``` -------------------------------- ### Retrieve All Chats Source: https://context7.com/avoylenko/wwebjs-api/llms.txt Fetches all chats for the given session. This endpoint can be used to get a list of all conversations. ```bash curl -H "x-api-key: my-secret-key" \ http://localhost:3000/client/getChats/acme-support ``` -------------------------------- ### Get Contact About Text Source: https://context7.com/avoylenko/wwebjs-api/llms.txt Retrieves the status or about text of a contact. ```APIDOC ## POST /contact/getAbout/:sessionId — Get a contact's status/about text ### Description Retrieves the status or about text of a contact. ### Method POST ### Endpoint /contact/getAbout/acme-support ### Parameters #### Request Body - **contactId** (string) - Required - The ID of the contact. ### Request Example ```json { "contactId": "6281288888888@c.us" } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. - **result** (string) - The about text of the contact. ``` -------------------------------- ### Update whatsapp-web.js Dependency Source: https://github.com/avoylenko/wwebjs-api/blob/main/README.md Modify package.json to use the latest edge version of whatsapp-web.js from GitHub. Rerun npm install after changes. ```json "whatsapp-web.js": "github:pedroslopez/whatsapp-web.js#main" ``` -------------------------------- ### Get Group Invite Code Source: https://context7.com/avoylenko/wwebjs-api/llms.txt Retrieves the invite link code for a group chat. ```APIDOC ## POST /groupChat/getInviteCode/:sessionId — Get the group invite link code ### Description Retrieves the invite link code for a group chat. ### Method POST ### Endpoint /groupChat/getInviteCode/acme-support ### Parameters #### Request Body - **chatId** (string) - Required - The ID of the group chat. ### Request Example ```json { "chatId": "XXXXXXXXXX@g.us" } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. - **inviteCode** (string) - The invite code for the group. - **Link** (string) - The full invite link. ``` -------------------------------- ### Get a Contact's Status/About Text Source: https://context7.com/avoylenko/wwebjs-api/llms.txt Retrieves the 'about' text (status message) of a contact. Requires the contactId. ```bash curl -X POST \ -H "x-api-key: my-secret-key" \ -H "Content-Type: application/json" \ -d '{"contactId":"6281288888888@c.us"}' \ http://localhost:3000/contact/getAbout/acme-support # Response: {"success":true,"result":"Hey there! I am using WhatsApp."} ``` -------------------------------- ### Clone Repository with Docker Compose Source: https://github.com/avoylenko/wwebjs-api/blob/main/README.md Clone the repository and navigate into the project directory. This is the initial step for setting up the WWebJS API. ```bash git clone https://github.com/avoylenko/wwebjs-api.git cd wwebjs-api ``` -------------------------------- ### Run Test Suite Source: https://github.com/avoylenko/wwebjs-api/blob/main/README.md Execute the project's test suite using the npm test command. ```bash npm run test ``` -------------------------------- ### Get Poll Votes Source: https://context7.com/avoylenko/wwebjs-api/llms.txt Retrieves the vote results for a poll message. ```APIDOC ## POST /message/getPollVotes/:sessionId — Get vote results for a poll message ### Description Retrieves the vote results for a poll message. ### Method POST ### Endpoint /message/getPollVotes/acme-support ### Parameters #### Request Body - **chatId** (string) - Required - The ID of the chat containing the poll message. - **messageId** (string) - Required - The ID of the poll message. ### Request Example ```json { "chatId": "6281288888888@c.us", "messageId": "3A80E857F9B44AF60C2C" } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. - **votes** (array) - An array of vote objects, each containing voter information and selected options. ``` -------------------------------- ### Get Chats Source: https://context7.com/avoylenko/wwebjs-api/llms.txt Retrieves all chats for a given session, with options for filtering. ```APIDOC ## GET /client/getChats/:sessionId — Retrieve all chats Retrieves all chats for a given session, with options for filtering. ### Method GET ### Endpoint /client/getChats/:sessionId ### Parameters #### Path Parameters - **sessionId** (string) - Required - The ID of the session to retrieve chats from. #### Request Body (for POST variant) - **searchOptions** (object) - Optional - Options to filter the chats (e.g., `unread`, `since`). ``` -------------------------------- ### Environment Configuration Reference Source: https://context7.com/avoylenko/wwebjs-api/llms.txt This is a complete reference for environment variables used to configure the WWebJS REST API. Adjust these settings to control port, API keys, webhook destinations, rate limits, session storage, and more. ```bash # .env — complete configuration reference PORT=3000 API_KEY=my-secret-key # All requests require x-api-key: my-secret-key header BASE_WEBHOOK_URL=https://my.server/webhook # Destination for all callback events ENABLE_LOCAL_CALLBACK_EXAMPLE=FALSE # Disable in production RATE_LIMIT_MAX=1000 # Max requests per window RATE_LIMIT_WINDOW_MS=1000 # Window duration in ms MAX_ATTACHMENT_SIZE=10000000 # Bytes; media above this size won't be auto-downloaded SET_MESSAGES_AS_SEEN=TRUE # Auto-mark received messages as read # Suppress high-volume callbacks: DISABLED_CALLBACKS=message_ack|unread_count|message_edit|message_ciphertext WEB_VERSION=2.2328.5 # Pin specific WhatsApp Web version WEB_VERSION_CACHE_TYPE=none # none | local | remote RECOVER_SESSIONS=TRUE # Restart session on browser page crash HEADLESS=TRUE RELEASE_BROWSER_LOCK=TRUE LOG_LEVEL=info # pino levels: trace|debug|info|warn|error|fatal ENABLE_WEBHOOK=TRUE ENABLE_WEBSOCKET=FALSE # Enable for ws:// real-time events AUTO_START_SESSIONS=TRUE # Restore persisted sessions on startup SESSIONS_PATH=./sessions ENABLE_SWAGGER_ENDPOINT=TRUE # Serve /api-docs BASE_PATH=/api/v1/whatsapp # Mount all routes under this prefix TRUST_PROXY=FALSE ALLOWED_ORIGINS=https://app.example.com # CORS — comma-separated ``` -------------------------------- ### Create a New WhatsApp Channel Source: https://context7.com/avoylenko/wwebjs-api/llms.txt Creates a new WhatsApp Channel with a specified title and optional description. Requires a title and can include options for description. ```bash curl -X POST \ -H "x-api-key: my-secret-key" \ -H "Content-Type: application/json" \ -d '{"title":"Acme Announcements","options":{"description":"Official company updates"}}' \ http://localhost:3000/client/createChannel/acme-support # Response: {"success":true,"result":{...channelObject}} ``` -------------------------------- ### Retrieve QR Code as PNG Image Source: https://context7.com/avoylenko/wwebjs-api/llms.txt Downloads the QR code for a session directly as a PNG image. This is convenient for immediate display or saving to a file. Requires an API key. ```bash # Get QR as PNG image (pipe to file) curl -H "x-api-key: my-secret-key" \ http://localhost:3000/session/qr/acme-support/image \ --output qr.png ``` -------------------------------- ### Execute any whatsapp-web.js client method dynamically Source: https://context7.com/avoylenko/wwebjs-api/llms.txt This advanced endpoint allows calling any method on the underlying `Client` instance that is not explicitly wrapped by a dedicated API endpoint. Use with caution. ```bash curl -X POST \ -H "x-api-key: my-secret-key" \ -H "Content-Type: application/json" \ -d '{"method":"getLabels"}' \ http://localhost:3000/client/runMethod/acme-support # Response: {"success":true,"data":[...]} ``` -------------------------------- ### Download Media as Raw Binary Stream Source: https://context7.com/avoylenko/wwebjs-api/llms.txt Use this endpoint to download media associated with a message as a raw binary stream. Requires chatId and messageId. ```bash curl -X POST \ -H "x-api-key: my-secret-key" \ -H "Content-Type: application/json" \ -d '{"chatId":"6281288888888@c.us","messageId":"3A80E857F9B44AF60C2C"}' \ http://localhost:3000/message/downloadMediaAsData/acme-support \ --output received-photo.jpg ``` -------------------------------- ### Docker Compose with Nginx Reverse Proxy Source: https://github.com/avoylenko/wwebjs-api/blob/main/REVERSE_PROXY_SETUP.md Set up WWebJS API and Nginx in a Docker Compose environment. Ensure environment variables and volume mounts are correctly configured. ```yaml version: '3.8' services: wwebjs-api: image: avoylenko/wwebjs-api:latest container_name: wwebjs-api restart: always environment: # Reverse proxy configuration - BASE_PATH=/api/v1/whatsapp - TRUST_PROXY=true # Other configurations - BASE_WEBHOOK_URL=https://api.yourdomain.com/api/v1/whatsapp/localCallbackExample - API_KEY=your_secure_api_key - ENABLE_LOCAL_CALLBACK_EXAMPLE=false - ENABLE_SWAGGER_ENDPOINT=true volumes: - ./sessions:/usr/src/app/sessions networks: - api-network nginx: image: nginx:alpine container_name: nginx-proxy ports: - "80:80" - "443:443" volumes: - ./nginx.conf:/etc/nginx/nginx.conf depends_on: - wwebjs-api networks: - api-network networks: api-network: driver: bridge ``` -------------------------------- ### Get Vote Results for a Poll Message Source: https://context7.com/avoylenko/wwebjs-api/llms.txt Retrieves the vote results for a specific poll message. Requires chatId and messageId. ```bash curl -X POST \ -H "x-api-key: my-secret-key" \ -H "Content-Type: application/json" \ -d '{"chatId":"6281288888888@c.us","messageId":"3A80E857F9B44AF60C2C"}' \ http://localhost:3000/message/getPollVotes/acme-support # Response: {"success":true,"votes":[{"voter":"6281299999999@c.us","selectedOptions":["Pepperoni"]}]} ``` -------------------------------- ### Connect to WebSocket for Events Source: https://github.com/avoylenko/wwebjs-api/blob/main/README.md Establish a WebSocket connection to receive real-time events for a specific session. The server supports ping/pong for maintaining the connection. ```javascript const ws = new WebSocket('ws://127.0.0.1:3000/ws/test'); ws.on('message', (data) => { // consume the events }); ``` -------------------------------- ### Capture Browser Screenshot for Debugging Source: https://context7.com/avoylenko/wwebjs-api/llms.txt Returns a PNG image of the current browser page. This is helpful for diagnosing authentication or connection issues. ```bash curl -H "x-api-key: my-secret-key" \ http://localhost:3000/session/getPageScreenshot/acme-support \ --output debug.png ``` -------------------------------- ### Retrieve QR Code String Source: https://context7.com/avoylenko/wwebjs-api/llms.txt Fetches the raw QR code string for a given session, which can then be encoded and displayed. Requires an API key. ```bash # Get raw QR string curl -H "x-api-key: my-secret-key" \ http://localhost:3000/session/qr/acme-support # Response: {"success":true,"qr":"2@xxx,yyy,..."} ``` -------------------------------- ### Environment Variables for Reverse Proxy Source: https://github.com/avoylenko/wwebjs-api/blob/main/REVERSE_PROXY_SETUP.md Set these environment variables to enable reverse proxy support. TRUST_PROXY is required for correct IP forwarding. ```bash # Base path for mounting all routes (optional) BASE_PATH=/api/v1/whatsapp # Enable trust proxy for proper IP forwarding (required for reverse proxy) TRUST_PROXY=true ``` -------------------------------- ### Execute any whatsapp-web.js client method dynamically Source: https://context7.com/avoylenko/wwebjs-api/llms.txt Allows calling any method on the underlying `Client` instance that is not explicitly wrapped by a dedicated endpoint. ```APIDOC ## POST /client/runMethod/:sessionId — Execute any whatsapp-web.js client method dynamically ### Description Allows calling any method on the underlying `Client` instance that is not explicitly wrapped by a dedicated endpoint. ### Method POST ### Endpoint /client/runMethod/:sessionId ### Parameters #### Path Parameters - **sessionId** (string) - Required - The session ID for the client. #### Request Body - **method** (string) - Required - The name of the method to execute on the `Client` instance. - **params** (array) - Optional - An array of parameters to pass to the method. ### Request Example ```bash curl -X POST \ -H "x-api-key: my-secret-key" \ -H "Content-Type: application/json" \ -d '{"method":"getLabels"}' \ http://localhost:3000/client/runMethod/acme-support ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. - **data** (any) - The result returned by the executed method. #### Response Example ```json { "success": true, "data": [...] } ``` ``` -------------------------------- ### Kong Configuration for WebSocket Support Source: https://github.com/avoylenko/wwebjs-api/blob/main/REVERSE_PROXY_SETUP.md Set up a separate Kong route for WebSocket connections, ensuring the correct protocols (ws, wss) are used. ```yaml # Kong route for WebSocket connections routes: - name: wwebjs-websocket paths: ["/api/v1/whatsapp/ws"] strip_path: true protocols: ["ws", "wss"] service: wwebjs-websocket-service services: - name: wwebjs-websocket-service url: http://wwebjs-api:3000 ``` -------------------------------- ### Search for Channels using REST API Source: https://context7.com/avoylenko/wwebjs-api/llms.txt Use this endpoint to search for channels based on provided search options. Requires session ID and search parameters. ```bash curl -X POST \ -H "x-api-key: my-secret-key" \ -H "Content-Type: application/json" \ -d '{"searchOptions":{"searchText":"news","countryCodes":["US"],"skipSubscribedNewsletters":true,"limit":10}}' \ http://localhost:3000/client/searchChannels/acme-support # Response: {"success":true,"result":[...channelList]} ``` -------------------------------- ### Create Channel Source: https://context7.com/avoylenko/wwebjs-api/llms.txt Creates a new WhatsApp Channel (Newsletter). ```APIDOC ## POST /client/createChannel/:sessionId — Create a new WhatsApp Channel ### Description Creates a new WhatsApp Channel (Newsletter). ### Method POST ### Endpoint /client/createChannel/acme-support ### Parameters #### Request Body - **title** (string) - Required - The title for the new channel. - **options** (object) - Optional - Additional options for channel creation. - **description** (string) - Optional - A description for the channel. ### Request Example ```json { "title": "Acme Announcements", "options": {"description": "Official company updates"} } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. - **result** (object) - An object containing details of the created channel. ``` -------------------------------- ### Create a new WhatsApp group Source: https://context7.com/avoylenko/wwebjs-api/llms.txt Creates a new WhatsApp group with a specified title and participants. ```APIDOC ## POST /client/createGroup/:sessionId — Create a new WhatsApp group ### Description Creates a new WhatsApp group with a specified title and participants. ### Method POST ### Endpoint /client/createGroup/:sessionId ### Parameters #### Path Parameters - **sessionId** (string) - Required - The session ID for the client. #### Request Body - **title** (string) - Required - The title of the group. - **participants** (array) - Required - An array of participant IDs (e.g., "6281288888888@c.us"). - **options** (object) - Optional - Additional options for group creation. ### Request Example ```bash curl -X POST \ -H "x-api-key: my-secret-key" \ -H "Content-Type: application/json" \ -d '{ "title": "Acme Team Q4", "participants": ["6281288888888@c.us","6281299999999@c.us"], "options": {} }' \ http://localhost:3000/client/createGroup/acme-support ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. - **response** (object) - Contains information about the created group, including its ID. #### Response Example ```json { "success": true, "response": { "gid": { "_serialized": "XXXXXXXXXX@g.us" }, ... } } ``` ``` -------------------------------- ### Create a new WhatsApp group Source: https://context7.com/avoylenko/wwebjs-api/llms.txt Creates a new WhatsApp group with a specified title and participants. Ensure participant numbers are in the correct format (e.g., '6281288888888@c.us'). ```bash curl -X POST \ -H "x-api-key: my-secret-key" \ -H "Content-Type: application/json" \ -d '{ "title": "Acme Team Q4", "participants": ["6281288888888@c.us","6281299999999@c.us"], "options": {} }' \ http://localhost:3000/client/createGroup/acme-support # Response: {"success":true,"response":{"gid":{"_serialized":"XXXXXXXXXX@g.us"},...}} ``` -------------------------------- ### Subscribe to a Channel using REST API Source: https://context7.com/avoylenko/wwebjs-api/llms.txt Use this endpoint to subscribe a client to a specific channel. Requires session ID and channel ID. ```bash curl -X POST \ -H "x-api-key: my-secret-key" \ -H "Content-Type: application/json" \ -d '{"channelId":"XXXXXXXXXX@newsletter"}' \ http://localhost:3000/client/subscribeToChannel/acme-support # Response: {"success":true,"result":true} ``` -------------------------------- ### Callbacks Source: https://github.com/avoylenko/wwebjs-api/blob/main/README.md Callbacks provide real-time notifications for various WhatsApp events. ```APIDOC ## Callback QR Code ### Description Callback for receiving QR code for session authentication. ### Method POST ### Endpoint /callback/qrCode ### Parameters #### Request Body - **qrCode** (string) - The QR code string. ``` ```APIDOC ## Callback New Message ### Description Callback for receiving new incoming messages. ### Method POST ### Endpoint /callback/newMessage ### Parameters #### Request Body - **message** (object) - Details of the new message. ``` ```APIDOC ## Callback Status Change ### Description Callback for changes in message or user status. ### Method POST ### Endpoint /callback/statusChange ### Parameters #### Request Body - **statusInfo** (object) - Information about the status change. ``` ```APIDOC ## Callback Message Media Attachment ### Description Callback for when a message contains media attachments. ### Method POST ### Endpoint /callback/messageMediaAttachment ### Parameters #### Request Body - **messageId** (string) - The ID of the message. - **mediaInfo** (object) - Information about the media attachment. ``` -------------------------------- ### Download media from a message Source: https://context7.com/avoylenko/wwebjs-api/llms.txt Downloads media (like images, videos, documents) attached to a specific message. Returns the media data, mimetype, and filename. ```bash curl -X POST \ -H "x-api-key: my-secret-key" \ -H "Content-Type: application/json" \ -d '{"chatId":"6281288888888@c.us","messageId":"3A80E857F9B44AF60C2C"}' \ http://localhost:3000/message/downloadMedia/acme-support # Response: {"success":true,"messageMedia":{"data":"","mimetype":"image/jpeg","filename":"photo.jpg"}} ``` -------------------------------- ### Restart Session (Keep Auth Data) Source: https://context7.com/avoylenko/wwebjs-api/llms.txt Restarts a session by destroying the browser process and re-initializing the client with saved credentials. Useful for recovering from stuck states without logging out. ```bash curl -H "x-api-key: my-secret-key" \ http://localhost:3000/session/restart/acme-support # Response: {"success":true,"message":"Restarted successfully"} ``` -------------------------------- ### Terminate Session (Logout and Remove) Source: https://context7.com/avoylenko/wwebjs-api/llms.txt Logs out the WhatsApp account, destroys the browser, and deletes the session folder. Use this to fully log out and clean up session data. ```bash curl -H "x-api-key: my-secret-key" \ http://localhost:3000/session/terminate/acme-support # Response: {"success":true,"message":"Logged out successfully"} ``` -------------------------------- ### Health Check Source: https://context7.com/avoylenko/wwebjs-api/llms.txt A lightweight liveness probe to verify the server is running. It requires no authentication and returns a simple 'pong' response. ```APIDOC ## GET /ping — Verify the server is running ### Description A lightweight liveness probe that requires no authentication and returns a simple `pong` response. ### Method GET ### Endpoint /ping ### Request Example ```bash curl http://localhost:3000/ping ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the request was successful. - **result** (string) - The response from the server, typically "pong". ### Response Example ```json { "success": true, "result": "pong" } ``` ``` -------------------------------- ### Protect REST Endpoints with API Key Source: https://github.com/avoylenko/wwebjs-api/blob/main/README.md Set the API_KEY environment variable to secure REST endpoints in a production environment. ```bash Set the `API_KEY` environment variable to protect the REST endpoints ``` -------------------------------- ### Monitor Docker Compose Logs Source: https://context7.com/avoylenko/wwebjs-api/llms.txt This command streams logs from your Docker Compose services, useful for checking QR codes or debugging session startup. ```bash docker compose logs -f ``` -------------------------------- ### Session Management Source: https://github.com/avoylenko/wwebjs-api/blob/main/README.md Actions related to managing WhatsApp sessions. ```APIDOC ## Initiate Session ### Description Initiates a new WhatsApp session. ### Method POST ### Endpoint /initiateSession ### Parameters #### Request Body - **sessionId** (string) - Required - A unique identifier for the session. ``` ```APIDIDOC ## Terminate Session ### Description Terminates an active WhatsApp session. ### Method POST ### Endpoint /terminateSession ### Parameters #### Request Body - **sessionId** (string) - Required - The ID of the session to terminate. ``` ```APIDOC ## Terminate Inactive Sessions ### Description Terminates all sessions that have been inactive for a specified duration. ### Method POST ### Endpoint /terminateInactiveSessions ### Parameters #### Request Body - **maxInactiveMinutes** (number) - Required - The maximum inactivity period in minutes. ``` ```APIDOC ## Terminate All Sessions ### Description Terminates all active WhatsApp sessions. ### Method POST ### Endpoint /terminateAllSessions ``` ```APIDOC ## Restart Session ### Description Restarts a specific WhatsApp session. ### Method POST ### Endpoint /restartSession ### Parameters #### Request Body - **sessionId** (string) - Required - The ID of the session to restart. ``` ```APIDOC ## Get Session Status ### Description Retrieves the status of a specific WhatsApp session. ### Method GET ### Endpoint /getSessionStatus ### Parameters #### Query Parameters - **sessionId** (string) - Required - The ID of the session. ``` ```APIDOC ## Health Check ### Description Performs a health check on the API and its connected WhatsApp sessions. ### Method GET ### Endpoint /healthCheck ``` -------------------------------- ### Download Media as Data Source: https://context7.com/avoylenko/wwebjs-api/llms.txt Downloads media associated with a specific message as raw binary data. ```APIDOC ## POST /message/downloadMediaAsData/:sessionId ### Description Downloads media associated with a specific message as raw binary data. ### Method POST ### Endpoint /message/downloadMediaAsData/acme-support ### Parameters #### Request Body - **chatId** (string) - Required - The ID of the chat containing the message. - **messageId** (string) - Required - The ID of the message with the media to download. ### Request Example ```json { "chatId": "6281288888888@c.us", "messageId": "3A80E857F9B44AF60C2C" } ``` ### Response #### Success Response (200) - **Binary Data** - The raw binary content of the media file. ``` -------------------------------- ### Promote Participants to Admin Source: https://context7.com/avoylenko/wwebjs-api/llms.txt Promotes specified participants to admin roles within a group. Requires chatId and a list of participantIds. ```bash curl -X POST \ -H "x-api-key: my-secret-key" \ -H "Content-Type: application/json" \ -d '{"chatId":"XXXXXXXXXX@g.us","participantIds":["6281288888887@c.us"]}' \ http://localhost:3000/groupChat/promoteParticipants/acme-support # Response: {"success":true,"result":{...}} ``` -------------------------------- ### Nginx Configuration for WWebJS API Source: https://github.com/avoylenko/wwebjs-api/blob/main/REVERSE_PROXY_SETUP.md Configure Nginx as a reverse proxy, including WebSocket support and appropriate headers for IP forwarding and connection management. ```nginx upstream wwebjs_backend { server wwebjs-api:3000; } server { listen 80; server_name api.yourdomain.com; location /api/v1/whatsapp/ { proxy_pass http://wwebjs_backend/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-Host $host; # WebSocket support proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; # Timeouts for long-running operations proxy_connect_timeout 60s; proxy_send_timeout 60s; proxy_read_timeout 60s; } } ``` -------------------------------- ### Request Pairing Code for Session Authentication Source: https://context7.com/avoylenko/wwebjs-api/llms.txt Use this endpoint to request a pairing code for authenticating via phone number. The user will enter this code in WhatsApp mobile. ```bash curl -X POST \ -H "x-api-key: my-secret-key" \ -H "Content-Type: application/json" \ -d '{"phoneNumber":"12025550108","showNotification":true}' \ http://localhost:3000/session/requestPairingCode/acme-support # Response: {"success":true,"result":"123-456"} ``` -------------------------------- ### Retrieve All Contacts Source: https://context7.com/avoylenko/wwebjs-api/llms.txt Fetches all contacts associated with the session. The response includes contact details like ID and name. ```bash curl -H "x-api-key: my-secret-key" \ http://localhost:3000/client/getContacts/acme-support # Response: {"success":true,"contacts":[{"id":{"user":"6281288888888","server":"c.us","_serialized":"6281288888888@c.us"},"name":"Alice",...}]} ``` -------------------------------- ### List All Active Session IDs Source: https://context7.com/avoylenko/wwebjs-api/llms.txt Retrieves a list of all currently active session IDs. Useful for monitoring or managing multiple active sessions. ```bash curl -H "x-api-key: my-secret-key" \ http://localhost:3000/session/getSessions # Response: {"success":true,"result":["acme-support","acme-sales"]} ``` -------------------------------- ### Download media from a message Source: https://context7.com/avoylenko/wwebjs-api/llms.txt Downloads the media content from a specific WhatsApp message. ```APIDOC ## POST /message/downloadMedia/:sessionId — Download media from a message ### Description Downloads the media content from a specific WhatsApp message. ### Method POST ### Endpoint /message/downloadMedia/:sessionId ### Parameters #### Path Parameters - **sessionId** (string) - Required - The session ID for the client. #### Request Body - **chatId** (string) - Required - The ID of the chat containing the message. - **messageId** (string) - Required - The ID of the message containing the media. ### Request Example ```bash curl -X POST \ -H "x-api-key: my-secret-key" \ -H "Content-Type: application/json" \ -d '{"chatId":"6281288888888@c.us","messageId":"3A80E857F9B44AF60C2C"}' \ http://localhost:3000/message/downloadMedia/acme-support ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. - **messageMedia** (object) - Contains the downloaded media details. - **data** (string) - The base64 encoded media data. - **mimetype** (string) - The MIME type of the media. - **filename** (string) - The original filename of the media. #### Response Example ```json { "success": true, "messageMedia": { "data": "", "mimetype": "image/jpeg", "filename": "photo.jpg" } } ``` ``` -------------------------------- ### Health Check Endpoint Source: https://context7.com/avoylenko/wwebjs-api/llms.txt Use this lightweight endpoint to verify if the WWebJS REST API server is running. It requires no authentication and returns a simple 'pong' response. ```bash curl http://localhost:3000/ping # Response: {"success":true,"result":"pong"} ``` -------------------------------- ### Send Location Message Source: https://context7.com/avoylenko/wwebjs-api/llms.txt Sends a location message with latitude, longitude, and an optional description. The `contentType` should be `Location`. ```bash curl -X POST \ -H "x-api-key: my-secret-key" \ -H "Content-Type: application/json" \ -d '{"chatId":"6281288888888@c.us","contentType":"Location","content":{"latitude":-6.2,"longitude":106.8,"description":"Jakarta Office"}}' \ http://localhost:3000/client/sendMessage/acme-support ``` -------------------------------- ### Send a Message to a Channel using REST API Source: https://context7.com/avoylenko/wwebjs-api/llms.txt Use this endpoint to post a message to a specific channel. Requires session ID, channel ID, content type, and message content. ```bash curl -X POST \ -H "x-api-key: my-secret-key" \ -H "Content-Type: application/json" \ -d '{"chatId":"XXXXXXXXXX@newsletter","contentType":"string","content":"New product launch tomorrow!"}' \ http://localhost:3000/channel/sendMessage/acme-support # Response: {"success":true,"message":{...}} ``` -------------------------------- ### Testing WebSocket Connection with Wscat Source: https://github.com/avoylenko/wwebjs-api/blob/main/REVERSE_PROXY_SETUP.md Use wscat to test WebSocket connections to your WWebJS API behind the reverse proxy. Ensure the URL uses wss and includes the base path. ```bash # Test WebSocket connection wscat -c wss://api.yourdomain.com/api/v1/whatsapp/ws/test ``` -------------------------------- ### Restart Session Source: https://context7.com/avoylenko/wwebjs-api/llms.txt Restarts a session by destroying and re-initializing the browser process using saved credentials. ```APIDOC ## GET /session/restart/:sessionId — Restart a session (keep auth data) Destroys the browser process and re-initializes the client using the existing saved credentials — useful for recovering from a stuck state without logging out. ### Method GET ### Endpoint /session/restart/:sessionId ### Parameters #### Path Parameters - **sessionId** (string) - Required - The ID of the session to restart. ``` -------------------------------- ### Search for channels Source: https://context7.com/avoylenko/wwebjs-api/llms.txt Enables searching for channels based on provided search criteria. The session ID is used to identify the client context. ```APIDOC ## POST /client/searchChannels/:sessionId — Search for channels ### Description Enables searching for channels based on provided search criteria. The session ID is used to identify the client context. ### Method POST ### Endpoint /client/searchChannels/:sessionId #### Request Body - **searchOptions** (object) - Required - Options for searching channels. - **searchText** (string) - Required - The text to search for. - **countryCodes** (array) - Optional - An array of country codes to filter by. - **skipSubscribedNewsletters** (boolean) - Optional - Whether to skip already subscribed newsletters. - **limit** (integer) - Optional - The maximum number of results to return. ### Request Example ```json { "searchOptions":{ "searchText":"news", "countryCodes":["US"], "skipSubscribedNewsletters":true, "limit":10 } } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. - **result** (array) - A list of channels matching the search criteria. ``` -------------------------------- ### Add Participants to a Group Source: https://context7.com/avoylenko/wwebjs-api/llms.txt Adds one or more participants to a group chat. Requires chatId and a list of participantIds. Optional sleep options can be provided. ```bash curl -X POST \ -H "x-api-key: my-secret-key" \ -H "Content-Type: application/json" \ -d '{ "chatId": "XXXXXXXXXX@g.us", "participantIds": ["6281288888887@c.us","6281288888886@c.us"], "options": {"sleep":[250,500]} }' \ http://localhost:3000/groupChat/addParticipants/acme-support # Response: {"success":true,"result":{"6281288888887@c.us":{"code":200},...}} ``` -------------------------------- ### Subscribe to a channel Source: https://context7.com/avoylenko/wwebjs-api/llms.txt Allows a client to subscribe to a specific channel using the provided session ID. Requires channel ID in the request body. ```APIDOC ## POST /client/subscribeToChannel/:sessionId — Subscribe to a channel ### Description Allows a client to subscribe to a specific channel using the provided session ID. Requires channel ID in the request body. ### Method POST ### Endpoint /client/subscribeToChannel/:sessionId #### Request Body - **channelId** (string) - Required - The ID of the channel to subscribe to. ### Request Example ```json { "channelId":"XXXXXXXXXX@newsletter" } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the operation was successful. - **result** (boolean) - The result of the subscription operation. ``` -------------------------------- ### Send Image Message from URL Source: https://context7.com/avoylenko/wwebjs-api/llms.txt Sends an image from a URL to a specified chat ID. Includes an optional caption. The `contentType` should be `MessageMediaFromURL`. ```bash curl -X POST \ -H "x-api-key: my-secret-key" \ -H "Content-Type: application/json" \ -d '{"chatId":"6281288888888@c.us","contentType":"MessageMediaFromURL","content":"https://example.com/photo.jpg","options":{"caption":"Look at this!"}}' \ http://localhost:3000/client/sendMessage/acme-support ```