接收目標對象名單的 Webhook 通知

本指南說明如何使用 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 通知。

建立目標對象名單並啟用 Webhook 通知

如要要求 Webhook 通知,請在 webhookNotification 物件中指定下列值:

  • 伺服器通知 URI,內含接收 Webhook 通知的網址。

  • (選用) 任意字串 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 通知

傳送至 Webhook 服務的 POST 要求,內文同時包含長時間執行的作業資源的 JSON 版本和 sentTimestamp 欄位。傳送時間戳記會指定要求傳送時的 Unix Epoch 時間 (以微秒為單位)。您可以使用這個時間戳記來識別重新傳送的通知。

建立目標對象名單時,系統會向 Webhook 傳送一或兩項 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 主體。