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

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

Webhook 通知是 Google Analytics Data API 的一项高级功能。如需了解受众群体导出功能,请参阅创建受众群体导出

如果不使用 Webhook,您需要定期轮询 API,以确定请求何时完成。

使用 Cloud Run 创建示例 webhook 应用

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

为了让示例服务能够监听 POST Webhook 通知请求,请将快速入门教程中的 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,您的应用会在此处监听来自 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,这确认了指定的 webhook 在 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 纪元以来经历的微秒数表示)。您可以使用此时间戳来识别重放的通知。

在创建受众群体列表期间,系统会向 webhook 发送一个或两个 POST 请求:

  1. 第一个 POST 请求会立即发送,显示新创建的受众群体列表处于 CREATING 状态。如果向网络钩子的第一个请求失败,audienceLists.create 操作会返回错误和网络钩子失败详细信息。
  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 正文。