事件与 Webhook
事件与 Webhook
除保存回调外,应用还可以接收关于会话、人员、文档和批注的事件:签名方式与保存回调完全相同(MRO-Signature),按同样的退避重试,并连同你服务器的应答列在开发者控制台中(投递与事件)。在控制台的 Webhooks 面板中订阅,或使用控制台 API:
# 为应用订阅事件(或在开发者控制台: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": ["*"] 订阅所有事件(包括今后新增的);null 则只订阅保存回调的事件。
# 发送任意事件的签名样例,看看你的接口如何响应
curl -X POST https://mroffice.ai/api/v1/embed/apps/$APP_ID/callbacks/test -d '{ "event": "comment.mention" }' …| 事件 | 何时发送 |
|---|---|
document.saved、document.save_failed | 保存写出了新版本 / 保存失败(即保存回调:无论是否订阅,总是发到回调 URL)。 |
session.started、session.ended | 会话开始;会话结束(data.reason:closed、idle、expired 或 revoked)。 |
user.joined、user.left | 某人在文档上的第一个会话开始;其最后一个会话结束。 |
document.opened、document.closed | 文档原本没有会话、第一个会话开始;最后一个会话结束。 |
document.locked、document.unlocked | 有可写入文档的人(view 以外的任何模式)在文档中 / 不再有——即 WOPI 的锁:期间不要改动你那边的副本。 |
comment.created、comment.updated、comment.resolved、comment.deleted | 在文档保存时(手动、自动或关闭时的保存)比较新文件与上一份文件中的批注得出:Word 批注与回复、Excel 线程批注与旧式批注、PowerPoint 批注、PDF 注释。 |
revision.accepted、revision.rejected | 某条修订(Word)自上次保存后消失:其效果保留即为接受,否则为拒绝。 |
job.succeeded、job.failed | 服务端任务(转换、模板填充、比较)结束;data 为该任务,附新签的 download_url。请求带 "webhook": true 时也会单独发送。 |
comment.mention | 发出提及他人的批注时立即发送(见“用户、在线状态与 @提及”)。 |
form.submitted | 填写 PDF 表单的人已提交(完成并提交):data.role 和 data.values。 |
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": "[email protected]" },
"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": "[email protected]" }]
}
}- document 为 { id, key, name, format, version };session 为 { id, mode, effective_mode };user 为做出该操作的你方用户 { id, name, email }。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 }。
- 事件发到应用的 webhook URL(未设置时发到回调 URL);保存回调自身的两种事件总是发到回调 URL。请在 20 秒内应答任意 2xx;否则会在 10 秒、30 秒、2 分钟、10 分钟、30 分钟、1 小时、3 小时和 6 小时后重试(410 Gone 立即停止)。每次重试的 MRO-Event-Id 和 Idempotency-Key 都相同:每个事件只处理一次。事件可能乱序到达:请按 created 排序。
- POST /api/v1/embed/apps/{id}/callbacks/test 并带上 { "event": "<type>" },会立即发送该事件的一份签名样例("test": true);GET /api/v1/embed/apps/{id}/webhooks 列出订阅、所有事件类型以及每种已发送的数量。
import express from "express";
import { verifyWebhook } from "mroffice-embed/server"; // 或使用上面的 verifyMROfficeSignature
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(); // 不是 MR Office 签名的,或已过期
}
if (await alreadyHandled(event.id)) return res.json({ ok: true }); // 重试时带着相同的 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 }); // 20 秒内返回任意 2xx
});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)# FastAPI;Flask 和 Django 读取原始请求体的方式相同。
from fastapi import FastAPI, Request, Response
app = FastAPI()
@app.post("/mroffice/events")
async def mroffice_events(request: Request) -> Response:
raw = await request.body() # 发送时的原始字节,未经任何 JSON 解析
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"]): # 重试时带着相同的 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)