Chatery WhatsApp API

repository·main·Indexed 41 days ago

https://github.com/farinchan/chatery_whatsapp

A WhatsApp backend built with Express.js and Baileys (version 1.2.0) for managing multiple sessions, sending various message types, and handling groups in real-time. It features a web-based admin dashboard, WebSocket support for real-time events, bulk messaging background jobs, and support for WhatsApp Business labels.

Tokens
15.1K
Snippets
51
Records
63
Agent score
53%

What's inside Chatery WhatsApp API

  1. Configure and Manage Webhooks

    main

    Webhooks allow you to receive WhatsApp events via POST requests to your own server. You can configure multiple webhooks per session, each subscribing to specific events.

    Setup and Management

    • Create Session with Webhooks: When connecting a session, include a webhooks array in the body. Use "events": ["all"] to receive every event.
    • Add a Webhook: POST /api/whatsapp/sessions/{sessionId}/webhooks
    • Remove a Webhook: DELETE /api/whatsapp/sessions/{sessionId}/webhooks
    • Update All Webhooks: PATCH /api/whatsapp/sessions/{sessionId}/config

    Webhook Payload Format

    {
      "event": "message",
      "sessionId": "mysession",
      "metadata": { "userId": "123" },
      "data": { "id": "ABC123", "text": "Hello!" },
      "timestamp": "2024-01-15T10:30:00.000Z"
    }

    Webhook Headers

    • Content-Type: application/json
    • X-Webhook-Source: chatery-whatsapp-api
    • X-Session-Id: <sessionId>
    • X-Webhook-Event: <eventName>

    Available Events

    • connection.update (connected, disconnected)
    • message (new message received)
    • message.sent (message sent confirmation)
    • Or use "all" to subscribe to everything.
    # Add a webhook to an 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"]
      }'
  2. Install Chatery WhatsApp API via Docker

    main

    To run the API using Docker Compose, follow these steps:

    1. Clone the repository.
    2. Create a .env file from the example.
    3. Build and run the containers in the background.

    Docker Management Commands:

    • 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

    Persisted Data (Volumes):

    • chatery_sessions (/app/sessions): WhatsApp session data
    • chatery_media (/app/public/media): Received media files
    • chatery_store (/app/store): Message history store
    # 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
  3. Use the Admin Dashboard

    main

    The web-based dashboard is available at http://localhost:3000/dashboard. It allows for real-time monitoring and API testing.

    Authentication: Use the DASHBOARD_USERNAME and DASHBOARD_PASSWORD configured in your .env file.

    Key Features:

    • Session Management: Create, connect, reconnect, and delete sessions.
    • QR Code Scanner: Scan QR codes directly from the UI.
    • Live Events: View real-time WebSocket events with filtering.
    • API Tester: Test all 40+ API endpoints with pre-filled templates.
    • Bulk Messaging: Track background jobs for sending messages to multiple recipients.
    • Webhook Manager: Configure webhooks per session.
  4. Install Chatery WhatsApp API via Standard Installation

    main

    To install the API directly on your host machine, follow these steps:

    1. Clone the repository.
    2. Install dependencies using npm.
    3. Create a .env file from the example.
    4. Start the server.

    You can also run in development mode with auto-reload.

    # 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
  5. Use WebSockets for Real-time WhatsApp Events

    main

    Connect to the WebSocket server at ws://localhost:3000 to receive real-time updates. You must subscribe to a specific session to receive events for that session.

    Connection Lifecycle

    1. Connect to the server using a Socket.io client.
    2. Emit the subscribe event with your sessionId.
    3. To stop receiving updates, emit the unsubscribe event.

    Supported Events

    EventDescriptionPayload
    qrQR code generated{ sessionId, qrCode, timestamp }
    connection.updateConnection status changed{ sessionId, status, phoneNumber?, name?, timestamp }
    messageNew message received{ sessionId, message, timestamp }
    message.sentMessage sent confirmation{ sessionId, message, timestamp }
    message.updateMessage status update (read, delivered){ sessionId, update, timestamp }
    message.reactionMessage reaction added{ sessionId, reactions, timestamp }
    message.revokeMessage deleted/revoked{ sessionId, key, participant, timestamp }
    chat.updateChat updated{ sessionId, chats, timestamp }
    chat.upsertNew chat created{ sessionId, chats, timestamp }
    chat.deleteChat deleted{ sessionId, chatIds, timestamp }
    contact.updateContact updated{ sessionId, contacts, timestamp }
    presence.updateTyping, online status{ sessionId, presence, timestamp }
    group.participantsGroup members changed{ sessionId, update, timestamp }
    group.updateGroup info changed{ sessionId, update, timestamp }
    callIncoming call{ sessionId, call, timestamp }
    labelsLabels updated (business){ sessionId, labels, timestamp }
    logged.outSession logged out{ sessionId, message, timestamp }

    Testing

    An interactive WebSocket testing interface is available at http://localhost:3000/ws-test.

    import { io } from 'socket.io-client';
    
    const socket = io('http://localhost:3000');
    
    // Subscribe to a session
    socket.emit('subscribe', 'mysession');
    
    // Listen for messages
    socket.on('message', (data) => {
      console.log('New message:', data.message);
    });
    
    // Unsubscribe from a session
    socket.emit('unsubscribe', 'mysession');
  6. Authenticate API requests with X-Api-Key

    main

    All WhatsApp API endpoints are protected. You must include the X-Api-Key header in your requests using the value defined in your .env file.

    Error Responses:

    • 401: Missing X-Api-Key header.
    • 403: Invalid API key.

    Example Request:

    curl -X GET http://localhost:3000/api/whatsapp/sessions \
      -H "X-Api-Key: your_secret_api_key_here"
  7. Quick Start: Connect a session and send a message

    main

    Follow these steps to get your first WhatsApp session running and send a text message:

    1. Start the server: npm start.
    2. Initiate connection: Call the /connect endpoint for a specific session ID.
    3. Scan QR Code: Access the QR image endpoint in a browser to scan with WhatsApp.
    4. Send Message: Use the /send-text endpoint.

    Note on IDs:

    • Personal chat IDs use @c.us format (e.g., 628123456789@c.us).
    • Group IDs use @g.us format.
    • Phone numbers are automatically normalized (e.g., 0 becomes 62).
    # 1. Create 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"
    
    # 2. Get QR Code (Open in browser or use curl)
    # http://localhost:3000/api/whatsapp/sessions/mysession/qr/image
    
    # 3. 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!"}'
  8. How session-based broadcasting works

    main

    The WebSocketManager uses a room-based pattern to isolate real-time updates to specific WhatsApp sessions.

    1. Subscription: Clients must emit a subscribe event with a sessionId to join a specific room (session:${sessionId}).
    2. Isolation: When the server calls emitToSession(sessionId, event, data), the event is only sent to clients currently subscribed to that specific sessionId.
    3. Unsubscription: Clients can leave a session by emitting unsubscribe with the sessionId.
    4. Lifecycle: If a client disconnects, the manager automatically removes them from all session rooms to prevent memory leaks.
    // Client-side subscription example (Socket.io client)
    socket.emit('subscribe', 'my-session-id-123');
    
    socket.on('subscribed', (data) => {
      console.log(data.message);
    });
  9. Manage WhatsApp sessions with WhatsAppManager

    main

    The WhatsAppManager class is a singleton responsible for managing multiple WhatsApp sessions. It handles session persistence by storing session data in a ./sessions directory relative to the current working directory.

    Key capabilities include:

    • Automatic Restoration: On startup, the manager scans the ./sessions folder and automatically reconnects any existing sessions found.
    • Session Creation: Create new sessions or reconnect existing ones using a unique sessionId.
    • Session Lifecycle: Create, retrieve, delete, and monitor the status of multiple WhatsApp connections.

    Session ID Constraints: Session IDs must be alphanumeric and can only contain underscores (_) or dashes (-).

  10. Configure Chatery WhatsApp API environment variables

    main

    Create a .env file in the root directory to configure the server.

    Available Keys:

    • PORT: The port the server will run on (default: 3000).
    • CORS_ORIGIN: Allowed origins for CORS (default: *).
    • DASHBOARD_USERNAME: Username for the web dashboard.
    • DASHBOARD_PASSWORD: Password for the web dashboard.
    • API_KEY: The secret key required for all API requests. To disable authentication, leave this empty or set it to your_api_key_here.
    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
  11. Use BaileysStore for managing WhatsApp session and state

    main

    The BaileysStore class is an in-memory data store designed to manage WhatsApp session data, including chats, contacts, messages, group metadata, and labels. It is optimized with pre-computed caches for fast querying of chat overviews and contacts. It also supports identity resolution (mapping LIDs to JIDs/Phone Numbers) and persistence to a file.

    const store = new BaileysStore('my-session-id');
  12. Start the Chatery WhatsApp API server

    main

    The application is an Express-based server that integrates RESTful APIs, WebSockets, and a dashboard. To run the server, ensure your environment variables are configured and execute the entrypoint. The server listens on a port defined by process.env.PORT (defaulting to 3000).

    Key features initialized on startup:

    • REST API: Available at /api/whatsapp (requires API Key authentication).
    • WebSockets: Managed via WebSocketManager for real-time communication.
    • API Documentation: Swagger UI is served at the root / path.
    • Dashboard: A web dashboard is available at /dashboard.
    • Media Access: Static files are served from /media.
    node index.js