Description

The WhatsApp integration routes inbound WhatsApp messages into Kommander conversations, runs the configured assistant, and sends replies back through the selected WhatsApp provider. Production deployments should use Meta Cloud API webhooks. The Baileys bridge is available for development, demos, and controlled deployments that can maintain a live paired session.

Kommander currently uses these WhatsApp routes:

RoutePurpose
GET /api/meta/[userId]Meta webhook challenge verification.
POST /api/meta/[userId]Meta Cloud API inbound message ingress.
POST /api/meta/replySends assistant or operator replies through Meta Graph API.
GET /api/whatsapp/config/[userId]Reads masked WhatsApp provider configuration for an organization.
POST /api/whatsapp/config/[userId]Stores Meta and Twilio WhatsApp credentials for an organization.
POST /api/whatsapp/startStarts a Baileys session and returns a QR code when pairing is required.
GET /api/whatsapp/statusReads Baileys connection status.
POST /api/whatsapp/stopStops the active Baileys session and removes local auth state.

Prerequisites

  • A Kommander organization with a trained assistant.
  • A public HTTPS deployment URL that Meta can reach.
  • A WhatsApp Business account connected to a Meta app for Cloud API.
  • A Meta verify token stored on the Kommander organization as whatsappVerifyToken.
  • A Meta permanent or long-lived access token stored through the WhatsApp settings screen.
  • A WhatsApp phone number ID stored as metaWhatsappNumberId.
  • The App Secret of the Meta app, stored encrypted as metaAppSecret, so Kommander can verify webhook signatures.
  • Optional: a Baileys-compatible runtime that can keep a Node.js process and auth state alive for session bridge usage.

Meta Webhook Setup

Representative WhatsApp integration setup screen with webhook URL, verify token, access token, and phone number ID.
WhatsApp setup captures the Meta webhook URL, verify token, access token, phone number ID, and Baileys session status.
  1. Open Integrations > WhatsApp in Kommander.
  2. Select the Meta provider and save the Meta access token, WhatsApp phone number ID and Meta App Secret (Meta Developer Dashboard > App settings > Basic > App Secret).
  3. Copy the organization webhook URL:
https://YOUR_DOMAIN/api/meta/YOUR_ORGANIZATION_ID
  1. In the Meta Developer Dashboard, open the app that owns the WhatsApp Business account.
  2. Add the callback URL from step 3 to the WhatsApp webhook configuration.
  3. Paste the same verify token stored in Kommander. During setup, Meta calls GET /api/meta/[userId] with hub.mode=subscribe, hub.verify_token, and hub.challenge; Kommander returns the challenge only when the token matches the organization.
  4. Subscribe the app to WhatsApp message events for the WhatsApp Business account.
  5. Send a test message from a real WhatsApp user that is not the same sender number. Confirm a Kommander conversation appears with site: "whatsapp" and provider: "meta".

WhatsApp Ingress Diagram

The ingress flow receives provider webhooks, normalizes the message, reuses the WhatsApp RAG trigger, and lets the reply callback send the final provider response.

Message Flow

Meta Configuration

SettingRequiredNotes
whatsappVerifyTokenYesStored on the organization and used only for the Meta webhook subscription challenge.
Meta access tokenYesStored encrypted by /api/whatsapp/config/[userId] when it is not already masked.
metaWhatsappNumberIdYesUsed by /api/meta/reply as the Graph API sender path segment.
metaAppSecretYesApp Secret of the Meta app. POST /api/meta/[userId] verifies X-Hub-Signature-256 with it and rejects unsigned or tampered requests once it is saved.
META_WEBHOOK_SIGNATURE_REQUIREDOptionalWebhooks from organizations that have not saved an App Secret are rejected by default. Set to false only as a temporary opt-out while organizations migrate.
Webhook URLYesMust be public HTTPS and include the organization ID in /api/meta/[userId].
NEXT_PUBLIC_BASE_URL or APP_URL_DEVYesUsed to build the internal RAG trigger and reply callback URLs.
INTERNAL_API_SECRETRequired for operator append flowUsed when /api/meta/reply appends an agent message to a conversation.

Baileys Configuration

Baileys connects by pairing a WhatsApp account through a QR code. Use it only when the deployment can keep the process and auth files available; serverless runtimes may lose /tmp state between cold starts.

Setting or behaviorCurrent configuration
Auth storagewhatsapp-auth-${userId} under process.cwd() in development or /tmp in production/serverless.
PairingPOST /api/whatsapp/start creates a socket and returns qrCode when WhatsApp pairing is required.
StatusGET /api/whatsapp/status returns isConnected, phoneNumber, lastActivity, and optional qrCode.
StopPOST /api/whatsapp/stop ends the socket and removes the auth directory.
Socket authuseMultiFileAuthState(authPath).
Browser identity['Chrome (Linux)', '', ''].
History syncDisabled with syncFullHistory: false and shouldSyncHistoryMessage: () => false.
Online statemarkOnlineOnConnect: false.
Link previewsgenerateHighQualityLinkPreview: false.
Message supportText from conversation and extendedTextMessage.text; status broadcasts, messages from the bot, empty messages, and groups are ignored.

The implemented Baileys socket is configured like this:

const sock = makeWASocket({ auth: state, printQRInTerminal: false, logger, browser: ['Chrome (Linux)', '', ''], markOnlineOnConnect: false, generateHighQualityLinkPreview: false, syncFullHistory: false, shouldSyncHistoryMessage: () => false, });

Baileys message handling is intentionally narrow for this integration. Do not rely on media, templates, buttons, reactions, group messages, or advanced session management unless a future task explicitly expands the supported surface.

Webhook Payload Example

Meta Cloud API message events arrive under entry[].changes[].value.messages[]. Kommander reads the first text message, the sender phone number, and metadata.display_phone_number before forwarding the normalized payload to /api/kommander-rag-trigger-whatsapp.

{ "object": "whatsapp_business_account", "entry": [ { "id": "123456789", "changes": [ { "field": "messages", "value": { "metadata": { "display_phone_number": "390212345678", "phone_number_id": "987654321" }, "messages": [ { "from": "393331234567", "id": "wamid.HBgMMz...", "timestamp": "1717420440", "type": "text", "text": { "body": "Do you have appointments tomorrow?" } } ] } } ] } ] }

Webhook Handler Example

The current Meta ingress route reads JSON, extracts the first message, finds or creates a conversation ID by sender number, and forwards a normalized request to the WhatsApp RAG trigger.

import { NextRequest, NextResponse } from 'next/server'; export async function POST( request: NextRequest, { params }: { params: Promise<{ userId: string }> }, ) { const { userId } = await params; const payload = await request.json(); const value = payload.entry?.[0]?.changes?.[0]?.value; const message = value?.messages?.[0]; if (!message?.text?.body) { return NextResponse.json({ ok: true, info: 'No text message in payload' }); } await fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/kommander-rag-trigger-whatsapp`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ userId, message: message.text.body, conversationId: `konv-${Date.now()}`, topK: 3, site: 'whatsapp', provider: 'meta', userNumber: message.from, organizationNumber: value.metadata?.display_phone_number, handledBy: 'bot', }), }); return NextResponse.json({ ok: true }); }

Webhook Signature Verification

Meta webhook delivery can include X-Hub-Signature-256, which is an HMAC-SHA256 signature of the raw request body using the Meta app secret. Verify the signature before parsing JSON, preserve the exact raw body bytes, and use a timing-safe comparison.

import { createHmac, timingSafeEqual } from 'crypto'; import { NextRequest, NextResponse } from 'next/server'; function verifyMetaSignature(rawBody: string, signatureHeader: string | null, appSecret: string) { if (!signatureHeader?.startsWith('sha256=')) return false; const expected = createHmac('sha256', appSecret) .update(rawBody, 'utf8') .digest('hex'); const received = signatureHeader.slice('sha256='.length); const expectedBuffer = Buffer.from(expected, 'hex'); const receivedBuffer = Buffer.from(received, 'hex'); return ( expectedBuffer.length === receivedBuffer.length && timingSafeEqual(expectedBuffer, receivedBuffer) ); } export async function POST(request: NextRequest) { const rawBody = await request.text(); const signature = request.headers.get('x-hub-signature-256'); if (!verifyMetaSignature(rawBody, signature, process.env.META_APP_SECRET ?? '')) { return NextResponse.json({ error: 'signature_invalid' }, { status: 401 }); } const payload = JSON.parse(rawBody); return NextResponse.json({ ok: true, object: payload.object }); }

Keep challenge verification and delivery signature verification separate:

  • GET /api/meta/[userId] validates hub.verify_token during subscription setup.
  • POST /api/meta/[userId] should validate X-Hub-Signature-256 before trusting production webhook payloads.

Rate Limiting Considerations

  • Meta applies WhatsApp Business Platform throughput and quality limits by phone number and business account. Watch send failures from /api/meta/reply and reduce automated reply volume when Meta returns rate or quality errors.
  • Webhook handlers should return quickly. If assistant generation becomes slow, acknowledge the provider event and move generation to a queue or background workflow so Meta does not retry the same delivery.
  • Treat Meta webhook deliveries as at-least-once. Use the provider message ID (wamid...) as an idempotency key before creating duplicate conversation turns.
  • Apply per-organization and per-sender limits before calling the RAG trigger to protect OpenAI, tools, and database capacity from message bursts.
  • Keep a separate limit for outbound replies. A busy conversation can produce multiple internal events, but WhatsApp policy windows and provider throughput still govern what can be sent.
  • Back off on 429, transient 5xx, and provider quality errors. Do not retry permanently invalid phone number, token, or permission errors.

Troubleshooting

SymptomCheck
Meta webhook verification returns 403Confirm hub.verify_token exactly matches organization.whatsappVerifyToken for the organization ID in the callback URL.
Meta webhook verification returns 400Confirm Meta sends hub.mode, hub.verify_token, and hub.challenge to the GET route.
Inbound messages do not appearConfirm the callback URL is public HTTPS, the app is subscribed to WhatsApp messages, and the URL includes the correct organization ID.
Messages are acknowledged but no assistant reply is sentCheck /api/kommander-rag-trigger-whatsapp errors, assistant training state, and whether the conversation is assigned to a human operator.
Replies fail from MetaVerify the access token is valid, the phone number ID belongs to the same business account, and the token has WhatsApp messaging permissions.
Signature verification failsRecompute the HMAC from the exact raw request body. Do not call request.json() before signature verification.
Duplicate messages appearStore and deduplicate by Meta message ID before appending conversation messages.
Baileys QR expiresCall POST /api/whatsapp/start again and scan the new QR code from WhatsApp on the paired phone.
Baileys disconnects after deployConfirm the runtime preserves auth state and keeps the Node.js process alive. Re-pair after auth directory deletion or serverless cold starts.
Group messages do not trigger repliesThis is expected. The current Baileys handler ignores JIDs containing @g.us.

Limitations

  • The documented Meta path is text-first. Media, templates, buttons, and interactive message types require provider-specific handling beyond the current ingress.
  • The Meta reply route currently sends text messages through Graph API version v22.0.
  • Baileys is session-based and less durable than Meta Cloud API for production workloads.
  • Advanced Baileys features are intentionally out of scope for this integration page.