使用 Webhook

使用 SharePoint Embedded 设置 Webhook

Webhook 是激活触发器时由应用程序传输的自动消息。 它们可以在 SPE 中使用,以实现工作流自动化、系统集成以及实时响应事件。

每当更新现有文件或上传新文件时,你都会使用 Webhook 从应用程序调用 Azure 认知服务 API。

若要使用 当前的 SharePoint Embedded 应用程序设置 Webhook,需要:

  1. 创建并注册 Webhook 终结点,以在容器中发生更改时获取通知。 这将使用 REST API 完成。
  2. 连接到 Graph 并订阅更改。 可以通过在本地运行应用程序或在云中部署应用程序,向 Internet 公开应用程序。 在本教程中,你将使用前者,方法是利用 ngrok,然后通过进行 POST 调用来订阅更改。
  3. 通过处理 Webhook 数据执行任何所需的作。 使用 Azure 认知服务启用文档处理教程中介绍了一个此类用例。

使用 Webhook 架构

提示

若要详细了解本教程中使用的 Microsoft Graph API,请参阅 创建订阅

创建和注册 Webhook

打开 index.ts 文件并添加终结点 onReceiptAdded

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();
});

还需要在此文件的顶部添加查询分析程序插件,以便它在服务器启动时运行:

server.use(restify.plugins.bodyParser(), restify.plugins.queryParser());

创建 onReceiptAdded.ts 并实现 onReceiptAdded 方法以读取 validationTokendriveIdvalidationToken 当 Microsoft Graph 在创建 Webhook 订阅时进行一次性调用来验证终结点时是必需的。 driveId 是为其创建订阅的容器 ID。

require('isomorphic-fetch');

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, "");
  return;
}

连接到 Graph 并订阅更改

按照 文档 作,使用 ngrok 为后端服务器创建隧道。

启动应用后,在终端中运行以下命令:

ngrok http 3001

成功完成后,应获得以下输出。 应用的面向公众的终结点在红色矩形中突出显示:

ngrok 注册

隧道处于活动状态后,可以通过添加 Webhook URL 来订阅容器中的增量更改。 为此,请打开 Postman,并使用相应的图形访问令牌和notificationUrldriveId追加作为查询参数的 发出以下POST请求,以确保仅在所需容器中收到更改通知。

POST  https://graph.microsoft.com/v1.0/subscriptions
{
  "changeType": "updated",
  "notificationUrl":"https://5ac2-2404-f801-8028-3-691a-87b2-d309-545b.ngrok-free.app/api/onReceiptAdded?driveId={{ContainerId}}",
  "resource": "drives/{{ContainerId}}/root",
  "expirationDateTime": "2024-01-20T03:58:34.088Z",
  "clientState": ""
}

可以将以下代码片段用于设置从当前时间开始的最大可能过期时间 4230 分钟,方法是将此代码片段添加到“请求前脚本”部分。 它将设置可在请求正文中使用的环境变量。

var now = new Date()
var duration = 1000 * 60 * 4230; // max lifespan of driveItem subscription is 4230 minutes
var expiry = new Date(now.getTime() + duration);
var expiryDateTime = expiry.toISOString();

pm.environment.set("ContainerSubscriptionExpiry", expiryDateTime);

此时,如果在容器中添加/更新任何文件,则会在以前添加的终结点 (/api/onReceiptAdded) 并在控制台上收到日志消息的通知: Received driveId: <containerId>