- Trang chủ nhà phát triển
- Nhúng trình soạn thảo
- Callback lưu
Callback lưu
Callback lưu
Khi một lần lưu ghi phiên bản mới, MR Office gửi POST tới URL callback của bạn. Lần lưu thất bại gửi document.save_failed kèm lỗi.
POST https://your-app.example/mroffice/callback
Content-Type: application/json
MRO-Signature: t=1795100212,v1=5f1c…e9a2
MRO-Event-Id: 6f0a1c1e-…
Idempotency-Key: 6f0a1c1e-…
{
"id": "6f0a1c1e-…",
"type": "document.saved",
"created": "2026-11-19T15:03:11+00:00",
"app_id": "7f1d2c3b-…",
"document": {
"id": "…", "key": "contract-42", "name": "contract.docx",
"version": 3, "previous_version": 2, "partner_version": "etag-17",
"sha256": "…", "size": 48211,
"content_type": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"source": "url"
},
"save": { "id": "…", "reason": "manual", "editors": ["user-7", "user-9"], "saved_at": "…" },
"download_url": "https://mroffice.ai/api/v1/embed/download/…?expires=…&signature=…",
"download_expires_at": "2026-11-19T16:03:11+00:00"
}- Hãy xác minh MRO-Signature trước mọi việc khác: t là dấu thời gian Unix, mỗi v1 là HMAC-SHA256(khóa webhook, "<t>.<raw body>") dạng hex (có hai giá trị v1 khi khóa đã xoay vòng vẫn còn được chấp nhận). Hãy từ chối dấu thời gian cũ hơn năm phút.
- Trả lời bằng bất kỳ mã 2xx nào trong vòng 20 giây. Tùy chọn, hãy trả lời { "version": "<your new version>" }: file.version của các token tiếp theo sẽ được so sánh với nó.
- Mọi câu trả lời khác sẽ được gửi lại sau 10 giây, 30 giây, 2 phút, 10 phút, 30 phút, 1 giờ, 3 giờ và 6 giờ (410 Gone thì dừng). id và Idempotency-Key giống nhau ở mọi lần gửi lại: hãy lưu mỗi sự kiện một lần.
- download_url dùng được trong một giờ (mỗi lần gửi lại callback mang một URL mới). Khi phiên bản còn được giữ, bạn có thể lấy nó bằng khóa của mình: GET /api/v1/embed/documents/{key}/content?version=N; phiên bản đã xóa trả về 410 embed_version_purged.
// Callback, dùng trình trợ giúp phía máy chủ của gói (mọi runtime có Web Crypto).
import { verifyCallback } from "mroffice-embed/server";
app.post("/mroffice/callback", express.raw({ type: "application/json" }), async (req, res) => {
let event;
try {
event = await verifyCallback(req.body, req.get("MRO-Signature"), process.env.MROFFICE_WEBHOOK_SECRET);
} catch {
return res.status(401).end(); // không được ký bằng khóa webhook của bạn
}
if (await seen(event.id)) return res.json({ ok: true }); // một callback có thể đến hai lần
// … lưu tệp từ event.download_url, như bên dưới
res.json({ ok: true });
});import { createHmac, timingSafeEqual } from "node:crypto";
// Dùng các byte thô của body, đúng như đã nhận (không phải JSON được tuần tự hóa lại).
export function verifyMROfficeSignature(rawBody, header, webhookSecret, toleranceSeconds = 300) {
const parts = Object.groupBy(header.split(","), (item) => item.split("=")[0].trim());
const t = Number(parts.t?.[0]?.split("=")[1]);
if (!Number.isFinite(t) || Math.abs(Date.now() / 1000 - t) > toleranceSeconds) return false;
const expected = createHmac("sha256", webhookSecret).update(`${t}.`).update(rawBody).digest();
return (parts.v1 ?? []).some((item) => {
const given = Buffer.from(item.split("=")[1] ?? "", "hex");
return given.length === expected.length && timingSafeEqual(given, expected);
});
}
// app.post("/mroffice/callback", express.raw({ type: "application/json" }), async (req, res) => {
// if (!verifyMROfficeSignature(req.body, req.get("MRO-Signature"), process.env.MROFFICE_WEBHOOK_SECRET))
// return res.status(401).end();
// const event = JSON.parse(req.body);
// if (await seen(event.id)) return res.json({ ok: true }); // idempotent
// if (event.type === "document.saved") {
// const file = await fetch(event.download_url).then((r) => r.arrayBuffer());
// const etag = await contracts.storeVersion(event.document.key, file, event.document.version);
// return res.json({ version: etag }); // your new version: compared with the next token's file.version
// }
// res.json({ ok: true });
// });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)