ChatKomodo Docs Home Sign in

Guide

Webhooks and live events

ChatKomodo posts events to your HTTPS endpoint as they happen: incoming messages, delivery results and device changes.

Create a webhook

Request
curl -X POST "https://api.chatkomodo.com/v1/webhooks" \
  -H "Authorization: Bearer $CHATKOMODO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
  "url": "https://example.com/webhooks/chatkomodo",
  "secret": "a-long-random-secret-of-32-characters-or-more",
  "events": [
    "message.received",
    "message.sent",
    "message.failed",
    "session.connected",
    "session.disconnected"
  ]
}'
const res = await fetch('https://api.chatkomodo.com/v1/webhooks', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.CHATKOMODO_API_KEY}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    "url": "https://example.com/webhooks/chatkomodo",
    "secret": "a-long-random-secret-of-32-characters-or-more",
    "events": [
      "message.received",
      "message.sent",
      "message.failed",
      "session.connected",
      "session.disconnected"
    ]
  }),
});
const data = await res.json();
if (!res.ok) throw new Error(`${data.code}: ${data.error}`);
console.log(data);
import os
import requests

res = requests.post(
    "https://api.chatkomodo.com/v1/webhooks",
    headers={
        "Authorization": f"Bearer {os.environ['CHATKOMODO_API_KEY']}",
    },
    json={
        "url": "https://example.com/webhooks/chatkomodo",
        "secret": "a-long-random-secret-of-32-characters-or-more",
        "events": [
            "message.received",
            "message.sent",
            "message.failed",
            "session.connected",
            "session.disconnected",
        ],
    },
    timeout=30,
)
res.raise_for_status()
print(res.json())
<?php
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client();
$res = $client->request('POST', 'https://api.chatkomodo.com/v1/webhooks', [
    'headers' => [
        'Authorization' => 'Bearer ' . getenv('CHATKOMODO_API_KEY'),
    ],
    'json' => [
        'url' => 'https://example.com/webhooks/chatkomodo',
        'secret' => 'a-long-random-secret-of-32-characters-or-more',
        'events' => [
            'message.received',
            'message.sent',
            'message.failed',
            'session.connected',
            'session.disconnected',
        ],
    ],
]);

print_r(json_decode((string) $res->getBody(), true));
package main

import (
	"fmt"
	"io"
	"net/http"
	"os"
	"strings"
)

func main() {
	body := strings.NewReader(`{
	  "url": "https://example.com/webhooks/chatkomodo",
	  "secret": "a-long-random-secret-of-32-characters-or-more",
	  "events": [
	    "message.received",
	    "message.sent",
	    "message.failed",
	    "session.connected",
	    "session.disconnected"
	  ]
	}`)
	req, err := http.NewRequest("POST", "https://api.chatkomodo.com/v1/webhooks", body)
	if err != nil {
		panic(err)
	}
	req.Header.Set("Authorization", "Bearer "+os.Getenv("CHATKOMODO_API_KEY"))
	req.Header.Set("Content-Type", "application/json")

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()
	data, _ := io.ReadAll(res.Body)
	if res.StatusCode >= 400 {
		panic(fmt.Sprintf("%d: %s", res.StatusCode, data))
	}
	fmt.Println(string(data))
}

The URL must be HTTPS and reachable from the internet; the secret at least 32 characters (keep it — it signs every delivery). Pause, change or delete it with PATCH /v1/webhooks/{id} and DELETE /v1/webhooks/{id}; send a webhook.test event with POST /v1/webhooks/{id}/test.

Events

EventWhendata
message.receivedA message arrived on one of your devicesmessage_id, wa_message_id, chat_id, phone (null for groups and hidden numbers), name (the sender's WhatsApp name), direction (inbound), message_type, body, is_group; for a photo, document, voice note or video also media_pending, media_type and file_name
message.mediaThe file of a customer's photo, document, voice note or video is stored, moments after message.receivedmessage_id, chat_id, message_type, media_key (download it with GET /v1/media/{key}; null when it was not kept: over 16 MB or the download failed), media_type, file_name
message.sentAn outgoing message was accepted by WhatsAppmessage_id, chat_id, direction, message_type, status
message.failedAn outgoing message could not be sentas above, plus error
session.connectedA device came onlinephone_number, wa_name
session.disconnectedA device went offlinereason: logged_out, banned or status_<code>
session.alertA device has been offline for more than 5 minutestype, message, disconnected_since, duration_ms
qr.generatedA new QR code is ready to scanqr, expires_at
label.added, label.removedLabels were put on or taken off a person or group chat (by hand, a rule, the AI or the store)chat_id, phone, contact_id, labels, source, rule_id
lead.stage_changedA person moved to another lead stagecontact_id, phone, chat_id, name, stage and stage_name, previous_stage and previous_stage_name (null = was not on the board), source, rule_id, actor
lead.updatedDeal value, owner or follow-up changedcontact_id, phone, currency, changes (only what changed), actor
lead.follow_up_dueA follow-up date has comecontact_id, phone, name, owner_agent_id, follow_up_at, follow_up_note
lead.lostA lead moved to a lost stage (the reason the team picks later comes as lead.updated with changes.lost_reason)contact_id, phone, name, stage, deal_value_minor, owner_agent_id, source, guess (first guess of the reason or null)
chat.unansweredA customer has waited longer than the alert time set in Support agents → Performance (or the chat was moved to another agent)chat_id, waiting_since, minutes, agent_id, reassigned_to
invoice.paidA QRIS invoice sent from a chat was paid (QRIS payments)invoice_id, order_id, phone, chat_id, contact_id, description, amount, fee, total, currency, sandbox, paid_at

Label and lead events about a person carry session_id: null when the change did not happen in a chat (the CRM, the leads board, an import).

Payload

Every delivery is a POST with a JSON body:

message.received
{
  "id": "evt_01JA5W9Q2R3S4T5V6W7X8Y9Z0A",
  "type": "message.received",
  "session_id": "01JA5V6Q8M2H7G4K9P3T0R1S2X",
  "occurred_at": 1767225600000,
  "data": {
    "message_id": "01JA5W9Q2R3S4T5V6W7X8Y9Z0B",
    "chat_id": "447700900123@s.whatsapp.net",
    "direction": "inbound",
    "message_type": "text",
    "body": "Is the red one still in stock?"
  }
}

and these headers:

Verify the signature

Compute the HMAC over the raw request body (before any JSON parsing) and compare in constant time. Reject anything that does not match.

Node.js (Express)
import express from 'express';
import { createHmac, timingSafeEqual } from 'node:crypto';

const app = express();
const secret = process.env.CHATKOMODO_WEBHOOK_SECRET;

app.post('/webhooks/chatkomodo', express.raw({ type: 'application/json' }), (req, res) => {
  const expected = 'sha256=' + createHmac('sha256', secret).update(req.body).digest('base64');
  const got = req.get('X-Webhook-Signature') ?? '';
  if (got.length !== expected.length || !timingSafeEqual(Buffer.from(got), Buffer.from(expected))) {
    return res.status(401).end();
  }
  const event = JSON.parse(req.body.toString('utf8'));
  res.status(200).end(); // answer first, then work
  handle(event);
});
Python (Flask)
import base64, hashlib, hmac, os
from flask import Flask, request, abort

app = Flask(__name__)
SECRET = os.environ["CHATKOMODO_WEBHOOK_SECRET"].encode()

@app.post("/webhooks/chatkomodo")
def chatkomodo():
    raw = request.get_data()
    expected = "sha256=" + base64.b64encode(hmac.new(SECRET, raw, hashlib.sha256).digest()).decode()
    if not hmac.compare_digest(expected, request.headers.get("X-Webhook-Signature", "")):
        abort(401)
    event = request.get_json()
    # queue the work, answer quickly
    return "", 200
PHP
<?php
$raw = file_get_contents('php://input');
$expected = 'sha256=' . base64_encode(hash_hmac('sha256', $raw, getenv('CHATKOMODO_WEBHOOK_SECRET'), true));
if (!hash_equals($expected, $_SERVER['HTTP_X_WEBHOOK_SIGNATURE'] ?? '')) {
    http_response_code(401);
    exit;
}
$event = json_decode($raw, true);
http_response_code(200);

Answer fast; retries

Live event stream (SSE)

For a live screen, open a Server-Sent Events stream instead: get a one-minute ticket with POST /v1/events-ticket, then connect to the url it returns. The ticket is the only way in (an API key in the URL would end up in proxy logs, so it is refused) and works once. Keys limited to some devices cannot open the stream: use webhooks.

Node.js
import { EventSource } from 'eventsource'; // npm i eventsource

const API = 'https://api.chatkomodo.com';
const res = await fetch(`${API}/v1/events-ticket`, {
  method: 'POST',
  headers: { Authorization: `Bearer ${process.env.CHATKOMODO_API_KEY}` },
});
const { url } = await res.json(); // "/v1/events?ticket=…", valid for 60 seconds

const events = new EventSource(API + url);
events.addEventListener('message.received', (e) => console.log(JSON.parse(e.data)));
events.addEventListener('blast.progress', (e) => console.log(JSON.parse(e.data)));

The stream carries the webhook events plus blast.progress, blast.waiting, blast.paused, blast.completed, scheduled.sent and recurring.executed. Events sent while you were disconnected are not replayed: use webhooks when every event matters.

Incoming store webhooks

Shopify and WooCommerce can call ChatKomodo too, to send order messages to buyers: see Online stores.