尝试从应用程序脚本获取 google analytics 4 数据时出现 403 错误

403 error when attempting to fetch google analytics 4 data from app script

我正在尝试将自定义社区连接器连接到 google analytics 4,以便从分析中获取数据并能够在应用程序脚本中对其进行修改,然后将其发送到数据工作室。但是,我很难从 google 分析中连接和检索数据。

错误:

    { error: 
   { code: 403,
     message: 'Google Analytics Data API has not been used in project 640397821842 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/analyticsdata.googleapis.com/overview?project=640397821842 then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.',
     status: 'PERMISSION_DENIED',
     details: [ [Object], [Object] ] } }

我已经设置了范围

 "oauthScopes": [
    "https://www.googleapis.com/auth/script.external_request",
    "https://www.googleapis.com/auth/analytics.readonly"
  ],

我要测试的代码:

function testFetch(){
  const options = {
  entry: { propertyId: 263290444},
  "dateRanges": [{ "startDate": "2020-12-01", "endDate": "2021-03-01" }],
  "dimensions": [{ "name": "country" }],
  "metrics": [{ "name": "activeUsers" }],
  // etc.
  }
  var response = UrlFetchApp.fetch(
    'https://analyticsdata.googleapis.com/v1alpha:runReport', {
    method: 'POST',
    muteHttpExceptions: true,
    headers: {
      Authorization : `Bearer ${ScriptApp.getOAuthToken()}`
    },
    contentType: 'application/json; charset=utf-8',
    payload: JSON.stringify(options)
  });
  var result = JSON.parse(response.getContentText());
  console.log(result);

'Google Analytics Data API has not been used in project 640397821842 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/analyticsdata.googleapis.com/overview?project=640397821842 then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.', status:

你遇到的问题是你没有在Google开发者控制台中启用API你需要按照错误消息中的link然后去图书馆看看Google 分析数据 api 并启用它。

一旦启用它,请再次尝试 运行 您的应用程序。

对于那些有同样问题但可能忽略了一些步骤的人:

  1. https://console.cloud.google.com/

    创建一个 API 项目
  2. 通过更改 appscript 设置中的 Google Cloud Platform (GCP) 项目,确保将您的 appscript 项目连接到云 API 项目(它设置为默认值开始时的项目)。

  3. 从云项目的 API 库中启用所需的 APIs。

  4. 现在您将能够获取与您已启用的 API 相关的网址。