适用于: 开发 人员
当应用程序必须响应 SharePoint Embedded 容器中的文件更改时,请使用 Microsoft Graph Webhook。 订阅告知 Microsoft Graph 在订阅的资源发生更改时调用 HTTPS 终结点。
创建通知终结点
公开接受 POST 请求的 HTTPS 终结点。 在本地开发期间,使用 ngrok 将请求隧道传送到本地服务器。
ngrok http 3001
Microsoft Graph 创建订阅时,它会通过发送 validationToken 查询参数来验证终结点。 使用 HTTP 200 以纯文本形式返回该令牌。
export const onReceiptAdded = async (req: Request, res: Response) => {
const validationToken = req.query['validationToken'];
if (validationToken) {
res.send(200, validationToken, { "Content-Type": "text/plain" });
return;
}
const driveId = req.query['driveId'];
if (!driveId) {
res.send(200, "Notification received without driveId, ignoring", { "Content-Type": "text/plain" });
return;
}
console.log(`Received driveId: ${driveId}`);
res.send(200, "");
}
在 API 服务器中注册路由,并在路由处理通知之前启用请求正文和查询分析。
server.use(restify.plugins.bodyParser(), restify.plugins.queryParser());
server.post('/api/onReceiptAdded', async (req, res, next) => {
try {
const response = await onReceiptAdded(req, res);
res.send(200, response);
} catch (error: any) {
res.send(500, { message: `Error in API server: ${error.message}` });
}
next();
});
订阅容器驱动器
使用 Microsoft Graph 创建订阅。 在此模式中,SharePoint Embedded 容器 ID 是驱动器 ID。
POST https://graph.microsoft.com/v1.0/subscriptions
Content-Type: application/json
{
"changeType": "updated",
"notificationUrl": "https://contoso.example/api/onReceiptAdded?driveId={container-id}",
"resource": "drives/{container-id}/root",
"expirationDateTime": "2026-06-25T03:58:34.088Z",
"clientState": ""
}
订阅下的 drives/{container-id}/root 更改并追加 driveId={container-id} 到通知 URL,以便处理程序可以标识容器。
计算过期时间
驱动器项订阅的最大生存期为 4,230 分钟。 在创建订阅之前,使用请求前脚本或后端计划程序设置过期时间。
var now = new Date();
var duration = 1000 * 60 * 4230;
var expiry = new Date(now.getTime() + duration);
pm.environment.set("ContainerSubscriptionExpiry", expiry.toISOString());
存储订阅 ID、资源、容器 ID 和过期时间。 在订阅过期之前续订每个订阅。
安全地处理通知
从 Webhook 请求快速返回。 队列后台工作,使用 Microsoft Graph 提取当前文件或容器状态,并使处理幂等,因为通知可能会重复或延迟。
将 Webhook 用于文档处理、索引刷新、用户通知或工作流触发器等操作。 针对错过的通知或过期的订阅保留定期对帐作业。
验证流
创建订阅、上传或更新容器中的文件,并确认终结点记录预期的驱动器 ID。 如果验证失败,检查公共 HTTPS URL、validationToken响应内容类型,以及服务器是否在执行路由之前分析查询参数。