WuzAPI Documentation

repository·main·Indexed 21 days ago

https://github.com/asternic/wuzapi

A RESTful API service implementing the whatsmeow library for high-performance WhatsApp automation. WuzAPI supports multiple concurrent sessions, webhooks with HMAC security, RabbitMQ integration, and S3 media storage. It provides endpoints for session management, sending various message types (text, template, media), managing users and groups, and configuring account privacy settings.

Tokens
31K
Snippets
112
Records
148
Agent score
74%

What's inside wuzapi

  1. Verify Webhook HMAC Signatures

    main

    When HMAC is configured, WuzAPI includes an x-hmac-signature header (SHA-256) in all webhooks. You should always verify this signature before processing the payload.

    Signature Generation Rules:

    Content-TypeSigned DataVerification Method
    application/jsonRaw JSON request bodyUse the exact JSON received
    application/x-www-form-urlencodedURL-encoded form stringReconstruct the form string from parameters
    multipart/form-dataJSON of form fields (excluding files)Create JSON from non-file form fields

    HMAC Priority:

    1. Per-instance HMAC (configured via API/Dashboard)
    2. Global HMAC (WUZAPI_GLOBAL_HMAC_KEY)
    3. No signature
  2. Authenticate with WUZAPI API

    main

    WUZAPI uses two types of authentication via the Authorization header:

    1. User Token: Use the specific user's token for regular endpoints (e.g., /session/*, /user/*, /webhook/*).
    2. Admin Token: Use the admin token (configured via WUZAPI_ADMIN_TOKEN) for management endpoints under the /admin/** path.

    All requests must include Content-Type: application/json for JSON-encoded bodies.

  3. S3 Media File Organization and Webhook Payload

    main

    File Structure

    Media files are organized in the bucket using the following pattern: users/{user_id}/{inbox|outbox}/{contact_jid}/{year}/{month}/{day}/{media_type}/{message_id}.{ext}

    Webhook Payload with S3

    Depending on your media_delivery setting, the webhook payload will include an s3 object:

    If media_delivery is "s3":

    • The payload contains the s3 object with url, key, bucket, size, mimeType, and fileName.
    • The base64 field is omitted.

    If media_delivery is "both":

    • The payload contains both the base64 string and the s3 object.
    // Example S3 payload (media_delivery: "s3")
    {
      "event": { "Info": { ... }, "Message": { ... } },
      "s3": {
        "url": "https://my-bucket.s3.us-east-1.amazonaws.com/users/abc123/inbox/...",
        "key": "users/abc123/inbox/5491155553934/2024/12/25/images/3EB06F9067F80BAB89FF.jpg",
        "bucket": "my-bucket",
        "size": 245632,
        "mimeType": "image/jpeg",
        "fileName": "3EB06F9067F80BAB89FF.jpg"
      }
    }
  4. Secure Webhooks with HMAC

    main

    To verify that incoming webhooks are authentic and untampered, you can configure HMAC signing. WUZAPI uses SHA-256 HMAC.

    Security Requirements

    • HMAC keys must be at least 32 characters long.
    • Once saved, the key cannot be retrieved or viewed via the API.
    • All webhooks will include an x-hmac-signature header.

    Signature Generation by Content-Type

    • application/json: Sign the raw JSON request body.
    • application/x-www-form-urlencoded: Sign the URL-encoded form string.
    • multipart/form-data: Sign a JSON representation of the form fields (excluding files).

    HMAC Management

    • Configure: POST /session/hmac/config with {"hmac_key": "..."}.
    • Status: GET /session/hmac/config returns whether it is configured (the key is masked as ***).
    • Delete: DELETE /session/hmac/config removes the key and disables signing.
    # Configure HMAC Key
    curl -s -X POST -H 'Authorization: 1234ABCD' -H 'Content-Type: application/json' --data '{"hmac_key":"your_hmac_key_minimum_32_characters_long_here"}' http://localhost:8080/session/hmac/config
    
    # Get Status
    curl -s -X GET -H 'Authorization: 1234ABCD' http://localhost:8080/session/hmac/config
    
    # Delete Configuration
    curl -s -X DELETE -H 'Authorization: 1234ABCD' http://localhost:8080/session/hmac/config
  5. Install and Run WuzAPI

    main

    WuzAPI can be installed via Homebrew or built from source using Go. It provides a RESTful API for WhatsApp communication using the whatsmeow library.

    Installation

    Via Homebrew:

    brew install asternic/wuzapi/wuzapi

    Via Go (Build from source):

    go build .

    Running the service

    By default, WuzAPI starts a REST service on port 8080. You can customize its behavior using CLI flags.

    Common CLI Flags:

    • -admintoken: Sets the authentication token for admin endpoints (overrides .env).
    • -address: IP address to bind to (default 0.0.0.0).
    • -port: Port number (default 8080).
    • -logtype: Log format: console (default) or json.
    • -color: Enable colored output for console logs.
    • -skipmedia: Skip downloading media from messages.
    • -wadebug: Enable whatsmeow debug levels (INFO or DEBUG).
    • -sslcertificate / -sslprivatekey: Path to SSL certificate and private key files.

    Examples:

    # Run with colored console logs
    ./wuzapi -logtype=console -color=true
    
    # Run with JSON logs
    ./wuzapi -logtype json
    brew install asternic/wuzapi/wuzapi
  6. Configure Webhook Format via Environment Variable

    main

    You can control how WuzAPI sends webhook data using the WEBHOOK_FORMAT environment variable. This is useful for switching between legacy form-encoded systems and modern JSON integrations.

    Options

    • form (default): Sends data as application/x-www-form-urlencoded. The JSON payload is in the jsonData field and the security token is in the token field.
    • json: Sends data as application/json. The full event JSON is the body, and the token field is included inside the JSON object.

    Setup

    Set the variable in your terminal before starting the service:

    export WEBHOOK_FORMAT=json
  7. Choose between HTTP and Stdio server modes

    main

    WuzAPI can run in two distinct modes defined by the -mode flag:

    1. HTTP Mode (-mode http): The default mode. Starts an HTTP server listening on the configured address and port. This mode is used for standard API interactions and webhook deliveries.
    2. Stdio Mode (-mode stdio): Starts a server that communicates via standard input/output. In this mode, logs are redirected to stderr to prevent interference with JSON responses on stdout.
    # Run as an HTTP server
    ./wuzapi -mode http -port 8080
    
    # Run in Stdio mode
    ./wuzapi -mode stdio
  8. Manage S3 operations with S3Manager

    main

    The S3Manager is the central authority for handling S3-related tasks. It maintains a registry of S3 clients and configurations mapped to user IDs. It supports lazy initialization from a database and provides high-level methods for media processing.

    Core workflow:

    1. Access the global instance via GetS3Manager().
    2. Provide a database connection via SetDB(db *sqlx.DB) to allow the manager to load configurations automatically.
    3. Use ProcessMediaForS3 to handle the full lifecycle of a media upload.
    var s3Manager = &S3Manager{
    	clients: make(map[string]*s3.Client),
    	configs: make(map[string]*S3Config),
    }
    
    func GetS3Manager() *S3Manager {
    	return s3Manager
    }
  9. Configure User Proxy and S3 Storage

    main

    When creating a user via POST /admin/users, you can include proxyConfig and s3Config objects to customize their environment.

    proxyConfig options:

    • enabled (boolean): Enable proxy for this user.
    • proxyURL (string): Proxy URL (e.g., socks5://user:pass@host:port).

    s3Config options:

    • enabled (boolean): Enable S3 storage.
    • endpoint (string): S3 endpoint URL.
    • region (string): S3 region.
    • bucket (string): S3 bucket name.
    • accessKey (string): S3 access key.
    • secretKey (string): S3 secret key.
    • pathStyle (boolean): Use path style addressing.
    • publicURL (string): Public URL for accessing files.
    • mediaDelivery (string): Delivery type (base64, s3, or both).
    • retentionDays (integer): Number of days to retain files.
    {
      "name": "test_user",
      "token": "user_token",
      "proxyConfig": {
        "enabled": true,
        "proxyURL": "socks5://user:pass@host:port"
      },
      "s3Config": {
        "enabled": true,
        "endpoint": "https://s3.amazonaws.com",
        "region": "us-east-1",
        "bucket": "my-bucket",
        "accessKey": "AKIAIOSFODNN7EXAMPLE",
        "secretKey": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
        "pathStyle": false,
        "publicURL": "https://cdn.yoursite.com",
        "mediaDelivery": "both",
        "retentionDays": 30
      }
    }
  10. Handle JSON-RPC notifications (Webhooks)

    main

    In stdio mode, Wuzapi uses the standard output stream to emit notifications (one-way messages that do not require a response). This is primarily used to implement webhooks.

    When an event occurs, Wuzapi writes a jsonRpcNotification object to stdout. These objects do not contain an id field.

    {
      "jsonrpc": "2.0",
      "method": "webhook.event_name",
      "params": {
        "some_key": "some_value"
      }
    }
  11. Database migration structure and sequence

    main

    The system uses a Migration struct to define schema changes. Migrations are applied in order of their ID.

    Migration Schema:

    • ID: Unique integer identifier.
    • Name: Descriptive name of the migration.
    • UpSQL: The SQL command to apply the change (primarily used for PostgreSQL).
    • DownSQL: The SQL command to revert the change (not implemented in the current migration list).
  12. Process incoming media messages

    main

    When a Message event containing media is received, wuzapi can automatically process and deliver it. The system supports:

    • Image Messages (.jpg)
    • Audio Messages (.ogg)
    • Document Messages (extracts extension from filename, defaults to .bin)
    • Video Messages (.mp4)
    • Sticker Messages (.webp, including animation status)

    Media delivery can be configured via media_delivery settings (e.g., s3, base64, or both) and can be integrated with S3 for storage.