Point the Messenger and Instagram webhooks at one HTTPS endpoint and branch on the top-level object field: page is Messenger, instagram is Instagram. Both put messages in entry[].messaging[] with sender, recipient and message, so one loop reads both. Check X-Hub-Signature-256 over the raw body first, answer 200 fast, and skip events where message.is_echo is true.
This covers Messenger plus Instagram set up through Instagram Login or through the Messenger Platform’s Instagram Messaging docs. Both document object: "instagram" with a messaging array. For Unified Login, Meta’s Instagram webhook examples page showed no messaging example on 2026-11-04 (Instagram webhook examples, accessed 2026-11-04).
Two payloads with the same shape
This is Meta’s Instagram Messaging sample, with the same fields and values on fewer lines (Instagram Messaging webhooks, accessed 2026-11-04).
{
"object": "instagram",
"entry": [
{
"id": "IGID",
"time": 1569262486134,
"messaging": [
{
"sender": { "id": "IGSID" },
"recipient": { "id": "IGID" },
"timestamp": 1569262485349,
"message": {
"mid": "MESSAGE-ID",
"text": "MESSAGE-TEXT",
"attachments": [
{ "type": "image", "payload": { "url": "LINK" } },
{ "type": "video", "payload": { "url": "LINK" } }
]
}
}
]
}
]
}
A Messenger payload has "object": "page", your Page ID in entry[].id, and the same messaging[] items (Messenger webhooks, accessed 2026-11-04). Only the meaning of each ID changes.
Messenger (object: page) |
Instagram (object: instagram) |
|
|---|---|---|
entry[].id |
Page ID | Instagram professional account ID |
Inbound sender.id |
PSID, the Page-scoped ID of the person | IGSID, the Instagram-scoped ID of the customer |
Inbound recipient.id |
Page ID | Instagram professional account ID |
Echo sender.id / recipient.id |
Page ID / PSID | Instagram account ID / IGSID |
Meta scopes a PSID to one Page and an IGSID to one Instagram account. Expect different values per channel, and key customers by channel plus ID. Messenger and Instagram user profiles shows how to fetch a name for either one.
Meta’s Graph API guide says updates are batched “with a maximum of 1000 updates”, and “batching cannot be guaranteed” (Graph API webhooks, accessed 2026-11-04). The Messenger page calls messaging an “array of individual events” without saying it holds one. Loop over both entry[] and messaging[].
Echoes arrive differently on each channel
An echo is a copy of a message your own account sent. On an echo, the customer is recipient.id, not sender.id. Code that always replies to sender.id sends to your own Page ID.
Messenger sends echoes only if you subscribe the separate message_echoes field. Each echo carries is_echo: true and app_id, the “ID of the app from which the message was sent” (Message echoes, accessed 2026-11-04). Compare app_id with your own app ID. A mismatch means someone sent the message from another app or the Page inbox, which is the signal to pause your bot, as in the Messenger handover protocol.
Instagram has no separate field. Meta says “the message echo notifications are included with the message webhook field subscription”, so you get them whether you want them or not. The is_echo flag marks a message “sent from the Instagram account itself”.
Signature, response time and retries
Both products sign with the same header. Messenger’s page says Meta signs “all Event Notification payloads with a SHA256 signature” in X-Hub-Signature-256, prefixed sha256=, using “your app’s App Secret”. Meta computes it over “an escaped unicode version of the payload”, so hash the raw bytes and never re-serialize the JSON. Use the app secret shown for the product you subscribed. The script accepts a comma-separated list, so each product’s secret can sit in one variable. Webhook signature verification explains why parsed JSON breaks the hash.
Answer before any slow work. Messenger asks for “a 200 OK HTTPS response, within 5 or less seconds”. The Instagram Platform setup page gives no timeout. Its checklist says your server “returns a success response before it starts slow work” (Instagram webhooks setup, accessed 2026-11-04).
The two products document retries differently. Messenger can unsubscribe your app after an hour of failures, and its page applies that rule to Instagram accounts too. The Instagram Platform setup page gives 36 hours.
| Messenger page | Instagram Platform setup page | |
|---|---|---|
| Retry | “we will immediately try a few more times” | “retry immediately, then try a few more times with decreasing frequency over the next 36 hours” |
| After failures | Alert after 15 minutes; after 1 hour, a “Webhooks Disabled” alert and the app is unsubscribed | “Unacknowledged responses will be dropped after 36 hours” |
The Instagram setup page and Meta’s Graph API guide both say “Your server should handle deduplication”. The script keys each message on channel, account and mid.
The endpoint in Python
Python’s standard library is enough here: http.server for the endpoint, hmac and hashlib for the signature, json and a queue for the work. No framework means nothing parses the body before you hash it. The handler checks the signature, answers 200, and hands the payload to a worker thread.
"""One webhook endpoint for Messenger (object: page) and Instagram (object: instagram).
Run: VERIFY_TOKEN=... APP_SECRETS=SECRET_ONE,SECRET_TWO APP_ID=... python3 webhook.py
"""
import hashlib
import hmac
import json
import os
import queue
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlparse
VERIFY_TOKEN = os.environ["VERIFY_TOKEN"]
# The app secret shown for each product you subscribed, comma-separated.
APP_SECRETS = [s.strip() for s in os.environ["APP_SECRETS"].split(",") if s.strip()]
APP_ID = os.environ.get("APP_ID", "") # your Meta app ID, to recognize your own Messenger echoes
PORT = int(os.environ.get("PORT", "8000"))
CHANNELS = {"page": "messenger", "instagram": "instagram"}
jobs = queue.Queue()
seen = set() # in production, a unique key in your database
def valid_signature(raw_body, header):
if not header or not header.startswith("sha256="):
return False
received = header[len("sha256="):].encode()
for secret in APP_SECRETS:
expected = hmac.new(secret.encode(), raw_body, hashlib.sha256).hexdigest().encode()
if hmac.compare_digest(received, expected):
return True
return False
def normalize(payload):
"""Yield one internal message dict per message event."""
envelopes = payload if isinstance(payload, list) else [payload]
for envelope in envelopes:
channel = CHANNELS.get(envelope.get("object"))
if channel is None:
continue # not Messenger or Instagram
for entry in envelope.get("entry", []):
account = str(entry.get("id")) # Page ID or Instagram account ID
for event in entry.get("messaging", []):
msg = event.get("message")
if not msg:
continue # postbacks, reads and reactions are other event types
echo = bool(msg.get("is_echo"))
side = "recipient" if echo else "sender" # on an echo the customer is the recipient
yield {
"dedup_key": f"{channel}:{account}:{msg.get('mid')}",
"channel": channel,
"account_id": account,
"customer_id": str(event.get(side, {}).get("id")),
"message_id": msg.get("mid"),
"timestamp": event.get("timestamp"),
"text": msg.get("text"),
"attachments": [
{"type": a.get("type"), "url": (a.get("payload") or {}).get("url")}
for a in msg.get("attachments", [])
],
"is_echo": echo,
"from_this_app": echo and APP_ID != "" and str(msg.get("app_id")) == APP_ID,
}
def handle(message):
"""Your logic: store the message, then reply through the channel's send API."""
print(json.dumps(message), flush=True)
def worker():
while True:
payload = jobs.get()
try:
for message in normalize(payload):
if message["dedup_key"] in seen:
continue # a retry of something already processed
seen.add(message["dedup_key"])
if message["is_echo"]:
# All echoes are skipped. A handoff rule can read from_this_app here.
continue
handle(message)
except Exception as exc:
print("failed to process payload:", exc, flush=True)
finally:
jobs.task_done()
class Webhook(BaseHTTPRequestHandler):
def do_GET(self):
query = parse_qs(urlparse(self.path).query)
mode = query.get("hub.mode", [""])[0]
token = query.get("hub.verify_token", [""])[0]
challenge = query.get("hub.challenge", [""])[0]
if mode == "subscribe" and hmac.compare_digest(token.encode(), VERIFY_TOKEN.encode()):
self.reply(200, challenge.encode())
else:
self.reply(403, b"")
def do_POST(self):
length = int(self.headers.get("Content-Length") or 0)
raw_body = self.rfile.read(length) # the exact bytes Meta signed
if not valid_signature(raw_body, self.headers.get("X-Hub-Signature-256")):
self.reply(401, b"")
return
try:
payload = json.loads(raw_body)
except ValueError:
self.reply(400, b"")
return
self.reply(200, b"") # answer first, work later
jobs.put(payload)
def reply(self, status, body):
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)
if __name__ == "__main__":
threading.Thread(target=worker, daemon=True).start()
ThreadingHTTPServer(("", PORT), Webhook).serve_forever()
The customer_id field is the reply address on both channels. The Messenger Send API setup and Instagram messaging setup with Instagram Login posts show the two send calls. Meta’s Instagram Login template wraps the payload in a JSON array, so normalize accepts a list as well as an object. The in-memory seen set forgets everything on restart. Move it to a unique key in your database before production.
The script only skips echoes. It computes from_this_app for a handoff rule like the Messenger handover protocol.
Test it locally with signed bodies. In the test shell, export VERIFY_TOKEN with the same value the server uses, and export APP_SECRET set to one of the values in APP_SECRETS.
curl -i "http://localhost:8000/?hub.mode=subscribe&hub.verify_token=$VERIFY_TOKEN&hub.challenge=1158201444"
for BODY in \
'{"object":"page","entry":[{"id":"PAGE_ID","time":1458692752478,"messaging":[{"sender":{"id":"PSID"},"recipient":{"id":"PAGE_ID"},"timestamp":1458692752478,"message":{"mid":"mid.1457764197618:41d102a3e1ae206a38","text":"hello, world!"}}]}]}' \
'{"object":"instagram","entry":[{"id":"IGID","time":1569262486134,"messaging":[{"sender":{"id":"IGSID"},"recipient":{"id":"IGID"},"timestamp":1569262485349,"message":{"mid":"MESSAGE-ID","text":"MESSAGE-TEXT"}}]}]}'
do
SIG=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$APP_SECRET" | awk '{print $NF}')
curl -s -o /dev/null -w '%{http_code}\n' -X POST http://localhost:8000/ \
-H "Content-Type: application/json" \
-H "X-Hub-Signature-256: sha256=$SIG" \
--data-binary "$BODY"
done
The GET returns 1158201444. Each POST returns 200, and the server prints one message dict per channel. The Messenger body wraps Meta’s text event in the Messenger envelope, and the Instagram body is Meta’s sample without attachments.
Subscribe both products to the same URL
In the App Dashboard you enter a callback URL and verify token for Messenger, and again under Instagram settings. Use the same URL and token in both. Meta’s Graph API guide doesn’t say outright that two objects may share one URL. After setup, send a test message on each channel and confirm both reach the endpoint.
Then subscribe each account to your app. For a Page, the call needs a Page access token from a person who can perform the MODERATE task, plus pages_messaging and pages_manage_metadata (Messenger webhooks, accessed 2026-11-04). Add message_echoes to the fields if you want Messenger echoes.
curl -i -X POST "https://graph.facebook.com/v26.0/PAGE_ID/subscribed_apps?subscribed_fields=messages&access_token=PAGE_ACCESS_TOKEN"
With Instagram Login, subscribe the Instagram professional account on graph.instagram.com. Meta’s sample breaks the URL across lines inside the quotes, so it won’t run as printed. It’s cleaned to one line here.
curl -i -X POST "https://graph.instagram.com/v26.0/INSTAGRAM_ACCOUNT_ID/subscribed_apps?subscribed_fields=messages&access_token=INSTAGRAM_USER_ACCESS_TOKEN"
Both return success set to true. Instagram notifications need the app “published or Live” (Instagram webhooks setup, accessed 2026-11-04).
With the Messenger Platform setup instead, Instagram needs instagram_basic, instagram_manage_messages and pages_manage_metadata. The Instagram account must be connected to a Facebook Page with Allow Access to Messages turned on under Connected Tools. “Your app must be published, regardless of app review status, to receive webhooks” (Instagram Messaging get started, accessed 2026-11-04).
Once both channels reach one handler, the next step is one storage model. One message model for four channels adds WhatsApp and Telegram to the same record. If you’d rather receive all four through one provider, Z-API Omni carries WhatsApp, Messenger, Instagram and Telegram in one subscription, with webhooks included without limit (View documentation). Its payload format isn’t covered here, so check the documentation before you map it.
Z-API Omni team