Google Analytics(分析)数据服务

借助 Google Analytics Data 服务,您可以在 Apps 脚本中使用 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);
  }
}