Guides

WhatsApp webhook receiver in Python (Flask and FastAPI)

A WhatsApp webhook receiver in Python (Flask) on HelloHop reads the raw bytes with request.get_data(), compares X-HelloHop-Signature with hmac.compare_digest, saves the event before it answers 200 and deduplicates by chat and UTC day. HelloHop has no verify token and no GET handshake. This guide's receiver replies to inbound messages and records message.status receipts, with a FastAPI variant.

Facts (as of October 2026, API v1)

  • HelloHop signs each delivery in X-HelloHop-Signature: the lowercase hex HMAC-SHA256 of the raw body, keyed with the receiver secret, with no prefix.
  • Your endpoint has 10 seconds by default to answer any 2xx. A timeout, a network error, a 5xx, 408, 425 or 429 is retried with a growing wait for about a day and a half. Any other 4xx is a refusal and stops after three tries over about five minutes, and the webhook.test event gets one attempt.
  • A retry keeps the same body, id and timestamp. The delivery header is not signed, so build your keys from fields inside the verified body.
  • HelloHop has no GET handshake and no verify token. You set a secret of at least 24 characters on the receiver and every delivery is signed with it in X-HelloHop-Signature. POST /v1/sessions/{channel}/webhooks/test sends one signed webhook.test event to a URL you already set.
  • The unified POST /v1/sessions/{channel}/messages route accepts an Idempotency-Key of up to 255 characters. Repeating the same key and body within 24 hours returns the first result without another send, with the response header Idempotent-Replayed: true.
  • A 504 send_unconfirmed, a timeout, a 409 idempotency_uncertain or a 503 with ambiguous true means the message may have gone out. Treat it as possibly delivered and look at the chat before you send it again.

Steps

  1. Subscribe. PUT your HTTPS URL, the events message and message.status, and a secret of at least 24 characters to /v1/sessions/{channel}/webhooks. PUT replaces the whole receiver list.
  2. Verify the raw body. Read request.get_data() before anything parses the JSON, hash it with HMAC-SHA256 and compare with hmac.compare_digest. Answer 401 on a mismatch.
  3. Save, then answer. Insert the inbound text under a key built from the chat and the day. Answer 500 if the insert fails so the event is delivered again, and 200 only after the write.
  4. Reply and track receipts. Claim the saved row, send one reply with an Idempotency-Key built from that key and store each message.status receipt by the message id it names.

No verify token: what HelloHop does instead

Some webhook providers check your endpoint with a GET request that carries a verify token. HelloHop sends no such request. You set a secret of at least 24 characters on the receiver with PUT, and every delivery is a POST signed with that secret. POST /v1/sessions/{channel}/webhooks/test delivers one signed webhook.test event to a URL you already set and sends nothing to WhatsApp.

Subscribe to messages and receipts

curl
API=https://api.hellohop.app/v1

curl -s -X PUT "$API/sessions/$CHANNEL_ID/webhooks" \
  -H "Authorization: Bearer $CHANNEL_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"receivers":[{"url":"https://example.com/webhooks/whatsapp","events":["message","message.status"],"secret":"REPLACE_WITH_24_PLUS_CHARACTERS"}]}'

The receiver (Flask)

This sample is self-contained: it keeps the events in a local SQLite file, so you can run it as it is and replace the storage later. Install the packages with python -m pip install flask requests and set CHANNEL_ID, CHANNEL_TOKEN and WEBHOOK_SECRET. The signature check compares bytes, so a header with unexpected characters cannot raise an error. The sample refuses to start when WEBHOOK_SECRET has fewer than 24 characters. It replies to plain text in a direct chat only, once per chat per UTC day, so reactions, deletes, poll votes and another auto-responder cannot start a loop. The day comes from the UTC timestamp of the event, so it rolls over at 07:00 in Bangkok, and a redelivery that crosses midnight keeps its key. To use your own day, change the [:10] slice in the key. A background thread runs every 60 seconds and logs a failed run instead of stopping: it sends pending rows that are due again with the same key and body, and marks claims older than five minutes as unknown. send_whatsapp does not sleep inside a claim: for a retry it returns retry_at, the time the row is due, from Retry-After. The claim only takes a pending row whose next_attempt has passed, so a new text from that chat does not resend early. A receipt that arrives before the id of your reply is saved waits in its own table and joins later. The reply text is an example.

Python: Flask receiver
import hashlib, hmac, json, logging, os, sqlite3, threading, time
import requests
from flask import Flask, request

API = 'https://api.hellohop.app/v1'
CHANNEL_ID, CHANNEL_TOKEN, WEBHOOK_SECRET = os.environ['CHANNEL_ID'], os.environ['CHANNEL_TOKEN'], os.environ['WEBHOOK_SECRET']
if len(WEBHOOK_SECRET) < 24:
    raise SystemExit('Set WEBHOOK_SECRET to the receiver secret (24 characters or more) before you start')
DB = os.environ.get('EVENTS_DB', 'events.db')
RANK = {'delivered': 1, 'read': 2, 'played': 2}  # any other status, such as undecryptable, ranks with delivered

def run(sql, params=()):
    con = sqlite3.connect(DB, timeout=10)
    try:
        with con:
            cur = con.execute(sql, params)
            return cur.rowcount, cur.fetchall()
    finally:
        con.close()

# One events row per chat per UTC day. A receipt can arrive before the reply's id is saved, so receipts have their own table:
# SELECT e.id, r.status FROM events e JOIN receipts r ON r.message_id = e.message_id
run("CREATE TABLE IF NOT EXISTS events (id TEXT PRIMARY KEY, body TEXT, state TEXT, claimed_at REAL, message_id TEXT, next_attempt REAL DEFAULT 0)")
run("CREATE TABLE IF NOT EXISTS receipts (message_id TEXT PRIMARY KEY, status TEXT, rank INTEGER)")

def send_whatsapp(key, message):
    """One send. Repeating the same key with the same body returns the first result."""
    try:
        r = requests.post(f'{API}/sessions/{CHANNEL_ID}/messages', json=message, timeout=15,
                          headers={'Authorization': f'Bearer {CHANNEL_TOKEN}', 'Idempotency-Key': key})
    except requests.RequestException:
        return {'status': 0}  # timeout or lost connection: the message may have gone out
    try:
        data = r.json()
    except ValueError:
        data = {}
    data = data if isinstance(data, dict) else {}
    result = {'status': r.status_code, 'code': data.get('code'), 'ambiguous': data.get('ambiguous'), 'id': data.get('id')}
    if classify(result) == 'retry':  # no sleeping inside the claim: say when the row is due again
        wait = r.headers.get('Retry-After', '')
        result['retry_at'] = time.time() + (int(wait) if wait.isdigit() else 1)  # a date value falls back to 1 second
    return result

def classify(r):
    """sent (server_ack), queued, retry, unknown or failed."""
    status, code, ambiguous = r['status'], r.get('code'), r.get('ambiguous')
    if status == 200: return 'sent'      # server_ack, not delivered
    if status == 202: return 'queued'    # observe webhooks, do not resend
    refused = ('upstream_unavailable', 'hopsmart_settings_unavailable', 'operator_unresolved')
    if status == 429 or (status == 503 and (ambiguous is False or code in refused)): return 'retry'  # refused before sending
    if status == 0 or status >= 500 or code == 'idempotency_uncertain': return 'unknown'  # look at the chat, never resend
    return 'failed'                      # idempotency_conflict, a bad request: fix it, do not retry

def reply(key):
    now = time.time()
    claimed, _ = run("UPDATE events SET state = 'claimed', claimed_at = ? WHERE id = ? AND state = 'pending' AND next_attempt <= ?", (now, key, now))
    if claimed != 1:
        return  # another worker has it, the row is final, or a retry is not due yet
    event = json.loads(run("SELECT body FROM events WHERE id = ?", (key,))[1][0][0])
    result = send_whatsapp(f'reply-{key}', {'type': 'text', 'to': event['payload']['chat_jid'], 'text': 'Thanks, we got your message.'})
    outcome = classify(result)  # retry releases the row to pending, due at retry_at; the id lets receipts match
    run("UPDATE events SET state = ?, message_id = ?, next_attempt = ? WHERE id = ? AND state = 'claimed'",
        ('pending' if outcome == 'retry' else outcome, result.get('id'), result.get('retry_at', 0), key))

def mark_status(ids, status):
    rank = RANK.get(status, 1)  # only moves forward
    for message_id in ids:
        run("INSERT INTO receipts (message_id, status, rank) VALUES (?, ?, ?) ON CONFLICT(message_id) DO UPDATE SET status = excluded.status, rank = excluded.rank WHERE excluded.rank > receipts.rank",
            (message_id, status, rank))

def sweep():
    while True:
        time.sleep(60)
        try:  # one failed tick must not end the thread
            run("UPDATE events SET state = 'unknown' WHERE state = 'claimed' AND claimed_at < ?", (time.time() - 300,))
            for (key,) in run("SELECT id FROM events WHERE state = 'pending' AND next_attempt <= ?", (time.time(),))[1]:
                reply(key)
        except Exception:
            logging.exception('sweep failed, trying again next minute')

threading.Thread(target=sweep, daemon=True).start()

def handle_delivery(raw: bytes, signature: str) -> int:
    expected = hmac.new(WEBHOOK_SECRET.encode(), raw, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected.encode(), signature.encode()):
        return 401
    event = json.loads(raw)
    m = event.get('payload', {})
    # Plain text in a direct chat only, one reply per chat per UTC day: no reply to reactions, deletes or poll votes, and
    # another auto-responder cannot start a loop. The date is the UTC day of the event timestamp, so a redelivery keeps
    # its key even across midnight. To use your own day, change the [:10] slice.
    inbound = event.get('type') == 'message' and m.get('type') == 'text' and not m.get('from_me') and not m.get('is_group')
    key = f"auto-{m.get('chat_jid')}-{event.get('timestamp', '')[:10]}" if inbound else None
    try:
        if event.get('type') == 'message.status':
            mark_status(m.get('ids', []), m.get('status'))  # safe to repeat
        elif inbound:
            run("INSERT INTO events (id, body, state) VALUES (?, ?, 'pending') ON CONFLICT(id) DO NOTHING", (key, raw.decode()))
    except sqlite3.Error:
        return 500  # nothing is lost: the webhook is delivered again
    if inbound:
        threading.Thread(target=reply, args=(key,), daemon=True).start()
    return 200  # only after the write

app = Flask(__name__)

@app.post('/webhooks/whatsapp')
def webhook():
    return '', handle_delivery(request.get_data(), request.headers.get('X-HelloHop-Signature', ''))

if __name__ == '__main__':
    app.run(port=3000)

FastAPI variant

Only the route changes. Keep the helpers from the Flask sample, read the body with await request.body() and run the blocking handler in a thread pool. Install fastapi and an ASGI server such as uvicorn to run it.

Python: FastAPI route
from fastapi import FastAPI, Request, Response
from starlette.concurrency import run_in_threadpool

api = FastAPI()  # reuses run, send_whatsapp, classify, reply and handle_delivery from the Flask sample, and its secret check

@api.post('/webhooks/whatsapp')
async def webhook(request: Request):
    status = await run_in_threadpool(handle_delivery, await request.body(), request.headers.get('X-HelloHop-Signature', ''))
    return Response(status_code=status)

What the handler does with each send result

Send resultWhat your handler does
200 server_ackWhatsApp acknowledged the send. Mark it sent and save id; this is not a delivery receipt.
202 queuedPersisted in the queue, not delivered. A channel that queues its sends (for example while accepted sends drain) answers every text send this way, with id, status queued, position and expires_at. Mark it queued and save id. Observe the result through webhooks without resending.
429, or 503 with ambiguous false or code upstream_unavailable, hopsmart_settings_unavailable or operator_unresolvedRefused before sending. Honor Retry-After, keep the same key and body, and retry later. The Node helper waits at most 30 seconds before returning retry with a retryAt time, and the pages that keep a due time skip the row until then; the other Node timer pages retry on their next run. The Flask, Python reminder and PHP samples return the time to retry instead of waiting; the Sheets helper saves next_attempt_at and skips the row until then.
504 send_unconfirmed, 409 idempotency_uncertain, 503 with ambiguous true, a timeout or a lost responsePossibly delivered. Mark it unknown and look at the chat before any resend. Never force a resend of an uncertain key with a new key.
409 idempotency_conflictThe same key was used for a different message. Fix how you build the key. The first message is unchanged.
Any other 409Mark it failed. Fix the channel before scheduling another attempt.
Other 4xxThe request is wrong and a retry will not fix it. Log it and move on.

Subscribe to message and message.status webhooks and verify their signatures. The result of a queued send arrives as a message event: match the saved response id to payload.id. message.status reports delivered or read for each id in payload.ids. A send held by HopSmart™ expires 72 hours after acceptance, and the 202 carries expires_at. If no event arrives, read the job with GET /hopsmart/jobs/{id}. Save event ids to deduplicate. Do not resend queued work while waiting for a result.

Questions

Is there a verify token or a GET handshake?
No. HelloHop signs every delivery with the secret you set on the receiver. Verify X-HelloHop-Signature on the raw body instead.
Why request.get_data() and not request.json?
The signature covers the exact bytes. Read them first, then parse. Re-serialized JSON can differ in bytes, and then the hash no longer matches.
Why hmac.compare_digest?
It compares in constant time. Encode both values to bytes first, so a non-ASCII header cannot raise an exception.
How do I avoid replying twice to one message?
The key is built from the chat and the day and is the primary key, the claim update succeeds for one worker, and the reply carries an Idempotency-Key built from that key.
What does the receiver do with duplicates?
A repeated key inserts nothing and only one worker can claim the row, so a duplicate, or a second text from the same chat that day, gets a plain 200 and no second reply.

Free sandbox, forever. Upgrade when you're ready.

Start free

HelloHop is an independent WhatsApp API for developers: send and receive messages, automate groups and communities, and get signed webhooks. Not affiliated with WhatsApp or Meta. You link your own number.

WhatsApp Webhook Receiver in Python (Flask) | HelloHop