# I-test nang local ang WhatsApp webhook gamit ang ngrok o Cloudflare Tunnel

> Patakbuhin ang WhatsApp Cloud API webhook sa localhost: stdlib na Python receiver, ngrok o Cloudflare tunnel, at override para sa isang test number.

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

Patakbuhin ang receiver mo sa isang local port, i-expose ito gamit ang `ngrok http 8080` o `cloudflared tunnel --url http://localhost:8080`, at i-save ang HTTPS address ng tunnel bilang callback URL. Nagde-deliver lang ang Meta sa endpoint na "nasa public server" na may valid na TLS certificate, at "hindi suportado ang mga self-signed certificate" ([Create a webhook endpoint, na-access noong 2026-11-04](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/create-webhook-endpoint)). Gamitin ang `https://` address na ipini-print ng tunnel. Panatilihing naka-on ang signature verification habang nagte-test ka. Kung nagse-serve na ng production ang app, ang test number mo lang ang ituro sa tunnel gamit ang webhook override.

## Receiver na standard library lang ang gamit

Tumatakbo ang receiver na ito sa Python 3.9 o mas bago nang walang package. Sinasagot nito ang verification GET, chine-check ang `X-Hub-Signature-256` laban sa raw bytes, nagbabalik ng 200, at saka lang pina-parse at ipini-print ang 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()
```

Sinusunod ng GET branch ang patakaran ng Meta: ikumpara ang `hub.verify_token` sa string na itinabi mo, saka "sumagot ng HTTP status `200` at ng value ng `hub.challenge`". Tinatawag ng WhatsApp page ang challenge na "isang random string", samantalang `int` naman ang tawag dito ng pangkalahatang Graph API webhooks page ng Meta ([Graph API webhooks](https://developers.facebook.com/docs/graph-api/webhooks/getting-started)). I-echo ito pabalik nang hindi ginagalaw at hindi na mahalaga ang pagkakaiba.

Hina-hash ng POST branch ang body bytes bago ang anumang JSON parsing, kaya direkta nitong binabasa ang `rfile`. Ipinapaliwanag ng [webhook signature verification](/academy/fil/articles/whatsapp-webhook-signature-verification-x-hub-signature-256/) kung bakit bumabagsak sa check ang JSON na na-serialize ulit, at ipinapakita nito kung paano mag-sign ng test body gamit ang `openssl`. Sabay-sabay na hina-handle ng `ThreadingHTTPServer` ang mga request, dahil ang Meta ay "sumusubok mag-deliver ng mga webhook nang sabay-sabay" ([Throughput, na-access noong 2026-11-04](https://developers.facebook.com/documentation/business-messaging/whatsapp/throughput)). Sinasabi rin ng Meta na ang batching ay "hindi magagarantiya", kaya hiwalay na tinatrato ang bawat POST.

I-check ang handshake nang local bago ka magbukas ng tunnel:

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

Ang hinahanap mo ay `200` at body na `123`.

## Magbukas ng tunnel

### ngrok

Patakbuhin ang `ngrok http 8080`. Kasama sa free plan ang isang awtomatikong naka-assign na dev domain. Sinasabi ng ngrok na "hindi ito nagbabago kapag ni-restart mo ang agent, at awtomatiko itong ginagamit ng `ngrok http`" ([ngrok free plan limits, na-access noong 2026-11-04](https://ngrok.com/docs/pricing-limits/free-plan-limits/)). Sinasabi ng mga lumang gabay na nagbabago ang libreng URL sa bawat restart. Sa kasalukuyang free plan, isang beses mo lang ise-save ang callback.

Naglalagay din ang free tier ng interstitial warning page "sa harap ng lahat ng HTML browser traffic". Dagdag ng ngrok na "hindi nito naaapektuhan ang mga user na nagse-serve ng API o nag-a-access ng mga ngrok endpoint nang programmatic" ([ngrok free plan limits, na-access noong 2026-11-04](https://ngrok.com/docs/pricing-limits/free-plan-limits/)). Programmatic na tinatawag ng mga server ng Meta ang callback mo, at hindi mo rin naman maidadagdag ang `ngrok-skip-browser-warning` header sa mga request ng Meta. May silbi lang ang header at ang trick na hindi standard na User-Agent kapag binuksan mo ang URL sa browser o tinawag mula sa sarili mong mga script.

Ang libreng quota ay 1 GB na data out, 20,000 HTTP request bawat buwan at 4,000 HTTP request bawat minuto. Bilang na request ang bawat status webhook mula sa isang test send.

### Cloudflare quick tunnel

Patakbuhin ang `cloudflared tunnel --url http://localhost:8080` at magpi-print ang Cloudflare ng pansamantalang `trycloudflare.com` address. "Nagbabago ang hostname sa bawat paggawa mo ng Quick Tunnel," kaya ise-save mo ulit ang callback o ang override sa bawat run ([Cloudflare Quick Tunnels, na-access noong 2026-11-04](https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/do-more-with-tunnels/trycloudflare/)). Tumatanggap ang bawat quick tunnel ng hanggang 200 in-flight na request at sumasagot ng 429 kapag lumampas doon. Sinasabi ng Cloudflare na ang mga quick tunnel ay "para sa testing at development" at "walang garantiya sa uptime", at itinuturo nito ang named tunnel para sa production.

## Ituro ang Meta sa tunnel

### Ang App Dashboard

Buksan ang App Dashboard > WhatsApp > Webhooks > Configuration. I-paste ang `https://YOUR_TUNNEL_HOST/webhook` sa Callback URL, i-type ang verify token mo, at i-click ang Verify and save ([Create a test webhook endpoint, na-access noong 2026-11-04](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/set-up-whatsapp-echo-bot)). May parehong form ang mga app na binuo sa use case na "Connect with customers through WhatsApp" sa ilalim ng Use cases > Customize > Configuration ([Webhooks overview, na-access noong 2026-11-04](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/overview)). Magpi-print ang receiver ng `WEBHOOK VERIFIED`. Pagkatapos ay i-subscribe ang `messages` field.

Itinatakda nito ang default na callback ng app, na ginagamit ng bawat naka-subscribe na Messaging account maliban kung may override. Sa app na nagpapatakbo rin ng production, inililipat nito ang production traffic sa laptop mo.

Hindi nagkakasundo ang mga page ng Meta sa scripted na alternatibo. Binabanggit ng WhatsApp create-endpoint page ang Application Subscriptions API. Sinasabi naman ng Graph `app/subscriptions` reference na "kailangang i-configure ang mga WhatsApp webhook gamit ang App Dashboard", at hindi kasama ang `whatsapp_business_account` sa mga `object` value nito ([app/subscriptions reference, na-access noong 2026-11-04](https://developers.facebook.com/docs/graph-api/reference/app/subscriptions/)). Gamitin ang dashboard para sa default ng app.

### Override para sa isang test number

Ipinapadala ng webhook override ang mga event ng isang business phone number, o ng isang Messaging account, sa ibang callback. Ganito ang pagkakasunod ng pag-resolve ng Meta sa callback: ang phone number, saka ang Messaging account, saka ang app ([Webhook overrides, na-access noong 2026-11-04](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/override)). Suportado ng `messages` field ang override. Hindi suportado ng template at account-level na webhook, kaya i-test ang mga iyon sa dashboard. Dapat naka-subscribe na ang app sa Messaging account, at parehong required ang `override_callback_uri` (hanggang 200 character) at `verify_token`.

```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": ""}}'
```

Nagbabalik ang GET ng mga key na `phone_number`, `whatsapp_business_account` at `application`, isang callback URL para sa bawat level na mayroon nito. Para sa buong Messaging account, ipadala na lang ang `override_callback_uri` at `verify_token` sa `POST /WABA_ID/subscribed_apps`. Para tanggalin iyon, i-subscribe ulit ang app sa Messaging account nang walang body.

Tanggalin ang override bago mo isara ang tunnel. Habang naroon ito, nilalaktawan ng mga event ng number na iyon ang production callback. Nire-retry din ng Meta ang mga pumalyang delivery "nang ilang beses pa na pabawas nang pabawas ang dalas sa susunod na 7 araw", kaya patuloy na nag-iipon ng retry ang patay na tunnel para sa number na iyon.

## Ang Test button at mga totoong mensahe

Sa Webhooks configuration page, mag-scroll sa `messages` field at i-click ang Test. Nagpapadala ang Meta ng sample na `messages` payload sa callback mo. Sinasabi ng Meta na "gumagana sa parehong mode ang mga messages test webhook", Development at Live, samantalang sa isa lang sa mga ito gumagana ang ilang ibang test webhook. Hindi sinasabi ng mga page ng Meta kung may valid na `X-Hub-Signature-256` ang sample na iyon. Kung nagla-log ang receiver ng 401 para dito, iwanang naka-on ang check at mag-test na lang gamit ang totoong mensahe.

Kailangan ng totoong sender ang totoong event. Mag-message sa business number mo mula sa isang WhatsApp account, o gamitin ang test phone number na ginagawa ng Meta habang nasa [Cloud API setup](/academy/fil/articles/whatsapp-cloud-api-test-number-get-started/). Sinasabi ng get-started page ng Meta na itabi ang test phone number ID at Messaging account ID; ang una ang kailangan ng override call sa itaas ([Get started, na-access noong 2026-11-04](https://developers.facebook.com/documentation/business-messaging/whatsapp/get-started)). Kapag nagpadala ka ng mensahe sa sarili mong phone mula sa number na iyon, dapat may lumabas na `sent` at `delivered` na status sa parehong callback.

## I-replay ang mga request mula sa ngrok inspector

Buksan ang http://localhost:4040 sa makinang nagpapatakbo ng ngrok. Nakalista roon ang bawat request na dumaan sa tunnel, at ipinapadala ulit ng Replay button ang isa sa mga ito ([ngrok web inspection, na-access noong 2026-11-04](https://ngrok.com/docs/agent/web-inspection-interface/)). Dapat pumasa sa signature check ang replay na hindi binago ang body, dahil ang body at ang app secret mo lang ang sakop ng HMAC. Kung babaguhin mo ang body sa replay editor, dapat sumagot ng 401 ang receiver. Parehong sumusunod ito sa signature rule ng Meta; hindi ito sinasabi ng ngrok o ng Meta.

Duplicate din ang replay na hindi binago, kapareho ng nililikha ng mga retry ng Meta. Gamitin ito para i-test ang dedupe step na kailangan ng totoong handler mo, na tinalakay sa [idempotency pattern para sa n8n](/academy/fil/articles/n8n-duplicate-webhooks-idempotency/) at sa [FastAPI receiver](/academy/fil/articles/whatsapp-webhook-python-fastapi-receive-messages/).

Kung pumalya ang Verify and save o hindi kailanman lumalabas ang mga totoong mensahe, sundan ang [webhook troubleshooting checklist](/academy/fil/articles/whatsapp-webhook-not-receiving-messages-troubleshooting/). Magsimula sa curl handshake sa itaas, na pinapatakbo laban sa tunnel URL sa halip na localhost.

*Ang Z-API Omni team*
