接收受众群体名单的网络钩子通知

本指南介绍了如何使用网络钩子接收有关受众群体导出请求状态的异步通知。此功能仅在 v1alpha 版 Data API 中提供。

网络钩子通知是 Google Analytics(分析)Data API 的一项高级功能。如需简要了解受众群体导出功能,请参阅创建受众群体导出

如果没有 webhook,您将需要定期轮询 API 以确定请求何时完成。

使用 Cloud Run 创建示例 webhook 应用

您可以按照快速入门:将示例服务部署到 Cloud Run 教程,使用 Google Cloud 创建示例网络钩子应用。

为使示例服务能够监听 POST 网络钩子通知请求,请将快速入门教程中的 index.js 文件替换为以下代码:

  import express from 'express';

  const app = express();
  app.use(express.json());

  app.post('/', (req, res) => {
    const channelToken = req.get('X-Goog-Channel-Token');
    const bodyJson = JSON.stringify(req.body);

    console.log(`channel token: ${channelToken}`);
    console.log(`notification body: ${bodyJson}`);

    res.sendStatus(200);
  });

  const port = parseInt(process.env.PORT) || 8080;
  app.listen(port, () => {
    console.log(`helloworld: listening on port ${port}`);
  });

对于以 POST 请求形式发送的每个传入 Webhook 通知,此代码会输出 Webhook 通知 JSON 正文和通道令牌值,并返回 HTTP 代码 200 以指示操作成功。

在完成 Cloud Run 快速入门教程的学习并使用 gcloud run deploy 命令部署 Webhook 应用后,请保存部署服务的网址。

服务网址显示在控制台中,例如:

  Service URL: https://webhooks-test-abcdef-uc.a.run.app

这是服务器通知 URI,您的应用会在此 URI 中监听来自 Google Analytics(分析)的网络钩子通知。

创建受众群体名单并开启网络钩子通知

如需请求 webhook 通知,请在 webhookNotification 对象中指定以下值:

  • 服务器通知 URI,包含将接收网络钩子通知的网址。

  • (可选)任意字符串 channelToken,以防止邮件被仿冒。在 webhook POST 请求的 X-Goog-Channel-Token HTTP 标头中指定 channelToken

以下是使用 webhook 的请求示例:

HTTP 请求

POST https://analyticsdata.googleapis.com/v1alpha/properties/1234567/audienceLists
{
  "webhookNotification": {
    "uri": "https://webhooks-test-abcdef-uc.a.run.app",
    "channelToken": "123456"
  },
  "audience": "properties/1234567/audiences/12345",
  "dimensions": [
    {
      "dimensionName": "deviceId"
    }
  ]
}

audienceLists.create 方法的响应包含 webhookNotification,用于确认指定的网络钩子在 5 秒内成功响应。

以下是示例响应:

HTTP 响应

{
  "response": {
    "@type": "type.googleapis.com/google.analytics.data.v1alpha.AudienceList",
    "name": "properties/1234567/audienceLists/123",
    "audience": "properties/1234567/audiences/12345",
    "audienceDisplayName": "Purchasers",
    "dimensions": [
      {
        "dimensionName": "deviceId"
      }
    ],
    "state": "ACTIVE",
    "beginCreatingTime": "2024-06-10T04:50:09.119726379Z",
    "creationQuotaTokensCharged": 51,
    "rowCount": 13956,
    "percentageCompleted": 100,
    "webhookNotification": {
      "uri": "https://webhooks-test-abcdef-uc.a.run.app",
      "channelToken": "123456"
    }
  }
}

如果 webhook 无法响应,或者您提供了不正确的服务网址,则会返回错误消息。

以下是您可能会收到的错误示例:

{
  "error": {
    "code": 400,
    "message": "Expected response code of 200 from webhook URI but instead
    '404' was received.",
    "status": "INVALID_ARGUMENT"
  }
}

处理网络钩子通知

向 webhook 服务发出的 POST 请求在正文中包含长时间运行的操作资源的 JSON 版本,以及 sentTimestamp 字段。发送的时间戳用于指定请求的 Unix 纪元时间(以微秒为单位)。您可以使用此时间戳来识别重放的通知。

在创建受众群体名单期间,系统会向网络钩子发送一个或两个 POST 请求:

  1. 第一个 POST 请求会立即发送,显示新创建的受众群体名单处于 CREATING 状态。如果对 webhook 的第一个请求失败,audienceLists.create 操作将返回错误和 webhook 失败详情。
  2. 第二个 POST 请求会在受众群体名单创建完毕后发送。当受众群体名单达到 ACTIVEFAILED 状态时,即表示创建完成。

以下示例展示了某个受众群体名单的第一条通知,该通知处于 CREATING 状态:

  {
    "sentTimestamp":"1718261355692983",
    "name": "properties/1234567/audienceLists/123",
    "audience": "properties/1234567/audiences/12345",
    "audienceDisplayName":"Purchasers",
    "dimensions":[{"dimensionName":"deviceId"}],
    "state":"CREATING",
    "beginCreatingTime": "2024-06-10T04:50:09.119726379Z",
    "creationQuotaTokensCharged":0,
    "rowCount":0,
    "percentageCompleted":0,
    "webhookNotification":
      {
        "uri": "https://webhooks-test-abcdef-uc.a.run.app",
        "channelToken":"123456"
      }
  }

以下示例展示了针对某个受众群体名单的第二条通知,其状态为 ACTIVE

  {
    "sentTimestamp":"1718261355692983",
    "name": "properties/1234567/audienceLists/123",
    "audience": "properties/1234567/audiences/12345",
    "audienceDisplayName":"Purchasers",
    "dimensions":[{"dimensionName":"deviceId"}],
    "state":"ACTIVE",
    "beginCreatingTime": "2024-06-10T04:50:09.119726379Z",
    "creationQuotaTokensCharged":68,
    "rowCount":13956,
    "percentageCompleted":100,
    "webhookNotification":
      {
        "uri": "https://webhooks-test-abcdef-uc.a.run.app",
        "channelToken":"123456"
      }
  }

第二个通知用于确认受众群体名单已创建完毕,可以使用 audienceLists.query 方法进行查询了。

如需在调用 audienceLists.create 方法后测试 webhook,您可以检查示例 Cloud Run webhook 应用的日志,并查看 Google Analytics(分析)发送的每个通知的 JSON 正文。