<!-- Generated from the canonical 99 Digital API documentation. Do not edit this file. -->

Canonical page: https://docs.99digital.co.il/facebook-api/webhooks/webhook-events

# Webhook Events

Webhooks allow you to get a push to your server whenever something happens
on your Facebook Page or Instagram account: a new comment or reply, a post
that is created, edited, deleted, hidden or unhidden, or a new Lead Ads lead.

- Set your webhook URL with [Set Webhook](https://docs.99digital.co.il/facebook-api/webhooks/set-webhook).
  The URL belongs to **one connection** (one `from`): a Facebook Page
  connection and an Instagram connection each need their own call, with
  different URLs or the same one.
- Every event is sent to your URL as JSON via POST
  (`Content-Type: application/json`), one POST per event. `event` tells you
  what arrived, and `action` what happened to it. For a Messenger connection,
  the same URL also receives the `sendStatus` of the messages you send
  (`event` "sendStatus" — it has its own fields, and `unique` instead of
  `eventId`).

:::warning
When a connection is onboarded again, you keep the same `from` and `apiKey`,
but its webhook URL is erased. Call [Set Webhook](https://docs.99digital.co.il/facebook-api/webhooks/set-webhook)
again right after every onboarding, or you stop receiving webhooks for that
connection.
:::

**Settings:**

| Setting | Value |
| --- | --- |
| URL | Your URL — set it with [Set Webhook](https://docs.99digital.co.il/facebook-api/webhooks/set-webhook) |
| Method | JSON via POST |

## Events

Every kind of event has its own page, with its explanation, examples, and
every parameter explained:

| Webhook | Connection | `event` | `action` | When it is sent |
| --- | --- | --- | --- | --- |
| [Facebook Comment](https://docs.99digital.co.il/facebook-api/webhooks/facebook-comment) | Facebook Pages (`facebook_type` 3) | `comment` | `created`, `edited`, `deleted`, `hidden`, `unhidden` | A comment or reply on your Page's posts is written, edited, deleted, hidden or unhidden. |
| [Facebook Post](https://docs.99digital.co.il/facebook-api/webhooks/facebook-post) | Facebook Pages (`facebook_type` 3) | `post` | `created`, `edited`, `deleted`, `hidden`, `unhidden` | A post on your Page — yours or a visitor's — is created, edited, deleted, hidden or unhidden. |
| [Facebook Lead](https://docs.99digital.co.il/facebook-api/webhooks/facebook-lead) | Facebook Pages (`facebook_type` 3) | `lead` | `created` | A person submits one of your Lead Ads forms. The answers are in the event. |
| [Instagram Comment](https://docs.99digital.co.il/facebook-api/webhooks/instagram-comment) | Instagram (`facebook_type` 4) | `comment` | `created` | A new comment or reply on your Instagram account's posts. |
| [Instagram Post](https://docs.99digital.co.il/facebook-api/webhooks/instagram-post) | Instagram (`facebook_type` 4) | `post` | `created` | A post you publish with [Create Post](https://docs.99digital.co.il/facebook-api/instagram-pages/create-post) (right away), or a post created in the Instagram app when its first comment arrives. |

## Fields in every event

Every comment, post and lead event starts with the same fields. The fields of
each kind of event are explained on its page.

| Parameter | Description |
| --- | --- |
| `event` | What arrived: "comment", "post" or "lead". |
| `action` | What happened: "created", "edited", "deleted", "hidden" or "unhidden" — see each event's page for the ones it can have. |
| `eventId` | The unique ID of this event (`fbw_` and 32 characters). Use it to ignore an event you already received — see [Duplicates and order](#duplicates-and-order). |
| `platform` | "facebook" or "instagram". |
| `from` | The ID of your connection — the `from` you use to call our API. |
| `facebook_type` | 3 (Facebook Pages) or 4 (Instagram). |
| `pageId` / `igUserId` | Your Facebook Page ID (facebook) or your Instagram account ID (instagram). |
| `author` | Who wrote the comment or post (`id` and `name` on Facebook, `id` and `username` on Instagram), or null when it is not known. |
| `fromSelf` | true when your own Page or Instagram account wrote it. |
| `text` | The text of the comment or post (on an Instagram post, its caption), or null. |
| `timestamp` | When it happened (Unix time in seconds, UTC). |

:::danger Bot loops
Comments and posts that your own Page or Instagram account writes — also the
ones you create through this API — come back to your webhook as events too,
with `fromSelf` true. **If your system replies automatically to comments or
posts, skip every event with `fromSelf` true**, or it will answer itself in an
endless loop.
:::

## Delivery and retries

- Your webhook must respond with a 2xx status (200 OK, 201, 204 …). We wait
  up to 5 seconds to connect to your server and up to 15 seconds for its
  answer, so answer first and process the event afterwards. Any other answer,
  or no answer in time, counts as a failed delivery. The body of your answer
  is ignored.
- Answer at your URL itself, without a redirect: a redirect is followed, but
  a 301, 302 or 303 redirect turns our POST into a GET, without the event.
- A failed delivery is tried again, with the same payload, on this schedule
  (each wait is counted from the previous failed attempt):

  | Attempt | When |
  | --- | --- |
  | First attempt | When the event happens |
  | Retry 1 | Immediately after the first attempt failed |
  | Retry 2 | 5 minutes after retry 1 failed |
  | Retry 3 | 20 minutes after retry 2 failed |
  | Retry 4 | 1 hour after retry 3 failed |
  | Retry 5 | 4 hours after retry 4 failed |
  | Retry 6 | 24 hours after retry 5 failed |

  That is 7 attempts over about 29 hours. When retry 6 fails too, the
  delivery is final: the event is not sent again. The comment, post or lead
  itself is not lost — you can still read it with our API (for example
  [All Comments](https://docs.99digital.co.il/facebook-api/facebook-pages/all-comments),
  [All Posts](https://docs.99digital.co.il/facebook-api/facebook-pages/all-posts) or
  [Get Lead](https://docs.99digital.co.il/facebook-api/facebook-pages/get-lead)).
- Every attempt goes to the URL that is set at that moment: if you change your
  URL, the remaining retries go to the new one; if you clear it, they stop.
- Events that happen while the connection has no URL, or while it is not
  active, are not sent — not even after you set a URL.
- Every event is sent with the header
  `User-Agent: 99digital-facebook-webhook/1.0`. There is no signature header:
  keep your webhook URL secret (for example, with a long random path).
- Webhook messages come from the following IP address. In case you are
  required to whitelist, please whitelist this: **34.165.99.212**

## Duplicates and order

- **Use `eventId` to ignore duplicates.** The same event always comes with
  the same `eventId`. Very rarely, the same delivery can reach you twice, so
  store the `eventId` of every event you processed and ignore a repeat. (A
  `sendStatus` has no `eventId`: use its `unique`.)
- **Facebook post events are the exception:** every edit of a post is its own
  event, and in rare cases the same post event can arrive twice with two
  different `eventId` values (also a new post that arrives as `created`
  twice). Treat a post event with the same `postId`, `action` and `text` as
  one you already processed. See
  [Facebook Post](https://docs.99digital.co.il/facebook-api/webhooks/facebook-post).
- **The order of delivery is not guaranteed.** For example, a `deleted` can
  arrive before its `created`, or an Instagram post after its first comment.
  Order events by `timestamp`.
- **Ignore what you don't know.** New `event` and `action` values will be
  added (for example, Messenger events). Answer them with 200 and ignore
  them.

## Example receiver

A small receiver in Python ([Flask](https://flask.palletsprojects.com/)): it
answers at once, ignores repeats by `eventId`, and skips your own comments.

```python
import logging
import queue
import threading

from flask import Flask, request

app = Flask(__name__)
events = queue.Queue()
seen = set()  # in production: a database table with eventId as a unique key


@app.post("/99digital/facebook-webhook")
def facebook_webhook():
    payload = request.get_json(silent=True)
    if isinstance(payload, dict):
        events.put(payload)  # answer first, process afterwards
    return "", 200


def handle(event):
    if event.get("event") == "comment" and event.get("action") == "created":
        if event.get("fromSelf"):
            return  # written by your own Page or account: never auto-reply to it
        print("New comment", event["commentId"], event.get("text"))
    elif event.get("event") == "lead" and event.get("leadFetched"):
        print("New lead", event["leadgenId"], event["lead"]["fields"])
    # any other event or action: ignore it


def worker():
    while True:
        event = events.get()
        event_id = event.get("eventId")
        if event_id in seen:
            continue  # a repeat of an event you already processed
        if event_id:
            seen.add(event_id)
        try:
            handle(event)
        except Exception:
            logging.exception("could not process event %s", event_id)


threading.Thread(target=worker, daemon=True).start()
```

## Checklist

- [ ] Call [Set Webhook](https://docs.99digital.co.il/facebook-api/webhooks/set-webhook) for every
      connection (`from`) — and again after every onboarding of it.
- [ ] Use an `https://` URL on a public host.
- [ ] Answer with a 2xx status within 15 seconds, and process the event
      afterwards.
- [ ] Store `eventId` and ignore repeats. For Facebook post events, also treat
      the same `postId`, `action` and `text` as already processed.
- [ ] In an automatic reply, skip every event with `fromSelf` true.
- [ ] Order events by `timestamp`, not by the time they arrive.
- [ ] Ignore a `created` or `edited` Facebook post event for a `postId` you
      already saw `deleted`.
- [ ] Handle `text` null (`textFetched` false) and `lead` null
      (`leadFetched` false).
- [ ] Download the `mediaUrl` of an Instagram post soon after the event — the
      link is temporary.
- [ ] Protect lead answers: they are personal data.
- [ ] Ignore `event` and `action` values you don't know.

## Coming later

These are not sent yet. When they come, they arrive on the same URL, with new
`event` values:

- Incoming Facebook Messenger and Instagram Direct messages (Facebook
  Messenger and Instagram Messenger connections, `facebook_type` 1 and 2).
- Reactions on posts and comments.
- Mentions of your Page or account.
- Comments on Instagram live videos.
