Skip to content

WhatsApp Cloud API Webhooks on Localhost with Localtonet

Verify a WhatsApp Cloud API webhook on localhost, validate X-Hub-Signature-256, handle retries and keep a stable HTTPS callback URL with Localtonet.

Summary in your language
In this article 13 sections
Diagram of Meta's webhook POST reaching a public Localtonet HTTPS URL and tunneling to a receiver on localhost:3000
Meta sends webhook requests to a public HTTPS URL; the Localtonet tunnel forwards them to the local receiver.
Webhooks · WhatsApp Cloud API · Localtonet · 2026

Pass Meta's verification handshake, validate every signed event and keep one callback URL that survives restarts

Meta's servers cannot reach a WhatsApp bot running on localhost:3000, and the Meta App Dashboard will only accept a publicly reachable HTTPS callback URL that answers its verification request correctly. This guide walks through building a small local webhook receiver that handles the GET verification handshake, validates the X-Hub-Signature-256 HMAC on every POST, and tolerates redelivered events. We then publish that receiver with a Localtonet HTTP tunnel, use a Custom Sub Domain so the callback URL stays the same between sessions, and set up our Token/Tunnel status webhooks so you know when the endpoint goes offline. A troubleshooting section covers the failures developers hit most often.

🔒 HMAC-SHA256 signature validation with your Meta app secret 🌐 Public HTTPS callback URL without port forwarding ⚡ Register the callback once with a stable subdomain

Why Meta cannot call your localhost webhook

A webhook reverses the usual direction of an API call. Instead of your code polling the WhatsApp Cloud API for new messages, Meta's servers open an HTTP connection to a URL you register and push events to it. That only works if Meta can reach the URL. A development laptop normally sits behind a home or office router that performs NAT, has no inbound ports open, and often has no stable public IP address at all. An address such as http://localhost:3000/webhook means "this machine" to whoever resolves it, so from Meta's point of view it points at Meta's own infrastructure, not at your laptop.

Meta adds a second requirement: the callback URL must use HTTPS with a valid TLS certificate. Meta's documentation states that self-signed certificates are not supported. So even if you opened a port on your router, you would still need a domain name and a trusted certificate pointing at your machine, plus a way to keep both working as your IP address changes.

The third requirement is easy to overlook. The Meta App Dashboard stores one callback URL per app configuration, and Meta sends a fresh verification request every time you set or edit the callback URL or the verify token. If your public URL changes every time you restart your tooling, you repeat the dashboard registration and the verification handshake every session. That is the chore this guide removes.

🧩 One path, two methods Your receiver must answer GET for the verification handshake and POST for event delivery on the same callback path, for example /webhook.
🔐 Public HTTPS Meta must reach the URL from the public internet over HTTPS with a valid certificate. A Localtonet HTTP tunnel provides a public HTTPS address that forwards to your local port.
📌 A URL that stays put Because editing the callback URL triggers re-verification, a stable address such as a Localtonet Custom Sub Domain means you register the endpoint once.

A Localtonet HTTP tunnel solves the reachability problem without router changes. Our client application runs on your machine and opens an outbound connection to a Localtonet relay server. The relay gives you a public HTTPS address, and requests to that address travel back through the outbound connection to the local IP and port you chose. No inbound port forwarding, firewall rule or public IP address is required on your side. The important caveat, which we return to later, is that the public URL only works while the Localtonet client on that device is connected and the tunnel is started.

Prerequisites

Gather the following before you write any code. Having everything ready matters because Meta calls your URL live the moment you save the webhook configuration, so the server and tunnel must already be running at that point.

  • A Meta developer app with WhatsApp added. You need access to the app in the Meta App Dashboard, including its WhatsApp configuration panel and its App settings.
  • Your app secret. Meta issues this per app. It is shown under App settings → Basic in the Meta App Dashboard. You will use it to validate signatures.
  • A verify token you invent. Any hard-to-guess string you choose. Meta does not issue it.
  • A local runtime. This guide shows Node.js with Express and Python with FastAPI. Use whichever you already work in. Exact supported runtime versions depend on those frameworks, not on Meta or Localtonet.
  • curl and openssl on your machine for local testing. Both ship with most Linux distributions and macOS, and are available for Windows.
  • A Localtonet account and the Localtonet client installed on the same machine that runs your receiver, or on a machine that can reach it over the local network.

Meta's documentation also lists the permission associated with each webhook field. For the messages field, which carries inbound messages and the status of messages you send, the relevant permission is whatsapp_business_messaging. If your app does not have it, verification can succeed while events never arrive.

About dashboard locations

Meta's dashboard layout varies by how the app was created. In apps with the WhatsApp product added directly, the webhook panel is under WhatsApp → Configuration. Apps created with the "Connect with customers through WhatsApp" use case place it under Use cases → Customize → Configuration. Meta changes its dashboard from time to time, so if the labels differ for you, look for the panel that asks for a Callback URL and a Verify token.

Verify token vs. app secret: two different credentials

Side-by-side comparison of the verify token used in the GET handshake and the app secret used to check X-Hub-Signature-256
The verify token answers the subscription handshake; the app secret signs every event payload.

The single most common cause of "every real message fails validation" is mixing up these two values. They look similar in a tutorial, both are strings stored in environment variables, and both relate to webhooks, but Meta uses them for completely different jobs.

Credential Who creates it Where it is used Suggested variable
Verify token You. Any string you choose and type into the dashboard. Only in the GET verification handshake, sent back to you as hub.verify_token. VERIFY_TOKEN
App secret Meta. Shown under App settings → Basic. As the HMAC-SHA256 key Meta uses to sign every POST event delivery. META_APP_SECRET
Access token Meta, via your app or system user. For your outgoing calls to the Cloud API, such as sending replies. Not used to receive webhooks. Your choice, kept separate

The verify token proves to your server that a verification request came from the configuration you set up. It is used during setup and whenever you change the callback URL or the token. The app secret is used on every single event delivery for as long as the integration runs. Store them in separate environment variables, never commit either to source control, and rotate the app secret through the Meta dashboard if you suspect it leaked.

Keep secrets out of logs and screenshots

It is tempting to print environment variables while debugging a signature mismatch. Log the computed and received signature prefixes or lengths if you must, but never the app secret itself. The same applies to your Localtonet auth token, which identifies your device and must not be shared or pasted into public issue trackers.

Build the local webhook receiver

The receiver has two jobs on one path. On GET, it completes the verification handshake. On POST, it validates the signature against the raw body, acknowledges quickly with HTTP 200, and hands the payload to background processing.

How the GET verification handshake works

When you save the Callback URL and Verify token in the dashboard, Meta sends a GET request to your callback URL with three query parameters:

GET /webhook?hub.mode=subscribe&hub.verify_token=YOUR_TOKEN&hub.challenge=1158201444
Parameter Value What your server does
hub.mode Always subscribe during verification Reject the request if it is anything else.
hub.verify_token The string you typed into the dashboard Compare it with your VERIFY_TOKEN environment variable.
hub.challenge A random value generated by Meta If mode and token match, return it as the response body with HTTP 200.

Meta's pass condition is strict: respond with status 200 and the hub.challenge value as the body. Return the raw value as plain text. Do not wrap it in JSON, do not add quotes, and do not add a trailing message. Any other response leaves the endpoint unverified, and Meta sends no webhooks to it.

Node.js with Express

Create a project folder and install Express:

mkdir whatsapp-webhook && cd whatsapp-webhook
npm init -y
npm install express

Save the following as server.js. Port 3000 is simply the example port we use throughout this guide; any free local port works as long as you use the same one in your tunnel.

// server.js
const express = require('express');
const crypto = require('crypto');

const app = express();
const PORT = process.env.PORT || 3000;
const VERIFY_TOKEN = process.env.VERIFY_TOKEN;
const APP_SECRET = process.env.META_APP_SECRET;

if (!VERIFY_TOKEN || !APP_SECRET) {
  console.error('Set VERIFY_TOKEN and META_APP_SECRET before starting.');
  process.exit(1);
}

// 1) GET: Meta's verification handshake
app.get('/webhook', (req, res) => {
  const mode = req.query['hub.mode'];
  const token = req.query['hub.verify_token'];
  const challenge = req.query['hub.challenge'];

  if (mode === 'subscribe' && token === VERIFY_TOKEN && challenge) {
    // Raw challenge, plain text, no JSON wrapper
    return res.status(200).type('text/plain').send(String(challenge));
  }
  return res.sendStatus(403);
});

// 2) Signature check over the exact bytes Meta sent
function isValidSignature(rawBody, header) {
  if (!header || !header.startsWith('sha256=')) return false;
  const expected = 'sha256=' + crypto
    .createHmac('sha256', APP_SECRET)
    .update(rawBody)
    .digest('hex');
  const a = Buffer.from(expected);
  const b = Buffer.from(header);
  return a.length === b.length && crypto.timingSafeEqual(a, b);
}

// 3) POST: event delivery. express.raw keeps the body as a Buffer.
app.post('/webhook', express.raw({ type: 'application/json' }), (req, res) => {
  if (!Buffer.isBuffer(req.body)) return res.sendStatus(400);

  const signature = req.get('x-hub-signature-256');
  if (!isValidSignature(req.body, signature)) {
    console.warn('Rejected webhook: signature mismatch');
    return res.sendStatus(401);
  }

  // Acknowledge first, then process asynchronously
  res.sendStatus(200);

  let payload;
  try {
    payload = JSON.parse(req.body.toString('utf8'));
  } catch (err) {
    console.error('Valid signature but unparseable JSON');
    return;
  }
  setImmediate(() => processPayload(payload));
});

// Demo-only in-memory dedupe. Use a database or Redis in production.
const seenIds = new Set();

function processPayload(payload) {
  for (const entry of payload.entry || []) {
    for (const change of entry.changes || []) {
      const value = change.value || {};

      for (const msg of value.messages || []) {
        if (seenIds.has(msg.id)) continue;   // duplicate delivery
        seenIds.add(msg.id);
        console.log('Inbound message', msg.id, 'type', msg.type);
        // Your bot logic goes here
      }

      for (const status of value.statuses || []) {
        const key = status.id + ':' + status.status;
        if (seenIds.has(key)) continue;
        seenIds.add(key);
        console.log('Status update', status.id, status.status);
      }
    }
  }
}

app.listen(PORT, '127.0.0.1', () => {
  console.log('Webhook receiver listening on http://127.0.0.1:' + PORT);
});

Start it with your two values set as environment variables. On Linux or macOS:

export VERIFY_TOKEN='choose-a-long-random-string'
export META_APP_SECRET='paste-your-app-secret-here'
node server.js

Two details in this code matter more than they look. First, express.raw() is attached only to the POST route, so the body stays as the exact bytes Meta signed. If you register express.json() globally with app.use() before this route, the body is parsed into an object before your handler runs and signature validation breaks. Second, the comparison uses crypto.timingSafeEqual after a length check, which avoids leaking information through comparison timing and avoids the exception that function throws on buffers of different lengths.

Python with FastAPI

If you prefer Python, install FastAPI and an ASGI server:

pip install fastapi uvicorn

Python parameter names cannot contain dots, so FastAPI's Query(alias=...) maps hub.mode and friends onto valid names. Save this as main.py:

import hashlib
import hmac
import json
import os

from fastapi import BackgroundTasks, FastAPI, Query, Request, Response
from fastapi.responses import PlainTextResponse

app = FastAPI()
VERIFY_TOKEN = os.environ["VERIFY_TOKEN"]
APP_SECRET = os.environ["META_APP_SECRET"].encode()

seen_ids = set()  # demo only, use persistent storage in production

@app.get("/webhook")
def verify(
    mode: str | None = Query(None, alias="hub.mode"),
    token: str | None = Query(None, alias="hub.verify_token"),
    challenge: str | None = Query(None, alias="hub.challenge"),
):
    if mode == "subscribe" and token == VERIFY_TOKEN and challenge:
        return PlainTextResponse(challenge, status_code=200)
    return Response(status_code=403)

def process(raw: bytes) -> None:
    payload = json.loads(raw)
    for entry in payload.get("entry", []):
        for change in entry.get("changes", []):
            value = change.get("value", {})
            for msg in value.get("messages", []):
                if msg["id"] in seen_ids:
                    continue
                seen_ids.add(msg["id"])
                print("Inbound message", msg["id"], msg.get("type"))

@app.post("/webhook")
async def receive(request: Request, background: BackgroundTasks):
    raw = await request.body()  # exact bytes, before any parsing
    header = request.headers.get("x-hub-signature-256", "")
    expected = "sha256=" + hmac.new(APP_SECRET, raw, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, header):
        return Response(status_code=401)
    background.add_task(process, raw)  # runs after the response is sent
    return Response(status_code=200)
export VERIFY_TOKEN='choose-a-long-random-string'
export META_APP_SECRET='paste-your-app-secret-here'
uvicorn main:app --host 127.0.0.1 --port 3000

The str | None syntax requires Python 3.10 or newer. On older versions, use Optional[str] from the typing module.

PHP and other frameworks

PHP converts periods in query parameter names to underscores, so in plain PHP you read $_GET['hub_mode'], $_GET['hub_verify_token'] and $_GET['hub_challenge']. For signature checks in PHP, read the raw body with file_get_contents('php://input') rather than relying on a decoded array. Whatever your stack, the rule is the same: answer the challenge as plain text and hash the unmodified request bytes.

What a messages payload looks like

The code above walks a structure like the following simplified example. Real payloads carry more fields, such as contact profiles, metadata about the receiving phone number and type-specific message content. Consult Meta's webhook reference for the full schema rather than treating this sample as complete.

{
  "object": "whatsapp_business_account",
  "entry": [
    {
      "id": "WHATSAPP_BUSINESS_ACCOUNT_ID",
      "changes": [
        {
          "field": "messages",
          "value": {
            "messaging_product": "whatsapp",
            "messages": [
              {
                "from": "SENDER_PHONE_NUMBER",
                "id": "wamid.EXAMPLE_MESSAGE_ID",
                "timestamp": "1700000000",
                "type": "text",
                "text": { "body": "Hello" }
              }
            ]
          }
        }
      ]
    }
  ]
}

Inbound messages appear in value.messages. Status updates for messages you sent, such as sent, delivered, read and failed, appear in value.statuses under the same messages field. A single POST can contain more than one entry or change, which is why the handlers loop rather than reading index zero.

Test the receiver locally before adding a tunnel

Debugging is far easier when you know the local server is correct before any public traffic arrives. Run these checks against localhost first. If they pass here but fail through the tunnel, you know the problem is in routing or configuration, not in your code.

Simulate the verification GET

curl -i "http://localhost:3000/webhook?hub.mode=subscribe&hub.verify_token=choose-a-long-random-string&hub.challenge=12345"

You should see HTTP/1.1 200 OK, a text/plain content type and a body of exactly 12345. Now change the token to something wrong and confirm you get 403. If you open http://localhost:3000/webhook in a browser without any query string, the 403 is expected; only Meta's request carries the challenge.

Simulate a signed POST

To test the signature path, compute an HMAC with a throwaway secret, start your server with that same secret, and send a request:

# Start the server in another terminal with META_APP_SECRET='local-test-secret'
SECRET='local-test-secret'
BODY='{"object":"whatsapp_business_account","entry":[{"id":"1","changes":[{"field":"messages","value":{"messages":[{"id":"wamid.TEST1","type":"text","text":{"body":"hi"}}]}}]}]}'

SIG=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$SECRET" | awk '{print $NF}')

curl -i -X POST http://localhost:3000/webhook \
  -H "Content-Type: application/json" \
  -H "X-Hub-Signature-256: sha256=$SIG" \
  --data-binary "$BODY"

Expect a 200 response and an "Inbound message wamid.TEST1" log line. Run the same command a second time: the response is still 200, but the log should skip the message because the ID was already seen. Then alter one character of SIG and confirm a 401. Use --data-binary rather than -d, because -d can strip newlines and change the bytes you signed. The awk '{print $NF}' step takes the last field of openssl's output, which works across openssl versions that label the output differently.

Restart with the real secret

After local testing, stop the server and start it again with your actual Meta app secret. A server still running with the test secret will reject every genuine Meta delivery with 401, which looks exactly like a signature bug.

Expose the receiver with a Localtonet HTTP tunnel

Localtonet console showing a connected HTTP/s tunnel from https://example.localto.net to 127.0.0.1 port 3000
A connected HTTP/s tunnel forwards the public URL to the receiver on port 3000.

With the receiver working on port 3000, the next step is giving it a public HTTPS address. An HTTP tunnel is the right tunnel type here, because Meta delivers webhooks over HTTPS and needs a hostname rather than a raw host and port. The sequence below is our standard workflow. For the exact field names and screens in the current dashboard, follow the Localtonet HTTP tunnel documentation.

1

Install and run the Localtonet client

Install our client application on the machine running your webhook receiver, or on a machine that can reach it on the local network, and start it.

2

Authenticate the device with its token

Connect the client using the auth token for that device from your Localtonet dashboard. Tokens are device-specific; keep yours private.

3

Select a relay server

Choose one of the relay servers or regions currently offered in the dashboard. Picking one close to where your traffic originates is a reasonable default.

4

Create the HTTP tunnel

Create an HTTP tunnel, choose a Process Type (Custom Sub Domain is recommended for webhooks, see below), select the device's auth token and server, and set the local target to the IP and port of your receiver, for example 127.0.0.1 and 3000.

5

Start the tunnel and copy the public URL

Creating a tunnel does not start it. Press Start, then copy the assigned public HTTPS address. Your callback URL is that address plus your path, for example https://your-subdomain.example/webhook.

6

Stop or delete it when you are done

Stop the tunnel when you no longer want the endpoint reachable, and delete it if you will not reuse it. Remember that Meta will keep trying to deliver to the registered URL while it is offline.

Choose a Process Type that keeps the URL stable

Our HTTP tunnels offer three Process Types. All of them serve your local receiver at a public HTTPS address. The difference that matters for webhooks is whether the address stays the same across sessions.

Process Type Best for Effect on Meta registration
Random Sub Domain A quick one-off test A generated address. If you end up with a different address in a later session, you must edit the callback URL in the dashboard, which triggers verification again.
Custom Sub Domain Day-to-day development of a WhatsApp bot A subdomain you select. Reusing it across restarts means the registered callback URL stays valid, so you verify once.
Custom Domain Long-lived staging or demo environments on your own domain Your own hostname, equally stable. DNS setup is required; check the current Localtonet documentation for the exact records before configuring it.

Availability of specific Process Types can depend on your plan, so confirm in your dashboard which options your account offers. If Custom Sub Domain is available to you, it is the simplest way to turn webhook registration into a one-time task.

Confirm the tunnel before touching Meta

Repeat the verification test from the previous section, but against the public URL. This proves that the tunnel is started, routes to the right port and preserves the query string.

curl -i "https://YOUR-PUBLIC-HOST/webhook?hub.mode=subscribe&hub.verify_token=choose-a-long-random-string&hub.challenge=67890"

You should receive a 200 with body 67890. You can also repeat the signed POST test against the public URL, which confirms that the X-Hub-Signature-256 header and the body arrive at your server in a form your validation accepts. If both checks pass, the remaining variables are all on the Meta side.

Register the callback URL in the Meta App Dashboard

These steps happen in Meta's dashboard, not ours. Keep your receiver running and the Localtonet tunnel started throughout, because Meta calls your URL the moment you save.

1

Open the webhook configuration panel

Go to WhatsApp → Configuration, or Use cases → Customize → Configuration for apps created with the WhatsApp use case.

2

Enter the Callback URL and Verify token

Paste your full public HTTPS URL including the path, such as https://your-subdomain.example/webhook, and type the exact string from your VERIFY_TOKEN variable.

3

Verify and save

Meta sends the GET handshake. Watch your server log for the request. A 200 with the raw challenge completes verification.

4

Subscribe to the messages field

Verification only proves the URL is yours. In the list of webhook fields shown afterwards, subscribe to messages to receive inbound messages and delivery statuses.

5

Send a test message

From a phone, message the WhatsApp number connected to your app. A signed POST should appear in your logs and pass validation.

Step 4 trips up many first-time integrations. A green checkmark on verification feels like the job is done, but without a field subscription Meta has nothing to send. If your app needs other events, subscribe to those fields too, and check Meta's reference for the permission each one requires.

Validating X-Hub-Signature-256 in depth

Anyone who learns your callback URL can POST to it. The signature header is how you tell Meta's genuine deliveries apart from forged ones. Each event delivery carries a header in this form:

X-Hub-Signature-256: sha256=<hex-encoded HMAC-SHA256 of the request body>

The HMAC is computed over the request payload using your app secret as the key. Meta describes validating it as optional but recommended. We would put it more strongly: an endpoint reachable through a public URL should treat unsigned or mis-signed requests as untrusted and reject them.

The three rules that make validation work

  • Hash the raw bytes. Compute the HMAC over the exact body bytes received, before any JSON parser touches them. Parsing and re-serializing JSON changes whitespace, key order or character escaping. Developers working with Meta webhooks have reported that Meta signs a form of the payload in which non-ASCII characters are escaped, so a body that you decode and re-encode will not reproduce the same bytes, especially for messages containing emoji or non-Latin text.
  • Use the right key. The key is the app secret from App settings → Basic, not the verify token and not your access token.
  • Compare in constant time. Use crypto.timingSafeEqual in Node.js or hmac.compare_digest in Python instead of === or ==. Include the sha256= prefix consistently on both sides, or strip it from both.

Body-parsing middleware is the usual culprit

Most frameworks encourage you to enable a JSON body parser globally. That is convenient for the rest of your API and fatal for webhook signatures. Common fixes by stack:

  • Express: mount express.raw({ type: 'application/json' }) on the webhook route only, and register any global express.json() so it does not run for that path. Alternatively, use the verify option of express.json() to capture the raw buffer before parsing.
  • FastAPI and Starlette: read await request.body() in the handler instead of declaring a Pydantic model parameter for the payload.
  • Other frameworks: look for the framework's raw-body or unparsed-input access and use that for the HMAC, then parse separately.

What the signature does not prove

The signature proves the body was produced by someone holding your app secret. It does not carry a timestamp, so it does not prove the request is fresh. A captured, validly signed request would still validate if someone replayed it. That is one more reason to deduplicate on message IDs, covered next, rather than treating a valid signature as proof that an event is new.

Designing for retries and duplicate deliveries

Flow showing signature check, fast 200 response, and message ID deduplication, with retries looping back on failure
Acknowledge quickly and deduplicate by message ID so retries do not repeat work.

Webhook delivery is "at least once", not "exactly once". If Meta does not receive a 200 acknowledgment for a delivery, it tries again. According to Meta's WhatsApp Business Platform documentation at the time of writing, failed deliveries are retried for up to 7 days. Meta controls the retry intervals and the conditions under which it gives up, and those details can change, so check Meta's current webhook documentation rather than designing around a specific interval. The safe assumptions are that any event may arrive more than once, may arrive late and may arrive out of order relative to other events.

⏱️ Acknowledge fast Validate the signature, return 200, then do the real work. Calling an LLM, a database or the Cloud API before responding risks a timeout, which Meta treats as a failed delivery and retries.
📥 Process asynchronously Hand validated payloads to a queue or background task. In development, setImmediate or FastAPI's BackgroundTasks is enough; in production, use a durable queue so work survives restarts.
🧮 Deduplicate by ID Inbound messages carry an id. Record processed IDs and skip repeats. For status updates, the same message passes through several states, so key on message ID plus status.
🕰️ Handle stale events A message retried hours later may no longer deserve an instant reply. Compare the event's timestamp with the current time and decide how your bot should respond to old messages.

Why deduplication storage matters

The in-memory Set in our sample is fine for a single development session, but it empties every time the process restarts. Restarts are exactly when duplicates are most likely: Meta retries deliveries that failed while you were down, and some of them may already have been processed before the crash. For anything beyond a quick test, store processed IDs in a database table with a unique constraint, or in a key-value store with an expiry comfortably longer than Meta's retry window. An insert that fails on the unique constraint is a clean, race-free "already seen" check.

Order of operations for each POST

  1. Read the raw body.
  2. Validate X-Hub-Signature-256. On failure, return 401 and stop.
  3. Return 200.
  4. Parse JSON and enqueue each message or status.
  5. In the worker, check the ID against your dedupe store, process, then record it.

Returning 200 for a valid signature even when your downstream logic later fails is deliberate. A retry from Meta will not fix a bug in your bot; your own queue's retry handling should. Returning a non-200 code is appropriate only when you genuinely want Meta to redeliver, for example because the request could not be read at all.

Keep the callback endpoint online and know when it drops

With Localtonet, a public URL is only live while two conditions hold: the Localtonet client on your device is connected, and the tunnel is started. Close your laptop lid, lose Wi-Fi, quit the client or press Stop, and the callback URL stops reaching your receiver. Your receiver process must also be running on the target port; a started tunnel in front of a stopped server still fails deliveries.

During that gap, Meta's deliveries fail and fall back on Meta's retry behavior. Events from a short outage will normally be redelivered when the endpoint returns, which is good, but they will arrive in a burst and possibly out of order. Events from an outage longer than Meta's retry window may never arrive. That makes it useful to know, promptly, when the endpoint goes offline.

Use our Token/Tunnel status webhooks

Our platform has its own webhook system for this purpose, separate from Meta's. You select a Token Group, and when a token or a tunnel in that group changes to Connected or Disconnected, we send a POST request to a URL you configure. The JSON body, a WebHookRequest, contains four fields:

Field Meaning
Id The tunnel id or the auth token the event refers to
ActionDate When the status change happened
Type "Token" or "Tunnel"
Status "Connected" or "Disconnected"

Point this webhook at something that is not behind the same tunnel, such as a chat-ops alert endpoint, an automation service or a small always-on server. A Disconnected event for the tunnel that fronts your WhatsApp receiver means Meta's deliveries are currently failing, and a later Connected event tells you when redelivery can begin. Setup details are in the Localtonet webhook documentation.

Two webhook systems, two jobs

Do not confuse the two. Meta's webhooks carry WhatsApp events and are signed with your Meta app secret via X-Hub-Signature-256. Our Token/Tunnel webhooks report the connection state of your Localtonet device and tunnels and use the WebHookRequest format above; they do not use Meta's signature scheme. Our documentation for these status webhooks does not describe a signing header, so do not write code that assumes one; protect the receiving endpoint with your own access controls.

Practical habits for development sessions

  • Start the receiver first, then confirm the tunnel is started, then edit anything in Meta's dashboard.
  • Reuse the same Custom Sub Domain each session so the registered URL never changes.
  • Stop the tunnel when you are not working if you do not want the endpoint reachable, and accept that Meta will queue retries during that time.
  • If you share a development app with teammates, agree on whose machine currently serves the callback URL, since only one endpoint is registered per configuration.

Troubleshooting common failures

Most problems fall into three groups: the verification handshake fails, signatures do not match, or events go missing. Work from the local machine outward: test against localhost, then against the public URL, then involve Meta.

Symptom Likely cause Fix
"Callback URL or verify token couldn't be validated" JSON-wrapped challenge, non-200 status, or a token mismatch such as a trailing space Return the raw challenge as text/plain with 200. Compare the dashboard token and VERIFY_TOKEN character by character.
Timeout during verification Receiver not running, tunnel created but not started, or client disconnected Start the server, start the tunnel, test the public URL with curl, then retry in the dashboard.
Verification hits the wrong app or 404 Tunnel points at the wrong port, or the callback URL is missing the /webhook path Check the tunnel's local target and include the full path in the Callback URL.
Browser shows 403 at /webhook No query string in a manual browser request Expected. Only Meta's GET includes hub.challenge.
Verification succeeds, no events arrive Not subscribed to the messages field, or missing permission Subscribe to messages and confirm whatsapp_business_messaging is granted.
Every POST fails signature validation Body parsed before hashing, wrong key (verify token instead of app secret), or server still running with a test secret Hash the raw bytes, use META_APP_SECRET from App settings → Basic, restart with the real value.
Only messages with emoji or non-Latin text fail validation Body decoded and re-encoded before hashing Hash the original bytes; never re-serialize JSON for signature checks.
Same message processed twice Retry after a slow response or restart; no persistent dedupe Acknowledge before processing and store processed IDs durably.
Burst of old events after reconnecting Meta redelivering events that failed while the tunnel was stopped Expected behavior. Dedupe and check timestamps before replying.

Verification failures, step by step

Run the curl verification against the public URL with your exact verify token. If that returns 200 with the challenge, your code and tunnel are correct, and the problem is the value typed into the dashboard. If it times out, check that the Localtonet client shows the device as connected and that the tunnel is started, not merely created. If it returns 403, your server received the request but the mode or token did not match; log the received hub.mode value and the token's length (not its content) to compare.

Signature mismatches, step by step

First confirm the header is arriving at all by logging whether x-hub-signature-256 is present. Then verify your validation logic with the local openssl test using a known secret. If the local test passes but Meta's deliveries fail, the cause is almost always the key (wrong secret, a stale secret after rotation, or the verify token used by mistake) or middleware that modified the body. Temporarily logging the body length you hash and comparing it with the Content-Length header can reveal whether a parser rewrote the payload.

Missed events while the tunnel was stopped

If you stopped the tunnel or your device went offline, deliveries in that window failed on Meta's side. Within Meta's retry window, they should be redelivered once the endpoint is reachable again. Beyond it, they may be gone, and our platform has no copy of events that never reached your receiver. If you cannot afford gaps, run the receiver on an always-on machine, use our Token/Tunnel Disconnected webhook to alert you quickly, and use the Cloud API's own facilities to reconcile state where your use case allows it.

Security practices for a public webhook endpoint

A tunnel makes a local port publicly reachable, and that deserves the same care as any internet-facing service. The tunnel does not bypass or replace your application's own security controls.

  • Expose only the webhook. Run the receiver as its own small process on its own port, rather than tunneling a development server that also serves admin pages or debug tools.
  • Bind locally. Our samples listen on 127.0.0.1 so the receiver is not reachable from your LAN directly; only the tunnel on the same machine reaches it. Adjust only if the client runs on a different machine.
  • Reject unsigned requests. Validation is optional in Meta's view, but treat it as mandatory on a public URL.
  • Limit what the handler does. The webhook should enqueue work, not execute arbitrary actions directly from message content.
  • Separate development from production. Use a dedicated Meta app or configuration for local development so a stopped laptop never breaks production delivery.
  • Protect credentials. Keep the verify token, app secret, Cloud API access token and Localtonet auth token in environment variables or a secret manager, out of repositories and logs.

Frequently asked questions

Can I register http://localhost as my WhatsApp Cloud API callback URL?

No. Meta's servers must reach the URL from the public internet over HTTPS with a valid certificate, and self-signed certificates are not supported. A Localtonet HTTP tunnel gives your local receiver a public HTTPS address without port forwarding or a public IP.

What should my server return for hub.challenge?

If hub.mode is subscribe and hub.verify_token matches your token, return HTTP 200 with the raw hub.challenge value as a plain-text body. Anything else, including a JSON wrapper, leaves the endpoint unverified.

Is the verify token the same as the app secret?

No. You invent the verify token and Meta only uses it in the GET handshake. Meta issues the app secret, found under App settings → Basic, and uses it to sign every POST with X-Hub-Signature-256. Using the verify token as the HMAC key makes every real delivery fail validation.

Why does my signature check fail even with the correct app secret?

Usually because a JSON body parser ran before your handler and you hashed a re-serialized body instead of the original bytes. Use express.raw() on the webhook route in Express or await request.body() in FastAPI, and compare with a constant-time function.

Do I need to re-verify the webhook every time I restart?

Only if the URL changes. Meta re-verifies when you set or edit the callback URL or verify token. If you reuse the same Localtonet Custom Sub Domain or Custom Domain and simply start the tunnel again, the registered URL stays valid. Check your dashboard for which Process Types your plan includes.

What happens to WhatsApp messages sent while my tunnel is stopped?

Meta's deliveries fail while the endpoint is unreachable, and Meta retries them. Its WhatsApp documentation describes retries for up to 7 days at the time of writing; Meta defines the exact schedule. Expect a burst of redelivered events after reconnecting and deduplicate by message ID.

How can I get alerted when my callback endpoint goes offline?

Configure our Token/Tunnel webhooks for the Token Group containing your device. We POST a WebHookRequest with Id, ActionDate, Type and Status whenever the token or tunnel becomes Connected or Disconnected. Send it to an endpoint that is not behind the same tunnel.

Does verification alone start event delivery?

No. Verification only confirms you control the URL. You must also subscribe to webhook fields such as messages, and your app needs the matching permission, whatsapp_business_messaging for messages.

Give your WhatsApp webhook a stable HTTPS address

Create a Localtonet HTTP tunnel to your local receiver, reserve a Custom Sub Domain so Meta's callback URL survives restarts, and add a Token/Tunnel status webhook so you know the moment your endpoint goes offline.

Get Started Free →

Localtonet is a secure multi-protocol tunneling and proxy platform designed to expose localhost, devices, private services, and AI agents to the public internet supporting HTTP/HTTPS tunnels, TCP/UDP forwarding, mobile proxy infrastructure, file server publishing, latency-optimized game connectivity, and developer-ready AI agent endpoint exposure from a single unified control plane.

Support