# Test a WhatsApp webhook locally with ngrok or Cloudflare Tunnel

> Run a WhatsApp Cloud API webhook on localhost: a stdlib Python receiver, an ngrok or Cloudflare tunnel, and an override for one test number.

Published 2026-11-04. Z-API Omni team.

Run your receiver on a local port, expose it with `ngrok http 8080` or `cloudflared tunnel --url http://localhost:8080`, and save the tunnel's HTTPS address as the callback URL. Meta only delivers to an endpoint "on a public server" with a valid TLS certificate, and "self-signed certificates are not supported" ([Create a webhook endpoint, accessed 2026-11-04](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/create-webhook-endpoint)). Use the `https://` address the tunnel prints. Keep signature verification on while you test. If the app already serves production, point only your test number at the tunnel with a webhook override.

## A receiver with the standard library only

This receiver runs on Python 3.9 or later with no packages. It answers the verification GET, checks `X-Hub-Signature-256` against the raw bytes, returns 200, and only then parses and prints the payload.

```python
# receiver.py. Run: APP_SECRET=... VERIFY_TOKEN=... python3 receiver.py
import hashlib
import hmac
import json
import os
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlsplit

APP_SECRET = os.environ["APP_SECRET"].encode()      # your app secret
VERIFY_TOKEN = os.environ["VERIFY_TOKEN"].encode()  # the string you type as Verify token
PORT = int(os.environ.get("PORT", "8080"))
PATH = "/webhook"

def valid_signature(raw, header):
    if not header or not header.startswith("sha256="):
        return False
    expected = hmac.new(APP_SECRET, raw, hashlib.sha256).hexdigest().encode()
    # http.server decodes headers as Latin-1, so this round-trips any byte value
    return hmac.compare_digest(header[len("sha256="):].encode("latin-1"), expected)

def summarize(payload):
    for entry in payload.get("entry", []):
        for change in entry.get("changes", []):
            value = change.get("value", {})
            for msg in value.get("messages", []):
                sender = msg.get("from") or msg.get("from_user_id")
                print(f"message {msg.get('id')} type={msg.get('type')} from={sender}", flush=True)
            for st in value.get("statuses", []):
                recipient = st.get("recipient_id") or st.get("recipient_user_id")
                print(f"status {st.get('status')} for {st.get('id')} to={recipient}", flush=True)

class Handler(BaseHTTPRequestHandler):
    def reply(self, status, body=b""):
        self.send_response(status)
        self.send_header("Content-Type", "text/plain")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def do_GET(self):
        url = urlsplit(self.path)
        query = parse_qs(url.query)
        mode = query.get("hub.mode", [""])[0]
        token = query.get("hub.verify_token", [""])[0].encode()
        challenge = query.get("hub.challenge", [""])[0]
        if url.path == PATH and mode == "subscribe" and challenge and hmac.compare_digest(token, VERIFY_TOKEN):
            print("WEBHOOK VERIFIED", flush=True)
            self.reply(200, challenge.encode())  # echo it as received, no JSON around it
        else:
            self.reply(403)

    def do_POST(self):
        raw = self.rfile.read(int(self.headers.get("Content-Length", 0)))
        if urlsplit(self.path).path != PATH or not valid_signature(raw, self.headers.get("X-Hub-Signature-256")):
            print("rejected: wrong path or bad signature", flush=True)
            self.reply(401)
            return
        self.reply(200)  # answer first, then look at the payload
        try:
            payload = json.loads(raw)
        except ValueError:
            print("signed body is not JSON", flush=True)
            return
        print(json.dumps(payload, indent=2), flush=True)
        summarize(payload)

if __name__ == "__main__":
    print(f"listening on http://127.0.0.1:{PORT}{PATH}", flush=True)
    ThreadingHTTPServer(("127.0.0.1", PORT), Handler).serve_forever()
```

The GET branch follows Meta's rule: compare `hub.verify_token` with your stored string, then "respond with HTTP status `200` and the `hub.challenge` value". The WhatsApp page calls the challenge "a random string", while Meta's general Graph API webhooks page calls it an `int` ([Graph API webhooks](https://developers.facebook.com/docs/graph-api/webhooks/getting-started)). Echo it back untouched and the difference doesn't matter.

The POST branch hashes the body bytes before any JSON parsing, which is why it reads `rfile` directly. [Webhook signature verification](/academy/articles/whatsapp-webhook-signature-verification-x-hub-signature-256/) explains why re-serialized JSON fails the check and shows how to sign a test body with `openssl`. `ThreadingHTTPServer` handles requests in parallel, because Meta "attempts to deliver webhooks concurrently" ([Throughput, accessed 2026-11-04](https://developers.facebook.com/documentation/business-messaging/whatsapp/throughput)). Meta also says batching "cannot be guaranteed", so each POST is treated on its own.

Check the handshake locally before you open a tunnel:

```shell
curl -i "http://localhost:8080/webhook?hub.mode=subscribe&hub.verify_token=$VERIFY_TOKEN&hub.challenge=123"
```

You want `200` and a body of `123`.

## Open a tunnel

### ngrok

Run `ngrok http 8080`. The free plan includes one automatically assigned dev domain. ngrok says it "doesn't change when you restart the agent, and `ngrok http` uses it automatically" ([ngrok free plan limits, accessed 2026-11-04](https://ngrok.com/docs/pricing-limits/free-plan-limits/)). Older guides say the free URL changes on every restart. On the current free plan you save the callback once.

The free tier also puts an interstitial warning page "in front of all HTML browser traffic". ngrok adds that this "does not impact users serving APIs or accessing ngrok endpoints programmatically" ([ngrok free plan limits, accessed 2026-11-04](https://ngrok.com/docs/pricing-limits/free-plan-limits/)). Meta's servers call your callback programmatically, and you couldn't add the `ngrok-skip-browser-warning` header to Meta's requests anyway. The header and the non-standard User-Agent trick matter when you open the URL in a browser or call it from your own scripts.

The free quotas are 1 GB of data out, 20,000 HTTP requests a month and 4,000 HTTP requests a minute. Every status webhook from a test send counts as a request.

### Cloudflare quick tunnel

Run `cloudflared tunnel --url http://localhost:8080` and Cloudflare prints a temporary `trycloudflare.com` address. "The hostname changes each time you create a Quick Tunnel," so you re-save the callback or the override on every run ([Cloudflare Quick Tunnels, accessed 2026-11-04](https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/do-more-with-tunnels/trycloudflare/)). Each quick tunnel accepts up to 200 in-flight requests and answers 429 above that. Cloudflare says quick tunnels "are for testing and development" and "have no uptime guarantee", and points to a named tunnel for production.

## Point Meta at the tunnel

### The App Dashboard

Open App Dashboard > WhatsApp > Webhooks > Configuration. Paste `https://YOUR_TUNNEL_HOST/webhook` into Callback URL, type your verify token, and click Verify and save ([Create a test webhook endpoint, accessed 2026-11-04](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/set-up-whatsapp-echo-bot)). Apps built on the "Connect with customers through WhatsApp" use case have the same form under Use cases > Customize > Configuration ([Webhooks overview, accessed 2026-11-04](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/overview)). The receiver prints `WEBHOOK VERIFIED`. Then subscribe the `messages` field.

This sets the app's default callback, which every subscribed Messaging account uses unless an override exists. On an app that also runs production, that moves production traffic to your laptop.

Meta's pages disagree on a scripted alternative. The WhatsApp create-endpoint page mentions the Application Subscriptions API. The Graph `app/subscriptions` reference says "WhatsApp webhooks must be configured using the App Dashboard", and its `object` values don't include `whatsapp_business_account` ([app/subscriptions reference, accessed 2026-11-04](https://developers.facebook.com/docs/graph-api/reference/app/subscriptions/)). Use the dashboard for the app default.

### An override for one test number

A webhook override sends one business phone number's events, or one Messaging account's, to a different callback. Meta resolves the callback in this order: the phone number, then the Messaging account, then the app ([Webhook overrides, accessed 2026-11-04](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/override)). The `messages` field supports overrides. Template and account-level webhooks don't, so test those through the dashboard. The app must already be subscribed to the Messaging account, and both `override_callback_uri` (200 characters at most) and `verify_token` are required.

```shell
# Set the override for one number
curl -X POST "https://graph.facebook.com/v26.0/$PHONE_NUMBER_ID" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d "{\"webhook_configuration\": {\"override_callback_uri\": \"$TUNNEL_URL/webhook\", \"verify_token\": \"$VERIFY_TOKEN\"}}"

# See which callback wins at each level
curl "https://graph.facebook.com/v26.0/$PHONE_NUMBER_ID?fields=webhook_configuration" \
  -H "Authorization: Bearer $ACCESS_TOKEN"

# Remove it when you stop the tunnel
curl -X POST "https://graph.facebook.com/v26.0/$PHONE_NUMBER_ID" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"webhook_configuration": {"override_callback_uri": ""}}'
```

The GET returns `phone_number`, `whatsapp_business_account` and `application` keys, one callback URL for each level that has one. For a whole Messaging account, send `override_callback_uri` and `verify_token` to `POST /WABA_ID/subscribed_apps` instead. To remove that one, subscribe the app to the Messaging account again with no body.

Remove the override before you close the tunnel. While it exists, that number's events skip the production callback. Meta also retries failed deliveries "a few more times with decreasing frequency over the next 7 days", so a dead tunnel keeps collecting retries for that number.

## The Test button and real messages

On the Webhooks configuration page, scroll to the `messages` field and click Test. Meta sends a sample `messages` payload to your callback. Meta says "messages test webhooks work in both modes", Development and Live, while some other test webhooks only work in one of them. Meta's pages don't say whether that sample carries a valid `X-Hub-Signature-256`. If the receiver logs a 401 for it, leave the check on and test with a real message instead.

A real event needs a real sender. Message your business number from a WhatsApp account, or use the test phone number Meta creates during [Cloud API setup](/academy/articles/whatsapp-cloud-api-test-number-get-started/). Meta's get-started page tells you to keep the test phone number ID and Messaging account ID; the override call above needs the first ([Get started, accessed 2026-11-04](https://developers.facebook.com/documentation/business-messaging/whatsapp/get-started)). Sending a message to your own phone from that number should produce `sent` and `delivered` statuses on the same callback.

## Replay requests from the ngrok inspector

Open http://localhost:4040 on the machine that runs ngrok. It lists each request that came through the tunnel, and the Replay button sends one again ([ngrok web inspection, accessed 2026-11-04](https://ngrok.com/docs/agent/web-inspection-interface/)). A replay with an unchanged body should pass the signature check, since the HMAC covers only the body and your app secret. If you edit the body in the replay editor, the receiver should answer 401. Both follow from Meta's signature rule; neither ngrok nor Meta states it.

An unchanged replay is also a duplicate, the same thing Meta's retries produce. Use it to test the dedupe step your real handler needs, covered in [the idempotency pattern for n8n](/academy/articles/n8n-duplicate-webhooks-idempotency/) and [the FastAPI receiver](/academy/articles/whatsapp-webhook-python-fastapi-receive-messages/).

If Verify and save fails or real messages never show up, work through the [webhook troubleshooting checklist](/academy/articles/whatsapp-webhook-not-receiving-messages-troubleshooting/). Start with the curl handshake above, run against the tunnel URL instead of localhost.

*Z-API Omni team*
