> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hypersender.com/llms.txt
> Use this file to discover all available pages before exploring further.

# WhatsApp Webhooks in Python

> Receive WhatsApp webhooks in Python with Flask or FastAPI: verify the secret, read incoming messages, delivery and read receipts, reactions, and poll votes.

## Overview

Hypersender sends a WhatsApp webhook to your URL whenever something happens on your instance: a new message, a delivery or read receipt, a reaction, a poll vote. You receive it with your own route. The SDK is only needed when you reply.

A webhook is a `POST` with a JSON body and your secret in the `Authorization` header, so any Python framework can handle it. The examples use Flask and FastAPI. For a complete bot, see [Build a WhatsApp Bot in Python](https://docs.hypersender.com/v2/packages-and-sdks/python/whatsapp/whatsapp-bot.md).

## Set up the webhook

**1. Add the webhook in the dashboard**

In the [Hypersender dashboard](https://app.hypersender.com), open your WhatsApp instance and add a webhook with your public HTTPS URL, for example `https://example.com/whatsapp/webhook`.

**2. Set a secret**

Set an authorization secret on the webhook. Hypersender sends it in the `Authorization` header so you can reject requests that did not come from Hypersender. Save the same value as `HYPERSENDER_WHATSAPP_WEBHOOK_SECRET`.

**3. Answer quickly**

Reply with a `2xx` status right away. If handling an event takes time, store the payload and process it in the background.

## Receive and verify webhooks

> [tab] Flask
>
> ```python theme={null}
> import hmac
> import os
>
> from flask import Flask, abort, request
>
> app = Flask(__name__)
> SECRET = os.environ["HYPERSENDER_WHATSAPP_WEBHOOK_SECRET"]
>
>
> @app.post("/whatsapp/webhook")
> def whatsapp_webhook():
>     if not hmac.compare_digest(request.headers.get("Authorization", ""), SECRET):
>         abort(401)
>
>     body = request.get_json()
>     print(body["event"], body["data"]["payload"])
>
>     return {"status": "ok"}
> ```

> [tab] FastAPI
>
> ```python theme={null}
> import hmac
> import os
>
> from fastapi import FastAPI, Header, HTTPException, Request
>
> app = FastAPI()
> SECRET = os.environ["HYPERSENDER_WHATSAPP_WEBHOOK_SECRET"]
>
>
> @app.post("/whatsapp/webhook")
> async def whatsapp_webhook(request: Request, authorization: str = Header("")):
>     if not hmac.compare_digest(authorization, SECRET):
>         raise HTTPException(status_code=401)
>
>     body = await request.json()
>     print(body["event"], body["data"]["payload"])
>
>     return {"status": "ok"}
> ```

> [!NOTE]
>
> Compare the secret with `hmac.compare_digest`, not `==`, so the comparison takes the same time whether or not the secret matches.

## Payload

Every WhatsApp webhook has the same outer shape:

```json theme={null}
{
  "event": "message.any",
  "data": {
    "event": "message.any",
    "instanceId": "123e4567-e89b-12d3-a456-426614174000",
    "userId": "123e4567-e89b-12d3-a456-426614174000",
    "me": { "id": "201234567890@c.us", "pushName": "My Business" },
    "payload": { "...": "the message, receipt, reaction, or vote" }
  }
}
```

The event-specific fields are in `data["payload"]`. Each event page in the [WhatsApp webhooks reference](https://docs.hypersender.com/v2/api-reference/whatsapp-webhooks/whatsapp-webhooks-introduction.md) shows the full payload.

## WhatsApp webhook events

| Event | Fires when |
| - | - |
| [`message.any`](https://docs.hypersender.com/v2/api-reference/whatsapp-webhooks/messages-any) | A message is created in any chat, including messages you send |
| [`message.ack`](https://docs.hypersender.com/v2/api-reference/whatsapp-webhooks/messages-ack) | A message is delivered, read, or played (`ackName`: `SERVER`, `DEVICE`, `READ`, `PLAYED`, or `ERROR`) |
| [`message.reaction`](https://docs.hypersender.com/v2/api-reference/whatsapp-webhooks/message-reaction) | Someone reacts to a message or removes a reaction |
| [`message.revoked`](https://docs.hypersender.com/v2/api-reference/whatsapp-webhooks/messages-revoked) | A message is deleted for everyone |
| [`message.waiting`](https://docs.hypersender.com/v2/api-reference/whatsapp-webhooks/messages-waiting) | WhatsApp shows "Waiting for this message" |
| [`poll.vote`](https://docs.hypersender.com/v2/api-reference/whatsapp-webhooks/poll-vote) | New votes arrive on a poll |
| [`poll.vote.failed`](https://docs.hypersender.com/v2/api-reference/whatsapp-webhooks/poll-vote-failed) | A poll vote could not be decrypted |
| [`presence.update`](https://docs.hypersender.com/v2/api-reference/whatsapp-webhooks/presence-update) | A contact starts or stops typing or recording |

## Handle each event

Route on `event` and reply with the SDK. This example answers incoming messages and records read receipts:

> [tab] Basic Usage
>
> ```python theme={null}
> from hypersender import Hypersender
>
> hs = Hypersender()
>
>
> def handle(event: str, payload: dict) -> None:
>     if event == "message.any":
>         if payload["fromMe"]:
>             return  # skip messages your own number sent
>         hs.whatsapp.send_text(payload["from"], f"Thanks! We got: {payload['body']}")
>
>     elif event == "message.ack":
>         if payload["ackName"] == "READ":
>             print(f"Message {payload['id']} was read")
> ```
>
> Call `handle(body["event"], body["data"]["payload"])` from your route after the secret check. For slow work, hand it to a background task (FastAPI `BackgroundTasks`, Celery, RQ) and return right away.

> [!TIP]
>
> Always skip `message.any` events where `fromMe` is `True`. Otherwise a bot that replies to every message also replies to its own replies.

## Next steps

* [Build a WhatsApp Bot in Python](https://docs.hypersender.com/v2/packages-and-sdks/python/whatsapp/whatsapp-bot.md): a complete bot with Flask and FastAPI
* [Send Messages](https://docs.hypersender.com/v2/packages-and-sdks/python/whatsapp/send-messages.md): reply with text, media, polls, and more
* [WhatsApp webhooks reference](https://docs.hypersender.com/v2/api-reference/whatsapp-webhooks/whatsapp-webhooks-introduction.md): every payload in full


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.