WhatsApp· 8 min read

WhatsApp campaign delivery report from status webhooks


Build a WhatsApp campaign report from status webhooks; the send response only says Meta accepted the message. Store each wamid against its campaign when the send returns, and log every status webhook. Count each message once, at the furthest status it reached. Call a message dropped only after its time-to-live plus a buffer has passed. The Python script below does all of this with SQLite from the standard library.

Tag every send with a campaign key

The biz_opaque_callback_data field carries a string of your choice from the send request into the status webhooks. Meta’s changelog entry of November 14, 2023 added it “to free-form messages for including arbitrary strings in messages webhooks”. On January 26, 2024, Meta “Changed biz_opaque_callback_data character maximum from 256 to 512” (Meta changelog, accessed 2026-11-16). Guides that give 200 or 256 characters are out of date.

The status webhook reference describes the echo. The field is a “String assigned by the business to the biz_opaque_callback_data property in the send message request”. It sits on each statuses[] item, next to id, status and timestamp. The syntax comment says “Only included if message sent with biz_opaque_callback_data” (Meta status webhook reference, accessed 2026-11-16).

That page does not say whether failed statuses carry the field. None of its example payloads include it. Don’t build the report on the assumption that a failure will tell you its campaign.

Meta’s send guides read today don’t show where the field goes in the request body. Meta’s OpenAPI spec defines it as a top-level string with maxLength: 512 and says “Cloud API does not process this field” (Meta OpenAPI spec, business-messaging-api_v23.0.yaml, accessed 2026-11-16). That definition sits on the calling payload. The changelog entries above don’t say when templates gained the field.

Put it at the top level of the body you POST to https://graph.facebook.com/v26.0/PHONE_NUMBER_ID/messages, next to to and type. Confirm the echo on one live template send before a campaign depends on it.

{
  "messaging_product": "whatsapp",
  "to": "RECIPIENT_PHONE_NUMBER",
  "type": "template",
  "biz_opaque_callback_data": "bf-2026-11|c-2004",
  "template": {
    "name": "TEMPLATE_NAME",
    "language": { "code": "LANGUAGE_CODE" }
  }
}

Put the campaign ID and your own recipient key in the string, split by a character your IDs never contain. Leave out phone numbers and names. The webhook already carries recipient_id, or recipient_user_id for a BSUID, and the string lands in every log that stores raw webhooks.

Key the report on the wamid

The send response returns messages[0].id, the wamid. Meta describes it as the ID that “appears in associated messages webhooks, such as sent, read, and delivered webhooks” (Meta send messages guide, accessed 2026-11-16). Write a row that ties the wamid to its campaign before anything else reads the response. Every later status joins on it.

Use the callback data as the fallback. If your HTTP client times out after Meta accepted the message, you never see the wamid. A status that echoes the callback data still names the campaign. That use is our inference from the field’s definition; Meta’s pages don’t describe it.

The response can also carry message_status. The Message API reference lists three values: accepted, held_for_quality_assessment and paused (Meta Message API reference, accessed 2026-11-16). The send guide says it appears only for a template message “that uses a template that is being paced”. Meta’s example response leaves it out.

Meta’s pacing page says that for paced templates, Cloud API “will always include a message_status property that will have a value of accepted” (Meta template pacing, accessed 2026-11-16). The pages disagree on how often the field appears, so treat it as optional. Store it when present. In the report, “accepted” means the API returned a wamid, whatever message_status said.

Held messages need their own column. Meta’s pacing page says held messages are released “and sent normally” after positive feedback. After negative feedback, “Each held message will be dropped and trigger a messages webhook with "status":"failed"”, code 132015 (Meta template pacing).

Meta’s stated goal is that “even if paced, campaign messages with highest throughput still get delivered within an hour”, at the 99th percentile. A held message can sit with no status for about that long, then end as delivered or as failed. Template quality, pacing and pauses covers why pacing starts.

Store sends and statuses in SQLite

The script uses four tables. campaigns holds each campaign’s TTL. sends maps each wamid to a campaign and records whether the mapping came from the response or the callback data. status_log keeps every status as received, and message_state keeps the furthest status per message.

The furthest-status rule comes from message statuses and their ranks: sent 1, failed 2, delivered 3, read 4, played 5. An update only moves a message up. That absorbs retried webhooks and statuses that arrive out of order. The Postgres versions of these tables are in the conversation storage schema.

The guarded update needs SQLite 3.24.0 or later. “UPSERT syntax was added to SQLite with version 3.24.0 (2018-06-04)” (SQLite UPSERT, accessed 2026-11-16). The SQLite version depends on how your Python was built, so the script prints it and stops below 3.24.0.

Save the script as report.py and run python3 report.py. It needs Python 3.9 or later and nothing outside the standard library.

"""Per-campaign delivery report from WhatsApp Cloud API status webhooks.

Standard library only. Run with: python3 report.py
"""
import json
import sqlite3
import sys
import time

if sqlite3.sqlite_version_info < (3, 24, 0):
    sys.exit("SQLite %s is too old: UPSERT needs 3.24.0 or later." % sqlite3.sqlite_version)
print("SQLite", sqlite3.sqlite_version)

DB_PATH = ":memory:"      # a file such as "campaigns.db" keeps the data between runs
DEFAULT_TTL = 30 * 86400  # Meta's default TTL for everything except authentication templates
DROP_BUFFER = 6 * 3600    # margin after the TTL; our choice, Meta only asks for "a small buffer"
RANK = {"sent": 1, "failed": 2, "delivered": 3, "read": 4, "played": 5}

NOW = int(time.time())
T0 = NOW - 31 * 86400     # sample campaign sent 31 days ago
T1 = NOW - 3600           # sample campaign sent one hour ago

SCHEMA = """
CREATE TABLE IF NOT EXISTS campaigns (
  campaign_id TEXT PRIMARY KEY,
  ttl_seconds INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS sends (
  wamid          TEXT PRIMARY KEY,
  campaign_id    TEXT NOT NULL,
  recipient_key  TEXT NOT NULL,
  sent_at        INTEGER NOT NULL,
  message_status TEXT,
  source         TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS status_log (
  wamid         TEXT NOT NULL,
  status        TEXT NOT NULL,
  ts            INTEGER NOT NULL,
  error_code    INTEGER,
  callback_data TEXT,
  raw           TEXT NOT NULL,
  UNIQUE (wamid, status, ts)
);
CREATE TABLE IF NOT EXISTS message_state (
  wamid       TEXT PRIMARY KEY,
  status      TEXT NOT NULL,
  status_rank INTEGER NOT NULL,
  status_ts   INTEGER NOT NULL,
  error_code  INTEGER
);
"""

REPORT_SQL = """
WITH m AS (
  SELECT s.campaign_id,
         COALESCE(s.message_status, '') AS message_status,
         COALESCE(ms.status_rank, 0) AS status_rank,
         :now > s.sent_at + c.ttl_seconds + :buffer AS past_ttl
  FROM sends s
  JOIN campaigns c ON c.campaign_id = s.campaign_id
  LEFT JOIN message_state ms ON ms.wamid = s.wamid
)
SELECT campaign_id,
       COUNT(*) AS accepted,
       SUM(status_rank >= 3) AS delivered_or_read,
       SUM(status_rank >= 4) AS read_or_played,
       SUM(status_rank = 2) AS failed,
       SUM(status_rank = 1 AND NOT past_ttl) AS sent_waiting,
       SUM(status_rank = 0 AND NOT past_ttl) AS no_status_yet,
       SUM(status_rank = 0 AND NOT past_ttl
           AND message_status = 'held_for_quality_assessment') AS held,
       SUM(status_rank <= 1 AND past_ttl) AS presumed_dropped
FROM m
GROUP BY campaign_id
ORDER BY campaign_id
"""

FAILED_SQL = """
SELECT s.campaign_id, ms.error_code, COUNT(*) AS messages
FROM sends s
JOIN message_state ms ON ms.wamid = s.wamid
WHERE ms.status_rank = 2
GROUP BY s.campaign_id, ms.error_code
ORDER BY s.campaign_id, messages DESC
"""

UNATTRIBUTED_SQL = """
SELECT COUNT(*) FROM message_state ms
WHERE NOT EXISTS (SELECT 1 FROM sends s WHERE s.wamid = ms.wamid)
"""


def add_campaign(db, campaign_id, ttl_seconds=DEFAULT_TTL):
    db.execute(
        "INSERT INTO campaigns (campaign_id, ttl_seconds) VALUES (?, ?) "
        "ON CONFLICT (campaign_id) DO NOTHING",
        (campaign_id, ttl_seconds),
    )


def record_send(db, campaign_id, recipient_key, sent_at, response):
    """Call this as soon as the /messages request returns."""
    message = response["messages"][0]
    add_campaign(db, campaign_id)
    db.execute(
        """
        INSERT INTO sends (wamid, campaign_id, recipient_key, sent_at, message_status, source)
        VALUES (?, ?, ?, ?, ?, 'response')
        ON CONFLICT (wamid) DO UPDATE SET
          sent_at = excluded.sent_at,
          message_status = excluded.message_status,
          source = 'response'
        WHERE sends.source = 'callback'
        """,
        (message["id"], campaign_id, recipient_key, sent_at, message.get("message_status")),
    )


def ingest_status(db, status):
    wamid = status["id"]
    ts = int(status["timestamp"])
    errors = status.get("errors") or [{}]
    code = errors[0].get("code")
    callback = status.get("biz_opaque_callback_data")
    db.execute(
        "INSERT OR IGNORE INTO status_log (wamid, status, ts, error_code, callback_data, raw) "
        "VALUES (?, ?, ?, ?, ?, ?)",
        (wamid, status["status"], ts, code, callback, json.dumps(status)),
    )
    if callback and "|" in callback:
        # fallback attribution when the send response was never stored
        campaign_id, recipient_key = callback.split("|", 1)
        add_campaign(db, campaign_id)
        db.execute(
            "INSERT OR IGNORE INTO sends (wamid, campaign_id, recipient_key, sent_at, source) "
            "VALUES (?, ?, ?, ?, 'callback')",
            (wamid, campaign_id, recipient_key, ts),
        )
    rank = RANK.get(status["status"])
    if rank is None:
        return
    db.execute(
        """
        INSERT INTO message_state (wamid, status, status_rank, status_ts, error_code)
        VALUES (?, ?, ?, ?, ?)
        ON CONFLICT (wamid) DO UPDATE SET
          status = excluded.status,
          status_rank = excluded.status_rank,
          status_ts = excluded.status_ts,
          error_code = excluded.error_code
        WHERE message_state.status_rank < excluded.status_rank
        """,
        (wamid, status["status"], rank, ts, code),
    )


def ingest_webhook(db, payload):
    for entry in payload.get("entry", []):
        for change in entry.get("changes", []):
            if change.get("field") == "messages":
                for status in change["value"].get("statuses", []):
                    ingest_status(db, status)


# Sample data, trimmed to the fields this script reads.
def status(wamid, value, ts, code=None, callback=None):
    item = {"id": wamid, "status": value, "timestamp": str(ts), "recipient_id": "RECIPIENT_WA_ID"}
    if code:
        item["errors"] = [{"code": code}]
    if callback:
        item["biz_opaque_callback_data"] = callback
    return item


def webhook(*statuses):
    return {
        "object": "whatsapp_business_account",
        "entry": [{
            "id": "WABA_ID",
            "changes": [{
                "field": "messages",
                "value": {
                    "messaging_product": "whatsapp",
                    "metadata": {"phone_number_id": "PHONE_NUMBER_ID"},
                    "statuses": list(statuses),
                },
            }],
        }],
    }


# (campaign, recipient key, sent at, send response). wamid.B4 is missing: its response was lost.
SENDS = [
    ("oct-restock", "c-1001", T0, {"messages": [{"id": "wamid.A1"}]}),
    ("oct-restock", "c-1002", T0, {"messages": [{"id": "wamid.A2"}]}),
    ("oct-restock", "c-1003", T0, {"messages": [{"id": "wamid.A3"}]}),
    ("oct-restock", "c-1004", T0, {"messages": [{"id": "wamid.A4"}]}),
    ("oct-restock", "c-1005", T0, {"messages": [{"id": "wamid.A5"}]}),
    ("bf-2026-11", "c-2001", T1, {"messages": [{"id": "wamid.B1", "message_status": "accepted"}]}),
    ("bf-2026-11", "c-2002", T1, {"messages": [{"id": "wamid.B2"}]}),
    ("bf-2026-11", "c-2003", T1,
     {"messages": [{"id": "wamid.B3", "message_status": "held_for_quality_assessment"}]}),
    ("bf-2026-11", "c-2005", T1, {"messages": [{"id": "wamid.B5"}]}),
]

SAMPLE_WEBHOOKS = {
    "oct_restock": webhook(
        status("wamid.A1", "sent", T0 + 5, callback="oct-restock|c-1001"),
        status("wamid.A1", "read", T0 + 900, callback="oct-restock|c-1001"),
        status("wamid.A1", "delivered", T0 + 60, callback="oct-restock|c-1001"),  # arrives after read
        status("wamid.A2", "delivered", T0 + 70, callback="oct-restock|c-1002"),
        status("wamid.A2", "delivered", T0 + 70, callback="oct-restock|c-1002"),  # retried duplicate
        status("wamid.A3", "failed", T0 + 8, code=131049),
        status("wamid.A4", "sent", T0 + 6, callback="oct-restock|c-1004"),
    ),
    "black_friday": webhook(
        status("wamid.B1", "sent", T1 + 5, callback="bf-2026-11|c-2001"),
        status("wamid.B1", "read", T1 + 40, callback="bf-2026-11|c-2001"),  # delivered skipped
        status("wamid.B2", "failed", T1 + 9, code=131026),
        status("wamid.B4", "sent", T1 + 6, callback="bf-2026-11|c-2004"),
        status("wamid.B4", "delivered", T1 + 50, callback="bf-2026-11|c-2004"),
        status("wamid.B5", "sent", T1 + 7, callback="bf-2026-11|c-2005"),
        status("wamid.B9", "delivered", T1 + 30),  # a wamid this pipeline never stored
    ),
}


def main():
    db = sqlite3.connect(DB_PATH)
    db.executescript(SCHEMA)
    for campaign_id, recipient_key, sent_at, response in SENDS:
        record_send(db, campaign_id, recipient_key, sent_at, response)
    for payload in SAMPLE_WEBHOOKS.values():
        ingest_webhook(db, payload)
    db.commit()

    cursor = db.execute(REPORT_SQL, {"now": NOW, "buffer": DROP_BUFFER})
    columns = [col[0] for col in cursor.description]
    for row in cursor.fetchall():
        print()
        for name, value in zip(columns, row):
            print("  %-18s %s" % (name, value))

    print("\nFailed by error code")
    for campaign_id, code, count in db.execute(FAILED_SQL):
        print("  %-12s %-8s %s" % (campaign_id, code, count))

    orphans = db.execute(UNATTRIBUTED_SQL).fetchone()[0]
    print("\nStatuses with no campaign:", orphans)
    db.close()


if __name__ == "__main__":
    main()

In oct-restock, sent 31 days ago, a read arrives before its delivered, a delivered arrives twice, and two messages end with no delivered, read or failed status. In bf-2026-11, sent an hour ago, one message is held, one send response was lost, and one status belongs to a wamid the script never stored.

In production, call record_send from the code that sends, and ingest_webhook from your webhook handler after it verifies the signature. Replace SENDS and SAMPLE_WEBHOOKS with those calls.

What the report counts

accepted is the total. The other buckets are exclusive and add up to it, apart from read_or_played and held, which are subsets. For the sample data the report prints these values:

Column What it counts oct-restock bf-2026-11
accepted Sends with a wamid, from the response or recovered from callback data 5 5
delivered_or_read Furthest status delivered, read or played 2 2
read_or_played Furthest status read or played 1 1
failed Furthest status failed 1 1
sent_waiting Only sent, still inside TTL plus buffer 0 1
no_status_yet No status, still inside TTL plus buffer 0 1
held Of those, held for quality assessment at send time 0 1
presumed_dropped No delivered, read or failed after TTL plus buffer 2 0

delivered_or_read includes read messages because Meta can skip the delivered webhook: “it’s implied that the message was delivered since it was read” (status webhook reference). This is also the only bucket that can carry a Meta fee. “Businesses are only charged when a message is delivered. Meta does not charge for messages sent” (Meta pricing, accessed 2026-11-16).

The script also prints failures by code and the statuses it could not attribute. In the sample, wamid.B9 has no send row and no callback data. A non-zero count points at a send path that skips record_send.

Read the failed column by error code

Group failures by errors[0].code, stored as an integer, because each code calls for a different next step. Descriptions are from Meta’s error codes reference (Meta error codes, accessed 2026-11-16).

Code Meta’s description What to do
131026 “Unable to deliver message” Don’t resend on WhatsApp; confirm the number through another channel; see error 131026
131049 “This message was not delivered to maintain healthy ecosystem engagement.” Wait at least 24 hours; see error 131049
131050 The recipient stopped marketing messages from you “Do not retry sending messages to this user as they will not be received.”
132015 Template paused for low quality Fix the template before the next send
130472 “Message was not sent as part of an experiment.” Count it apart from list problems
131000 “Message failed to send due to an unknown error.” Meta says “Try again”

A failure bucket that grows from a resend loop distorts the report. The 131049 article quotes Meta on how early resends affect campaign reporting. The remaining codes and their retry rules are in the error codes reference.

When a message counts as dropped

A message with no delivered, read or failed is unknown until its TTL runs out. Meta’s TTL is “All messages except authentication templates: 30 days” and “Authentication templates: 10 minutes”. “The platform drops messages it cannot deliver within the default or customized TTL” (send messages guide).

Meta’s instruction is to assume the message was dropped if no delivered status arrives “before the TTL is exceeded”. It adds: “Build in a small buffer before assuming the message was dropped.” Expiry produces no error code, so presumed_dropped comes from the clock alone. The script’s 6-hour buffer is our choice; Meta gives no number.

Templates can carry a custom TTL in message_send_ttl_seconds, set when the template is created or updated (Meta time-to-live, accessed 2026-11-16):

Category Allowed range Default
Authentication 30 to 900 seconds 10 minutes
Utility 30 to 43,200 seconds 30 days
Marketing (Marketing Messages API only) 43,200 to 2,592,000 seconds 30 days

Set campaigns.ttl_seconds to the TTL of the template the campaign used. Call add_campaign(db, CAMPAIGN_ID, TTL_SECONDS) before the first record_send; later calls leave it unchanged. With the default, a campaign sent today reports its final presumed_dropped count 30 days and 6 hours from now. The marketing row applies only to the Marketing Messages API.

Check the totals against Meta’s analytics

Meta’s analytics and template_analytics give aggregates you can set beside your own counts. The analytics article covers both. Template read and click counts there reset after 7 days, and the figures are approximate, so expect small gaps. Your status log counts per message and keeps every row. For clicks per person, use a token in the button URL, as in dynamic URL suffixes.

Z-API Omni team