# Events and webhooks

Source: https://mroffice.ai/en/developers/embed/webhooks

Besides the save callback, an app can receive events about its sessions, people, documents and comments, signed exactly as the save callback is (MRO-Signature), retried with the same backoff, and listed with your server's answers in the developer console (Deliveries and Events). Subscribe in the console's Webhooks panel, or with the console API:

```bash
# Subscribe the app to events (or in the developer console: Webhooks)
curl -X PATCH https://mroffice.ai/api/v1/embed/apps/$APP_ID \
  -H "Content-Type: application/json" -H "X-CSRF-Token: …" --cookie "…" \
  -d '{ "webhook_url": "https://your-app.example/mroffice/events",
        "webhook_events": ["document.opened", "user.joined", "comment.created", "comment.mention", "document.closed"] }'
# "webhook_events": ["*"] subscribes to every event, new ones too; null to the save callback's only.

# Send a signed sample of any event to see your endpoint answer it
curl -X POST https://mroffice.ai/api/v1/embed/apps/$APP_ID/callbacks/test -d '{ "event": "comment.mention" }' …
```

| Event | When |
| --- | --- |
| document.saved, document.save_failed | A save wrote a new version / failed (the save callback: always sent to the callback URL, subscribed or not). |
| session.started, session.ended | A session begins; it ends (data.reason: closed, idle, expired or revoked). |
| user.joined, user.left | A person's first session on a document begins; their last one ends. |
| document.opened, document.closed | The first session on a document that had none; the last one ends. |
| document.locked, document.unlocked | Someone who may write the document (any mode but view) is in it / no longer is — WOPI's lock: do not change your copy meanwhile. |
| comment.created, comment.updated, comment.resolved, comment.deleted | Found when the document is saved (manual, auto or closing save), by comparing the comments in the new file with the last one's: Word comments and replies, Excel threaded and legacy comments, PowerPoint comments, PDF notes. |
| revision.accepted, revision.rejected | A tracked change (Word) is gone since the last save: accepted when its effect stayed, rejected otherwise. |
| job.succeeded, job.failed | A server job (conversion, template fill, compare) ended; data is the job with a fresh download_url. Also sent for one request with "webhook": true. |
| comment.mention | At once, when a comment naming people is posted (see Users, presence and mentions). |
| form.submitted | A person filling in a PDF form submitted it (Complete & Submit): data.role and data.values. |

Every event has this envelope; data is per type:

```http
POST https://your-app.example/mroffice/events
Content-Type: application/json
User-Agent: MROffice-Embed/1
MRO-Signature: t=1795100212,v1=5f1c…e9a2
MRO-Event-Id: 2b7d…            (also Idempotency-Key: the same on every retry)
MRO-Event-Type: comment.mention

{
  "id": "2b7d…",
  "type": "comment.mention",
  "created": "2026-11-20T10:00:00+00:00",
  "app_id": "7f1d2c3b-…",
  "document": { "id": "…", "key": "contract-42", "name": "contract.docx", "format": "docx", "version": 3 },
  "session":  { "id": "…", "mode": "comment", "effective_mode": "comment" },
  "user":     { "id": "user-7", "name": "Ada Lovelace", "email": "ada@example.com" },
  "data": {
    "comment":   { "thread_id": "w:1A2B3C4D", "id": "w:1A2B3C4D:m1", "text": "@Grace Hopper please check this clause." },
    "mentioned": [{ "id": "user-9", "name": "Grace Hopper", "email": "grace@example.com" }]
  }
}
```

- document is { id, key, name, format, version }; session is { id, mode, effective_mode }; user is your person { id, name, email } (who did it). comment.* data: { comment: { id, author, author_id, text, resolved, parent_id, date, anchor? }, save_id, version }; revision.* data: { revision: { type, author, author_id, date, text }, save_id, version }.
- Events go to the app's webhook URL (its callback URL when it has none); the save callback's own two always go to the callback URL. Answer any 2xx within 20 seconds; anything else is retried after 10 s, 30 s, 2 min, 10 min, 30 min, 1 h, 3 h and 6 h (410 Gone stops). MRO-Event-Id and Idempotency-Key stay the same on every retry: handle each event once. Events can arrive out of order: order them by created.
- POST /api/v1/embed/apps/{id}/callbacks/test with { "event": "<type>" } sends a signed sample of that event ("test": true) now; GET /api/v1/embed/apps/{id}/webhooks lists the subscription, every event type and how many of each were sent.

Node (Express), with the package's verifyWebhook:

```js
import express from "express";
import { verifyWebhook } from "mroffice-embed/server";   // or verifyMROfficeSignature above

app.post("/mroffice/events", express.raw({ type: "application/json" }), async (req, res) => {
  let event;
  try {
    event = await verifyWebhook(req.body, req.get("MRO-Signature"), process.env.MROFFICE_WEBHOOK_SECRET);
  } catch {
    return res.status(401).end();                      // not signed by MR Office, or too old
  }
  if (await alreadyHandled(event.id)) return res.json({ ok: true });   // retries carry the same id
  switch (event.type) {
    case "comment.mention":
      for (const person of event.data.mentioned) await notify(person.id, event.document, event.data.comment.text);
      break;
    case "document.locked":   await files.markEditing(event.document.key, true); break;
    case "document.unlocked": await files.markEditing(event.document.key, false); break;
    case "comment.created":   await activity.add(event.document.key, event.data.comment); break;
  }
  res.json({ ok: true });                              // any 2xx within 20 s
});
```

Python: the signature check:

```python
import hashlib, hmac, time

def verify_mroffice_signature(raw_body: bytes, header: str, webhook_secret: str, tolerance: int = 300) -> bool:
    pairs = [item.split("=", 1) for item in header.split(",") if "=" in item]
    timestamps = [value for key, value in pairs if key.strip() == "t"]
    signatures = [value for key, value in pairs if key.strip() == "v1"]
    if not timestamps or not timestamps[0].isdigit() or abs(time.time() - int(timestamps[0])) > tolerance:
        return False
    expected = hmac.new(webhook_secret.encode(), f"{timestamps[0]}.".encode() + raw_body, hashlib.sha256).hexdigest()
    return any(hmac.compare_digest(expected, candidate.strip()) for candidate in signatures)
```

Python (FastAPI):

```python
# FastAPI; Flask and Django read the raw body the same way.
from fastapi import FastAPI, Request, Response

app = FastAPI()

@app.post("/mroffice/events")
async def mroffice_events(request: Request) -> Response:
    raw = await request.body()                         # the bytes as sent, before any JSON parsing
    if not verify_mroffice_signature(raw, request.headers.get("MRO-Signature", ""), WEBHOOK_SECRET):
        return Response(status_code=401)
    event = json.loads(raw)
    if already_handled(event["id"]):                   # retries carry the same id
        return Response(status_code=200)
    if event["type"] == "comment.mention":
        for person in event["data"]["mentioned"]:
            notify(person["id"], event["document"]["key"], event["data"]["comment"]["text"])
    return Response(status_code=200)
```
