事件與 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 排序。
- 以 { "event": "<type>" } 呼叫 POST /api/v1/embed/apps/{id}/callbacks/test,會立即傳送該事件的一份已簽章範例("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)