이벤트와 웹훅
이벤트와 웹훅
저장 콜백 외에도 앱은 세션, 사람, 문서, 메모에 관한 이벤트를 받을 수 있습니다. 서명은 저장 콜백과 똑같고(MRO-Signature), 같은 백오프로 재시도되며, 서버의 응답과 함께 개발자 콘솔(전송 및 이벤트)에 표시됩니다. 콘솔의 웹훅 패널이나 콘솔 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 }.
- 이벤트는 앱의 웹훅 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)