- Trang chủ nhà phát triển
- Nhúng trình soạn thảo
- Bắt đầu nhanh
Bắt đầu nhanh
Bắt đầu nhanh
Cách nhanh nhất: npx mroffice-embed init
Trong thư mục dự án của bạn, một lệnh làm thay bạn cả ba bước bên dưới: nó tìm framework của bạn (Next.js, Vite, Express, Nuxt, SvelteKit, FastAPI, Flask, Django hoặc trang HTML thuần), tạo một ứng dụng trong tài khoản MR Office của bạn sau một lần Allow trong trình duyệt, ghi các khóa vào .env.local hoặc .env (không bao giờ in ra, và không đưa vào git), rồi thêm một route máy chủ ký token phiên cùng một trang mở trình soạn thảo. Các tác tử lập trình AI chạy nó với --yes. Chạy lại không làm thay đổi những gì đã có. Hoặc làm thủ công:
# trong thư mục dự án của bạn: một ứng dụng trong tài khoản của bạn (một lần "Allow" trong trình duyệt),
# các khóa của nó trong .env.local / .env (không bao giờ in ra, không đưa vào git), một route máy chủ
# ký token phiên và một trang mở trình soạn thảo
npx mroffice-embed init
# Tác tử lập trình AI và script: không hỏi gì (--origin thêm một origin production)
npx mroffice-embed init --yes --origin https://app.example.com1. Tạo một ứng dụng
Trong bảng điều khiển dành cho nhà phát triển, chọn Ứng dụng mới. Đặt tên cho nó, khai báo origin của các trang sẽ hiển thị trình soạn thảo (ví dụ https://app.example.com — origin chính xác, chỉ https), và tùy chọn thêm URL callback của bạn. Sao chép hai khóa được hiển thị: khóa bí mật (mro_sk_…) ký token phiên và gọi API; khóa webhook (mro_whsec_…) xác minh callback. Chúng chỉ hiển thị một lần. Hãy mở một tệp mẫu để thấy trình soạn thảo hoạt động trước khi viết bất kỳ dòng mã nào. Khi phát triển trên máy tính của bạn, hãy bật Cho phép localhost: khi đó mọi trang http://localhost hoặc http://127.0.0.1, ở bất kỳ cổng nào, đều hiển thị được trình soạn thảo.
2. Cấp token phiên trên máy chủ của bạn
// server.js — endpoint token của bạn, dùng trình trợ giúp phía máy chủ của gói
// (Node 18+, Deno, Bun, edge function; npm install mroffice-embed).
import { createSessionToken } from "mroffice-embed/server";
app.get("/api/contracts/:id/editor-token", requireLogin, async (req, res) => {
const contract = await contracts.get(req.params.id, req.user); // bước kiểm tra quyền truy cập của riêng bạn
const token = await createSessionToken({
appId: process.env.MROFFICE_APP_ID, // lấy từ bảng điều khiển dành cho nhà phát triển
secretKey: process.env.MROFFICE_SECRET_KEY, // mro_sk_… (chỉ trên máy chủ)
file: {
key: `contract-${contract.id}`, // mọi người có khóa này cùng chỉnh sửa một tài liệu
name: contract.fileName, // .docx .xlsx .pptx .pdf
url: contract.signedDownloadUrl(), // nơi MR Office đọc tệp (https)
version: contract.etag, // tùy chọn
},
user: { id: req.user.id, name: req.user.name },
mode: contract.canEdit(req.user) ? "edit" : "view",
});
res.json({ token });
});// server.js — cấp token phiên cho một người và một tệp (Node 18+).
import { createHmac, randomUUID } from "node:crypto";
const APP_ID = process.env.MROFFICE_APP_ID; // lấy từ bảng điều khiển dành cho nhà phát triển (mroffice.ai/developers/console)
const SECRET = process.env.MROFFICE_SECRET_KEY; // mro_sk_… (chỉ trên máy chủ)
const b64url = (value) => Buffer.from(JSON.stringify(value)).toString("base64url");
export function mintSessionToken({ fileKey, fileName, fileUrl, version, userId, userName, mode = "edit" }) {
const now = Math.floor(Date.now() / 1000);
const header = { alg: "HS256", typ: "JWT" };
const claims = {
iss: APP_ID,
aud: "mroffice-embed",
iat: now,
exp: now + 600, // tối đa 3600
jti: randomUUID(), // dùng một lần
file: { key: fileKey, name: fileName, url: fileUrl, version },
mode, // "edit" hoặc "view"
user: { id: userId, name: userName },
};
const body = `${b64url(header)}.${b64url(claims)}`;
const signature = createHmac("sha256", SECRET).update(body).digest("base64url");
return `${body}.${signature}`;
}
// ví dụ với Express:
// app.get("/api/contracts/:id/editor-token", requireLogin, (req, res) => {
// const contract = await contracts.get(req.params.id, req.user);
// res.json({ token: mintSessionToken({
// fileKey: `contract-${contract.id}`, fileName: contract.fileName,
// fileUrl: contract.signedDownloadUrl(), version: contract.etag,
// userId: req.user.id, userName: req.user.name,
// mode: contract.canEdit(req.user) ? "edit" : "view" }) });
// });# server.py — cùng token đó với PyJWT (pip install pyjwt)
import os, time, uuid
import jwt
APP_ID = os.environ["MROFFICE_APP_ID"]
SECRET = os.environ["MROFFICE_SECRET_KEY"] # mro_sk_… (chỉ trên máy chủ)
def mint_session_token(file_key, file_name, file_url, user_id, user_name, mode="edit", version=None):
now = int(time.time())
claims = {
"iss": APP_ID,
"aud": "mroffice-embed",
"iat": now,
"exp": now + 600,
"jti": str(uuid.uuid4()),
"file": {"key": file_key, "name": file_name, "url": file_url, "version": version},
"mode": mode,
"user": {"id": user_id, "name": user_name},
}
return jwt.encode(claims, SECRET, algorithm="HS256")3. Mở trình soạn thảo trong trang của bạn
<div id="editor" style="height: 80vh"></div>
<script src="https://mroffice.ai/embed/v1/embed.js"></script>
<script>
const editor = MROffice.open({
container: "#editor",
appId: "YOUR_APP_ID", // trình soạn thảo bắt đầu tải trong khi máy chủ của bạn ký
// Được gọi mỗi khi cần token mới: lần đầu tiên, trước khi phiên
// kết thúc, sau khi tải lại, và bởi setMode() cùng setLocale().
token: () => fetch("/api/contracts/42/editor-token").then((r) => r.json()).then((b) => b.token),
locale: "en",
theme: "light", // "dark" | "system"
ui: { toolbar: "full" }, // "none" ẩn dải băng
onReady: (event) => console.log("open", event.document),
onChange: (event) => console.log("modified", event.modified),
onSave: (event) => console.log("saved version", event.version, event.downloadUrl),
onError: (error) => console.error(error.code, error.hint ?? error.message),
});
document.querySelector("#save").onclick = () => editor.requestSave();
</script>Hoặc cài gói có kiểu:
npm install mroffice-embed
import { open } from "mroffice-embed";
const editor = open({
container: element,
appId: "YOUR_APP_ID",
token: ({ mode }) => getEditorToken(contractId, mode), // endpoint của bạn
onSave: (saved) => { /* … */ },
onConnectionChange: ({ online }) => setBanner(online ? null : "Reconnecting…"),
});
await editor.ready;
const saved = await editor.requestSave(); // { version, sha256, downloadUrl, … }
await editor.setMode("view"); // một token mới từ token({ mode: "view" })
await editor.setLocale("ja"); // tải lại bằng tiếng Nhật, vẫn tài liệu đó
await editor.destroy();Trong React hoặc Vue, đó chỉ là một component (Angular, Svelte và Web Component cũng vậy: xem Component cho framework):
import { MROfficeEditor } from "mroffice-embed/react";
// route trên máy chủ của bạn trả về { token, appId, origin } (npx mroffice-embed init tạo sẵn)
<MROfficeEditor tokenUrl="/api/mroffice/session" style={{ height: "80vh" }} onSave={(saved) => console.log(saved.version)} /><script setup>
import { MROfficeEditor } from "mroffice-embed/vue";
</script>
<template>
<MROfficeEditor token-url="/api/mroffice/session" style="height: 80vh" @save="(saved) => console.log(saved.version)" />
</template>Phát triển trên localhost
Khi bật Cho phép localhost, máy chủ dev của bạn hiển thị được trình soạn thảo mà không cần chỉnh gì. Token file.local hoàn toàn không cần máy chủ tệp: người dùng (hoặc trang của bạn, bằng openFile) mở một tệp từ máy tính của họ. Mọi lần bắt đầu bị từ chối, kèm lý do, đều nằm trong mục Sự kiện của bảng điều khiển.
// Trong khi phát triển: "Allow localhost" của bảng điều khiển cho phép mọi trang http://localhost:<port>
// (và http://127.0.0.1:<port>) hiển thị trình soạn thảo, nên máy chủ dev của bạn chạy được ngay.
// Mở tệp từ máy tính của bạn bằng token file.local (không cần máy chủ tệp):
const token = await createSessionToken({
appId, secretKey,
file: { key: `dev-${Date.now()}`, local: true }, // ứng dụng phải cho phép tệp cục bộ
user: { id: "me", name: "Me" },
});