> ## 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.

# SMS Webhooks in Python: Delivery Reports and Incoming SMS

> Receive SMS webhooks in Python with Flask or FastAPI: verify the secret, get delivery reports, read incoming SMS, and alert when your phone goes offline.

## Overview

Hypersender sends an SMS webhook to your URL when a message is sent, delivered, fails, or expires, when your phone receives an SMS, and when the phone goes online or offline. 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.

## Set up the webhook

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

In the [Hypersender dashboard](https://app.hypersender.com), open your SMS instance, add a webhook with your public HTTPS URL, for example `https://example.com/sms/webhook`, and pick the events you want.

**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_SMS_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_SMS_WEBHOOK_SECRET"]
>
>
> @app.post("/sms/webhook")
> def sms_webhook():
>     if not hmac.compare_digest(request.headers.get("Authorization", ""), SECRET):
>         abort(401)
>
>     body = request.get_json()
>     print(body["event"], body["data"]["id"], body["data"].get("status"))
>
>     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_SMS_WEBHOOK_SECRET"]
>
>
> @app.post("/sms/webhook")
> async def sms_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"]["id"], body["data"].get("status"))
>
>     return {"status": "ok"}
> ```

> [!NOTE]
>
> The secret is sent exactly as you saved it, with no `Bearer` prefix. Compare it with `hmac.compare_digest`, not `==`.

## Payload

Every SMS webhook has two keys: `event` and `data`. For message events, `data` is the message:

```json theme={null}
{
  "event": "message.phone.received",
  "data": {
    "id": "9f8b7c6d-6666-4a2b-8c3d-4e5f6a7b8c9d",
    "phone_id": "9f8b7c6d-1111-4a2b-8c3d-4e5f6a7b8c9d",
    "request_id": null,
    "from_phone_number": "+12025550188",
    "to_phone_number": "+12025550101",
    "content": "Hi, is my order ready?",
    "status": "received",
    "sim": "SIM1",
    "tags": [],
    "failure_reason": null,
    "received_at": "2026-11-19 10:05:12"
  }
}
```

For `phone.*` events, `data` is the phone, with fields such as `is_online`, `last_heartbeat_at`, and `phone_number`. `request_id` is the value you passed to `send_message`, so you can match a delivery report to your own record. The [SMS webhooks reference](https://docs.hypersender.com/v2/api-reference/sms-webhooks/sms-webhooks-introduction.md) shows every field and header.

## SMS webhook events

| Event | Fires when |
| - | - |
| [`message.notification.scheduled`](https://docs.hypersender.com/v2/api-reference/sms-webhooks/messages-events/message-scheduled) | A message is waiting for its send time or the phone's sending rate |
| [`message.notification.failed`](https://docs.hypersender.com/v2/api-reference/sms-webhooks/messages-events/message-notification-failed) | Hypersender could not push the message to the phone |
| [`message.phone.sent`](https://docs.hypersender.com/v2/api-reference/sms-webhooks/messages-events/message-sent) | The phone handed the message to the carrier |
| [`message.phone.delivered`](https://docs.hypersender.com/v2/api-reference/sms-webhooks/messages-events/message-delivered) | The carrier confirmed delivery |
| [`message.send.failed`](https://docs.hypersender.com/v2/api-reference/sms-webhooks/messages-events/message-failed) | The phone could not send the message |
| [`message.send.expired`](https://docs.hypersender.com/v2/api-reference/sms-webhooks/messages-events/message-expired) | The message was not sent before it expired |
| [`message.phone.ussd`](https://docs.hypersender.com/v2/api-reference/sms-webhooks/messages-events/message-ussd) | The phone got a USSD or flash reply for a message you sent |
| [`message.phone.received`](https://docs.hypersender.com/v2/api-reference/sms-webhooks/messages-events/message-received) | The phone received an SMS |
| [`phone.heartbeat.received`](https://docs.hypersender.com/v2/api-reference/sms-webhooks/heartbeats/heartbeat-received) | An online phone sent a heartbeat |
| [`phone.heartbeat.online`](https://docs.hypersender.com/v2/api-reference/sms-webhooks/heartbeats/heartbeat-online) | The phone is back online |
| [`phone.heartbeat.missed`](https://docs.hypersender.com/v2/api-reference/sms-webhooks/heartbeats/heartbeat-missed) | No heartbeat for 16 minutes |
| [`phone.heartbeat.offline`](https://docs.hypersender.com/v2/api-reference/sms-webhooks/heartbeats/heartbeat-offline) | No heartbeat for about an hour; the phone is marked offline |
| [`phone.heartbeat.disabled`](https://docs.hypersender.com/v2/api-reference/sms-webhooks/heartbeats/heartbeat-disabled) | No heartbeat for 2 hours; checks stop |
| [`phone.logout`](https://docs.hypersender.com/v2/api-reference/sms-webhooks/phone-events/phone-logout) | The phone was logged out of the app |

## Handle each event

Route on `event`. This example auto-replies to incoming SMS, tracks delivery, and alerts when the phone goes offline:

> [tab] Basic Usage
>
> ```python theme={null}
> import logging
>
> from hypersender import Hypersender
>
> hs = Hypersender()
> log = logging.getLogger("sms")
>
>
> def handle(event: str, data: dict) -> None:
>     if event == "message.phone.received":
>         hs.sms.send_message(data["from_phone_number"], "Thanks for your message! We'll reply soon.")
>
>     elif event == "message.phone.delivered":
>         log.info("Delivered: %s", data["request_id"])
>
>     elif event == "message.send.failed":
>         log.warning("Failed: %s (%s)", data["request_id"], data["failure_reason"])
>
>     elif event == "phone.heartbeat.offline":
>         log.error("Phone %s is offline", data["phone_number"])
> ```
>
> Call `handle(body["event"], body["data"])` from your route after the secret check. For slow work, hand it to a background task (FastAPI `BackgroundTasks`, Celery, RQ) and return right away.

## Retries and duplicates

If your endpoint does not answer with a `2xx` in time, Hypersender retries, so the same event can arrive more than once and out of order.

* Use `event` plus `data["id"]` (and `data["status"]` for message events) as the key to skip duplicates.
* Compare `updated_at` before overwriting a newer state.

## Next steps

* [Send and Manage SMS](https://docs.hypersender.com/v2/packages-and-sdks/python/sms/send-and-manage-sms-messages.md): send, schedule, and list messages
* [Heartbeat Management](https://docs.hypersender.com/v2/packages-and-sdks/python/sms/heartbeat-management.md): check the phone's status on demand
* [SMS webhooks reference](https://docs.hypersender.com/v2/api-reference/sms-webhooks/sms-webhooks-introduction.md): every payload and header in full


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