GA4 到 Google Sheets 通过 Google Apps Script – 无法找到适当的请求端点。

huangapple go评论96阅读模式
英文:

GA4 to Google Sheets via GAS - Can't find appropriate request endpoint

问题

如何在Google Apps Script中运行GA4属性的报告?我是否应该使用AnalyticsData命名空间还是Analytics?还是我的属性设置有问题?!

      report = AnalyticsAdmin.Properties.runReport(request,
        'properties/' + 'zxc');

      Logger.log('We dont get here ' + report);

我已经看过这个老问题(类似于这个问题),但似乎无法使用它:

目标

该脚本旨在自动化每周从Google Analytics中检索访问者计数数据的过程,并使用结果更新Google表格。主要步骤包括:

  1. 识别Google Analytics帐户和属性:脚本通过匹配来自Google表格的帐户名称和ID来查找相关的Google Analytics帐户和属性(特别是“新”的GA4属性)。
  2. 列出Web数据流:它列出了所有Web数据流(相当于通用分析中的视图),以供识别的属性。
  3. 运行报告:脚本尝试运行报告,以检索指定日期范围内的总访问者计数(会话数),通常是过去一周。
  4. 更新Google表格:报告结果应添加到工作表中的新列中,日期作为标题。一周的总访问者数会在行的底部汇总。

挑战

脚本面临的主要挑战包括:

  • 从较旧的Google Analytics API转向新的Google Analytics Admin API和数据API。
  • 生成Google Analytics API的请求通过Google执行报告请求
  • 解决与权限和API方法调用相关的调试问题。

状态

该脚本处于开发阶段,目前的重点是解决运行报告以检索访问者计数数据时遇到的错误。

最终的实现将允许从所选的Google Analytics属性自动每周更新Google表格,从而简化了组织的报告流程。

注意:在GA Query Explorer中运行此请求时,我收到了有效的JSON响应:

{
"metricHeaders":[
{
"name":"sessions"
"type":"TYPE_INTEGER"
}
]
"rows":[
{
"metricValues":[...]
}
]
"rowCount":1
"metadata":{
"currencyCode":"ZZZ"
"timeZone":"XX/YY"
}
"kind":"analyticsData#runReport"
}
function getReportDataForProperty(view, property) {
  Logger.log(view);
  Logger.log(property);

  // 从属性对象中提取属性ID
  const matchedViewId = view.name.split('/')[3];
  const matchedPropertyId = property.name.split('/')[1];

  Logger.log(matchedViewId);
  Logger.log(matchedPropertyId);

  try {
      const metrics =  [
        { "name": "sessions" }
        //查看可用的度量标准 https://developers.google.com/analytics/devguides/reporting/data/v1/api-schema?hl=en#metrics
        ]
      const dateRange = AnalyticsData.newDateRange();
      dateRange.startDate = getLastNdays(7);
      dateRange.endDate = 'today';

      const request = AnalyticsReporting.newReportRequest();
      request.metrics = metrics;
      request.dateRanges = dateRange;
      //request.property = "properties/zxc";

      Logger.log(request);

      // --------------------- 此处需要支持 ---------------------

      report = AnalyticsAdmin.Properties.runReport(request,
        'properties/' + 'zxc');

      // 我也尝试了 report = AnalyticsData.Properties.runReport(request,
        'properties/' + 'zxc');

      // 我也尝试了 
      // request.property = 'properties/ + propertyId'
      // report = AnalyticsAdmin.Properties.runReport(request);

      Logger.log('We dont get here ' + report);
      
      // --------------------- 此处需要支持 ---------------------
      if (!report.rows) {
        Logger.log('No rows returned.');
        return;
      }
  } catch (e) {
    Logger.log(e)
    // TODO (Developer) - 处理异常
    Logger.log('Failed with error: %s', e.error);
  }
}

// 编辑:
在发布之前,我已运行了Google示例,但没有分享详细信息。运行代码时,我收到以下错误。我唯一更改的是Property Id。如您所见,在脚本中我添加了“AnalyticsData”API命名空间。

Execution log
1:29:32 PM	Notice	Execution started
1:29:33 PM	Info	Failed with error: undefined
1:29:32 PM	Notice	Execution completed

GA4 到 Google Sheets 通过 Google Apps Script – 无法找到适当的请求端点。

英文:

TL;DR

How to run report on GA4 property in GAS? Do I use AnalyticsData namespace or Analytics? or am I doing something wrong with properties?!

      report = AnalyticsAdmin.Properties.runReport(request,
'properties/' + 'zxc');
Logger.log('We dont get here ' + report);

I've seen this oldish question (similar to this question) but can't seem to use that:
GA4 到 Google Sheets 通过 Google Apps Script – 无法找到适当的请求端点。

Objective

The script is designed to automate the process of retrieving visitor count data from Google Analytics on a weekly basis and updating a Google Sheet with the results. The main steps include:

  1. Identifying the Google Analytics Account and Property: The script finds the relevant Google Analytics account and property (specifically the 'new' GA4 properties) by matching the account name and id from a Google Sheet.
  2. Listing Web Data Streams: It lists all web data streams (equivalent to views in Universal Analytics) for the identified property.
  3. Running a Report: The script attempts to run a report to retrieve the total visitor count (sessions) for a specified date range, typically the past week.
  4. Updating Google Sheet: The report results are intended to be added to the working sheet in a new column with the date as the header. The total visitors for the week are summed up at the bottom of the rows.

Challenges

The main challenges faced in the script include:

  • Transitioning from the older Google Analytics API to the new Google Analytics Admin API and Data API.
  • Generating the request for the Google Analytics API Executing the report request via Google
  • Analytics API Debugging issues related to permissions and API method
    calls.

Status

The script is in the development phase, and the current focus is on resolving the error encountered while running the report to retrieve the visitor count data.

The final implementation will enable automated, weekly updates to the Google Sheet with visitor count data from the selected Google Analytics property, streamlining the reporting process for the organization.

Note: When running this request inthe GA Query Explorer I get a valid Json response:

{
"metricHeaders":[
{
"name":"sessions"
"type":"TYPE_INTEGER"
}
]
"rows":[
{
"metricValues":[...]
}
]
"rowCount":1
"metadata":{
"currencyCode":"ZZZ"
"timeZone":"XX/YY"
}
"kind":"analyticsData#runReport"
}
function getReportDataForProperty(view, property) {
  Logger.log(view);
  Logger.log(property);

  // Extract the property ID from the property object
  const matchedViewId = view.name.split('/')[3];
  const matchedPropertyId = property.name.split('/')[1];

  Logger.log(matchedViewId);
  Logger.log(matchedPropertyId);

  try {
      const metrics =  [
        { "name": "sessions" }
        //See avaiable metrics https://developers.google.com/analytics/devguides/reporting/data/v1/api-schema?hl=en#metrics
        ]
      const dateRange = AnalyticsData.newDateRange();
      dateRange.startDate = getLastNdays(7);
      dateRange.endDate = 'today';

      const request = AnalyticsReporting.newReportRequest();
      request.metrics = metrics;
      request.dateRanges = dateRange;
      //request.property = "properties/zxc";

      Logger.log(request);

      // --------------------- SUPPORT NEEDED HERE ---------------------

      report = AnalyticsAdmin.Properties.runReport(request,
        'properties/' + 'zxc');

      // I also tried report = AnalyticsData.Properties.runReport(request,
        'properties/' + 'zxc');

      // I also tried 
      // request.property = 'properties/ + propertyId'
      // report = AnalyticsAdmin.Properties.runReport(request);

      Logger.log('We dont get here ' + report);
      
      // --------------------- SUPPORT NEEDED HERE ---------------------
      if (!report.rows) {
        Logger.log('No rows returned.');
        return;
      }
  } catch (e) {
    Logger.log(e)
    // TODO (Developer) - Handle exception
    Logger.log('Failed with error: %s', e.error);
  }
}

// EDIT:
I've had run the Google example before posting, but not shared details about this. I'm receiving the following error when running the code. The only thing I changed was the Property Id. As you can see in the 6 I have added the "AnalyticsData" API namespace to the script.

Execution log
1:29:32 PM	Notice	Execution started
1:29:33 PM	Info	Failed with error: undefined
1:29:32 PM	Notice	Execution completed

GA4 到 Google Sheets 通过 Google Apps Script – 无法找到适当的请求端点。

答案1

得分: 1

首先,我将开始移除所有其他服务。您有数据、管理和报告功能。

然后只需启用数据 API。

您需要确保已启用该服务。

确保分析数据已列出。

代码

/**
 * 运行 Google Analytics 4 属性 ID 的报告。创建包含报告的工作表。
 */
function runReport() {
  /**
   * TODO(开发人员):在运行示例之前取消注释此变量并替换为您的
   * Google Analytics 4 属性 ID。
   */
  const propertyId = '250796939';  
  
  try {
    const metric = AnalyticsData.newMetric();    
    metric.name = 'activeUsers';

    const dimension = AnalyticsData.newDimension();
    dimension.name = 'city';

    const dateRange = AnalyticsData.newDateRange();
    dateRange.startDate = '2020-03-31';
    dateRange.endDate = 'today';

    const request = AnalyticsData.newRunReportRequest();
    request.dimensions = [dimension];
    request.metrics = [metric];
    request.dateRanges = dateRange;

    const report = AnalyticsData.Properties.runReport(request,
        'properties/' + propertyId);
    if (!report.rows) {
      console.log('No rows returned.');
      return;
    }


  } catch (e) {
    // TODO(开发人员)- 处理异常
    console.log('Failed with error: %s', e.error);
  }
}

GA4 到 Google Sheets 通过 Google Apps Script – 无法找到适当的请求端点。

GA4 到 Google Sheets 通过 Google Apps Script – 无法找到适当的请求端点。


<details>
<summary>英文:</summary>
First I would start with removing all of those other serives. you have data, admin and reporting included.  
Then just enable data api.
You need to make sure that you have enabled the service
[![enter image description here][1]][1]
Make sure the analytics data is listed.
[![enter image description here][2]][2]
# code
/**
* Runs a report of a Google Analytics 4 property ID. Creates a sheet with the
* report.
*/
function runReport() {
/**
* TODO(developer): Uncomment this variable and replace with your
*   Google Analytics 4 property ID before running the sample.
*/
const propertyId = &#39;250796939&#39;;  
try {
const metric = AnalyticsData.newMetric();    
metric.name = &#39;activeUsers&#39;;
const dimension = AnalyticsData.newDimension();
dimension.name = &#39;city&#39;;
const dateRange = AnalyticsData.newDateRange();
dateRange.startDate = &#39;2020-03-31&#39;;
dateRange.endDate = &#39;today&#39;;
const request = AnalyticsData.newRunReportRequest();
request.dimensions = [dimension];
request.metrics = [metric];
request.dateRanges = dateRange;
const report = AnalyticsData.Properties.runReport(request,
&#39;properties/&#39; + propertyId);
if (!report.rows) {
console.log(&#39;No rows returned.&#39;);
return;
}
} catch (e) {
// TODO (Developer) - Handle exception
console.log(&#39;Failed with error: %s&#39;, e.error);
}
}
[1]: https://i.stack.imgur.com/BLwQH.png
[2]: https://i.stack.imgur.com/AuQ68.png
</details>

huangapple
  • 本文由 发表于 2023年8月10日 17:28:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76874393.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定