Verify webhook signatures
Every webhook 2Chat sends is signed, so your endpoint can check three things before trusting it:
- Authenticity: it was sent by 2Chat and not by someone who found your URL.
- Integrity: the body was not altered on the way.
- Freshness: it is not an old event being replayed.
2Chat follows the open Standard Webhooks specification (HMAC-SHA256). You can verify with the official standardwebhooks libraries (Node.js, Python, PHP, Go, Ruby, Java, C#…) or with a few lines of your own code.
Verifying is optional. Webhooks keep arriving as before; the signature only adds headers. Platforms like Make, Zapier or n8n don't verify signatures natively, so nothing changes for them.
Get your signing secret
- Go to the Developer's Portal and open the Webhooks tab.
- In Signing secret, click the eye icon to reveal the secret, or the copy icon to copy it.
The secret looks like whsec_ followed by a base64 string. There is one secret per account: it signs every webhook of every channel and event, so one endpoint needs only one secret. Only account admins can see it.
Keep it private, like an API key: store it in an environment variable or a secrets manager, never in your code.
Signature headers
Each webhook carries these headers:
| Header | Example | Description |
|---|---|---|
webhook-id | MSG6a1f0c2e-9b7d-4e43-8f0a-2c51d7e9b3a4_message.received | Unique id of the event. It does not change when 2Chat retries the delivery, so use it to discard duplicates. |
webhook-timestamp | 1762077600 | When the webhook was signed, in seconds since the Unix epoch. |
webhook-signature | v1,K5oZfzN95Z9UVu1EsfQmfVNQhnkZ2pj9o9NDN/H/pI4= | One or more signatures separated by spaces. Each one is v1, followed by the base64 HMAC-SHA256. |
The signed content is the id, the timestamp and the raw request body, joined with dots:
{webhook-id}.{webhook-timestamp}.{raw body}
The HMAC key is the base64-decoded part of the secret that comes after whsec_.
How to verify
- Read the raw body exactly as it arrived, before any JSON parsing.
- Reject the request if
webhook-timestampis more than 5 minutes away from your current time. - Compute the HMAC-SHA256 of
{webhook-id}.{webhook-timestamp}.{raw body}with your key and encode it in base64. - Compare it, in constant time, with each
v1,signature inwebhook-signature. Accept the webhook if any of them matches. - Optionally, store the
webhook-idyou processed and ignore it if it arrives again.
Respond with a 2xx status once the webhook is verified. Reject failed verifications with 400 or 401.
Examples with the official library
- Node.js (Express)
- Python (Flask)
- PHP
npm install standardwebhooks
const express = require("express");
const { Webhook } = require("standardwebhooks");
const app = express();
const wh = new Webhook(process.env.TWOCHAT_WEBHOOK_SECRET); // whsec_...
// express.raw keeps the body as bytes: express.json() would re-serialize it
app.post("/2chat/webhooks", express.raw({ type: "application/json" }), (req, res) => {
let event;
try {
event = wh.verify(req.body, req.headers); // checks signature and timestamp
} catch (err) {
return res.status(400).send("Invalid signature");
}
console.log("Verified event", req.headers["webhook-id"], event);
res.sendStatus(204);
});
app.listen(3000);
pip install standardwebhooks
import os
from flask import Flask, request, abort
from standardwebhooks.webhooks import Webhook
app = Flask(__name__)
wh = Webhook(os.environ["TWOCHAT_WEBHOOK_SECRET"]) # whsec_...
@app.post("/2chat/webhooks")
def receive_webhook():
try:
# request.get_data() is the raw body, not the parsed JSON
event = wh.verify(request.get_data(), dict(request.headers))
except Exception:
abort(400)
print("Verified event", request.headers["webhook-id"], event)
return "", 204
composer require standard-webhooks/standard-webhooks
<?php
require 'vendor/autoload.php';
$wh = new \StandardWebhooks\Webhook(getenv('TWOCHAT_WEBHOOK_SECRET')); // whsec_...
$payload = file_get_contents('php://input'); // raw body
$headers = [
'webhook-id' => $_SERVER['HTTP_WEBHOOK_ID'] ?? '',
'webhook-timestamp' => $_SERVER['HTTP_WEBHOOK_TIMESTAMP'] ?? '',
'webhook-signature' => $_SERVER['HTTP_WEBHOOK_SIGNATURE'] ?? '',
];
try {
$event = $wh->verify($payload, $headers);
} catch (Exception $e) {
http_response_code(400);
exit('Invalid signature');
}
http_response_code(204);
Examples without a library
- Node.js (Express)
- Python (Flask)
- PHP
const crypto = require("crypto");
const express = require("express");
const SECRET = process.env.TWOCHAT_WEBHOOK_SECRET; // whsec_...
const KEY = Buffer.from(SECRET.replace(/^whsec_/, ""), "base64");
const TOLERANCE_SECONDS = 5 * 60;
function verify(rawBody, headers) {
const id = headers["webhook-id"];
const timestamp = headers["webhook-timestamp"];
const signatures = headers["webhook-signature"];
if (!id || !timestamp || !signatures) return false;
if (Math.abs(Date.now() / 1000 - Number(timestamp)) > TOLERANCE_SECONDS) return false;
const expected = crypto
.createHmac("sha256", KEY)
.update(`${id}.${timestamp}.`)
.update(rawBody)
.digest();
return signatures.split(" ").some((candidate) => {
const [version, signature] = candidate.split(",");
if (version !== "v1" || !signature) return false;
const received = Buffer.from(signature, "base64");
return received.length === expected.length && crypto.timingSafeEqual(received, expected);
});
}
const app = express();
app.post("/2chat/webhooks", express.raw({ type: "application/json" }), (req, res) => {
if (!verify(req.body, req.headers)) return res.status(400).send("Invalid signature");
const event = JSON.parse(req.body.toString("utf8"));
res.sendStatus(204);
});
import base64
import hashlib
import hmac
import os
import time
from flask import Flask, request, abort
SECRET = os.environ["TWOCHAT_WEBHOOK_SECRET"] # whsec_...
KEY = base64.b64decode(SECRET.removeprefix("whsec_"))
TOLERANCE_SECONDS = 5 * 60
def verify(raw_body: bytes, headers) -> bool:
msg_id = headers.get("webhook-id")
timestamp = headers.get("webhook-timestamp")
signatures = headers.get("webhook-signature")
if not (msg_id and timestamp and signatures):
return False
if abs(time.time() - int(timestamp)) > TOLERANCE_SECONDS:
return False
to_sign = f"{msg_id}.{timestamp}.".encode() + raw_body
expected = base64.b64encode(hmac.new(KEY, to_sign, hashlib.sha256).digest()).decode()
for candidate in signatures.split(" "):
version, _, signature = candidate.partition(",")
if version == "v1" and hmac.compare_digest(signature, expected):
return True
return False
app = Flask(__name__)
@app.post("/2chat/webhooks")
def receive_webhook():
if not verify(request.get_data(), request.headers):
abort(400)
event = request.get_json()
return "", 204
<?php
$secret = getenv('TWOCHAT_WEBHOOK_SECRET'); // whsec_...
$key = base64_decode(preg_replace('/^whsec_/', '', $secret));
$tolerance = 5 * 60;
$payload = file_get_contents('php://input'); // raw body
$id = $_SERVER['HTTP_WEBHOOK_ID'] ?? '';
$timestamp = $_SERVER['HTTP_WEBHOOK_TIMESTAMP'] ?? '';
$signatures = $_SERVER['HTTP_WEBHOOK_SIGNATURE'] ?? '';
function verify_2chat_webhook($key, $id, $timestamp, $signatures, $payload, $tolerance) {
if ($id === '' || $timestamp === '' || $signatures === '') return false;
if (abs(time() - (int) $timestamp) > $tolerance) return false;
$expected = base64_encode(hash_hmac('sha256', "{$id}.{$timestamp}.{$payload}", $key, true));
foreach (explode(' ', $signatures) as $candidate) {
$parts = explode(',', $candidate, 2);
if (count($parts) === 2 && $parts[0] === 'v1' && hash_equals($expected, $parts[1])) {
return true;
}
}
return false;
}
if (!verify_2chat_webhook($key, $id, $timestamp, $signatures, $payload, $tolerance)) {
http_response_code(400);
exit('Invalid signature');
}
$event = json_decode($payload, true);
http_response_code(204);
Rotate the secret
Rotate the secret from Signing secret → Rotate secret in the Developer's Portal. Do it on a schedule if your security policy requires it, or right away if the secret leaked. You can choose between two options:
- Keep the current secret valid for 24 hours (recommended). During those 24 hours every webhook carries two signatures, one per secret (
v1,<new> v1,<old>). Your endpoint keeps verifying with the old secret while you deploy the new one, so no event is lost. - Invalidate the current secret now. Only the new secret signs from that moment. Use it when the secret leaked: until you deploy the new secret, your endpoint will reject 2Chat's webhooks.
A rotation can take up to a minute to reach every 2Chat server.
Common mistakes
- Verifying a re-serialized body. Frameworks that parse JSON automatically (
express.json(),request.json, Laravel's$request->all()) change spaces, key order or escaping, and the signature no longer matches. Always verify the raw bytes, then parse. - Clocks out of sync. If your server's clock drifts, valid webhooks fall outside the 5-minute window. Keep the clock synced with NTP.
- Checking only the first signature. During a rotation the header has two signatures. Accept the webhook if any of them matches.
- Comparing with
==. Use a constant-time comparison (crypto.timingSafeEqual,hmac.compare_digest,hash_equals). - Not responding quickly. Verify, respond
2xx, and do the heavy work afterwards. Slow responses trigger retries.
See also Logs & Troubleshooting.