Google Analytics(分析)数据服务

通过 Google Analytics 数据服务,您可以使用 Google Analytics Data API v1。 。此 API 可让 Google Analytics 用户以编程方式访问 Google Analytics 4 (GA4) 报告数据。

参考

有关此服务的详细信息,请参阅 Google Analytics Data API v1 参考文档

与 Apps 脚本中的所有高级服务一样,AnalyticsData 服务使用 对象、方法和参数与公共 API 相同。如需更多信息 请参阅如何确定方法签名

如需报告问题和寻求其他支持,请参阅 Google Analytics Data API v1 支持页面

示例代码

运行报告

该示例通过生成报告来按城市检索活跃用户数 并将结果存储在新电子表格中。

advanced/analyticsData.gs
/**
 * 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 = 'YOUR-GA4-PROPERTY-ID';

  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;
    }

    const spreadsheet = SpreadsheetApp.create('Google Analytics Report');
    const sheet = spreadsheet.getActiveSheet();

    // Append the headers.
    const dimensionHeaders = report.dimensionHeaders.map(
        (dimensionHeader) => {
          return dimensionHeader.name;
        });
    const metricHeaders = report.metricHeaders.map(
        (metricHeader) => {
          return metricHeader.name;
        });
    const headers = [...dimensionHeaders, ...metricHeaders];

    sheet.appendRow(headers);

    // Append the results.
    const rows = report.rows.map((row) => {
      const dimensionValues = row.dimensionValues.map(
          (dimensionValue) => {
            return dimensionValue.value;
          });
      const metricValues = row.metricValues.map(
          (metricValues) => {
            return metricValues.value;
          });
      return [...dimensionValues, ...metricValues];
    });

    sheet.getRange(2, 1, report.rows.length, headers.length)
        .setValues(rows);

    console.log('Report spreadsheet created: %s',
        spreadsheet.getUrl());
  } catch (e) {
    // TODO (Developer) - Handle exception
    console.log('Failed with error: %s', e.error);
  }
}