Webhooks
Get a call on your server whenever the status of a message you sent through the API changes.
Webhooks are sent only for messages sent through this API (not for chats your team handles in the inbox).
Overview
sent -> delivered -> read
\-> failed
| Event | When |
|---|---|
message.sent | WhatsApp accepted the message |
message.delivered | Delivered to the customer's phone |
message.read | The customer read it |
message.failed | WhatsApp could not deliver it |
Setup
- In the GB Chat dashboard open Settings > API & Webhooks.
- In the Webhook card enter your endpoint URL and Save. It must be
https://. - Use Regenerate Secret to get your webhook secret. It is shown only once: store it safely.
- Use Send Test Event to check your endpoint (see Testing).
Your endpoint must accept POST with a JSON body and answer with a 2xx status within 10 seconds.
Request we send
Headers
| Header | Description |
|---|---|
Content-Type | application/json |
X-GBChat-Signature | sha256= followed by the HMAC-SHA256 of the raw request body (hex) |
X-GBChat-Timestamp | Unix time in seconds when the request was created |
Body
{
"event": "message.delivered",
"timestamp": 1707300605000,
"data": {
"messageId": "65c7f0a1b2c3d4e5f6a7b8c9",
"externalId": "your-reference-123",
"status": "delivered",
"to": "919876543210"
}
}
| Field | Type | Description |
|---|---|---|
event | string | One of the events above |
timestamp | number | Event time, Unix milliseconds |
data.messageId | string | The messageId returned by the send API |
data.externalId | string | Your reference, if you sent one (only present then) |
data.status | string | sent, delivered, read or failed |
data.to | string | Recipient phone number |
data.error | object | Only on failure: { "code": number, "message": string } |
Match events to your records with data.externalId (your own reference) or data.messageId.
Failed messages
{
"event": "message.failed",
"timestamp": 1707300605000,
"data": {
"messageId": "65c7f0a1b2c3d4e5f6a7b8c9",
"externalId": "your-reference-123",
"status": "failed",
"to": "919876543210",
"error": {
"code": 131026,
"message": "Message undeliverable"
}
}
}
Verifying the signature
Always verify the signature, so you only act on requests that really come from GB Chat.
- Take the raw request body exactly as received (do not parse and re-serialize it).
- Compute
HMAC-SHA256(rawBody, webhookSecret)and hex-encode it. - Compare with the value of
X-GBChat-Signatureafter thesha256=prefix, using a constant-time comparison.
The timestamp header is not part of the signature. You may use it to reject very old requests.
Node.js (Express)
const crypto = require('crypto');
const express = require('express');
const app = express();
// keep the raw body for signature checking
app.use(express.json({ verify: (req, res, buf) => { req.rawBody = buf.toString('utf8'); } }));
function verifyWebhook(req, webhookSecret) {
const signature = req.headers['x-gbchat-signature'] || '';
const timestamp = parseInt(req.headers['x-gbchat-timestamp'], 10);
// optional: reject requests older than 5 minutes
if (!timestamp || Math.abs(Math.floor(Date.now() / 1000) - timestamp) > 300) return false;
const expected = 'sha256=' + crypto
.createHmac('sha256', webhookSecret)
.update(req.rawBody)
.digest('hex');
const a = Buffer.from(signature);
const b = Buffer.from(expected);
return a.length === b.length && crypto.timingSafeEqual(a, b);
}
app.post('/webhook', (req, res) => {
if (!verifyWebhook(req, process.env.GBCHAT_WEBHOOK_SECRET)) {
return res.status(401).send('Invalid signature');
}
const { event, data } = req.body;
console.log(`Received ${event} for message ${data.messageId}`);
res.status(200).send('OK');
});
Python (Flask)
import hashlib
import hmac
import os
import time
from flask import Flask, request, jsonify
app = Flask(__name__)
WEBHOOK_SECRET = os.environ['GBCHAT_WEBHOOK_SECRET']
def verify_webhook(req) -> bool:
signature = req.headers.get('X-GBChat-Signature', '')
try:
timestamp = int(req.headers.get('X-GBChat-Timestamp', ''))
except ValueError:
return False
# optional: reject requests older than 5 minutes
if abs(int(time.time()) - timestamp) > 300:
return False
expected = 'sha256=' + hmac.new(
WEBHOOK_SECRET.encode(),
req.get_data(), # raw body bytes
hashlib.sha256
).hexdigest()
return hmac.compare_digest(signature, expected)
@app.route('/webhook', methods=['POST'])
def webhook():
if not verify_webhook(request):
return jsonify({'error': 'Invalid signature'}), 401
payload = request.get_json()
print(f"Received {payload['event']} for message {payload['data']['messageId']}")
return 'OK', 200
Testing webhooks
In Settings > API & Webhooks click Send Test Event. We send a signed request to your URL with this body:
{
"event": "message.sent",
"timestamp": 1707300605000,
"data": {
"messageId": "test_message_id",
"status": "test",
"externalId": "test_external_id"
}
}
A test is recognised by data.status being test. Do not update any real order for it.
For local development, expose your machine with a tunnel (for example ngrok http 3000) and use the HTTPS URL it gives you.
Delivery rules and best practices
Retries
If your endpoint does not answer with a 2xx status within 10 seconds, we try again. There are 3 attempts in total: immediately, after 1 second and after 2 more seconds. After that the event is dropped, so keep your endpoint reliable and use the status of a message as a fallback when needed.
Duplicates and order
- The same event can arrive more than once (for example
message.sentis sent when you call the API and WhatsApp's own "sent" update can follow). Make your handler idempotent, usingmessageIdandstatus. - Events can arrive out of order (for example
readbeforedelivered). Never move a message back to an earlier status.
Respond first, process later
Return 200 right away and do the work afterwards:
app.post('/webhook', (req, res) => {
res.status(200).send('OK');
processWebhook(req.body).catch(console.error);
});