javascript - 请求报告 apiv4 以进行 Google 分析

标签 javascript google-apps-script google-analytics-api

今天,我尝试使用报告 API v4 发出请求,以从 Google Analytics 获取数据。我编写了 Google 应用脚本以在 Google 电子表格中显示数据。

这是我的功能:

function get_ga(){
  var now = new Date();
  var doc = SpreadsheetApp.getActiveSpreadsheet();       
  var site = doc.getSheetByName("Dashboard").getRange(2,1).getValue();
  var sheet = doc.getSheetByName("Google analytics");
  var service = getService(); 
  if (sheet==null){
    sheet = doc.insertSheet("Google analytics"); 
  }
  start_date=getstart(now);
  end_date=getend(now);

  if (service.hasAccess()) {

    var apiURL = 'https://analyticsreporting.googleapis.com/v4/reports:batchGet';

    var headers = {"Authorization": "Bearer " + getService().getAccessToken()};

    var request = {
      "reportRequests":
      [
        {
          "viewId": VIEW_ID,
          "dateRanges": [{"startDate": start_date, "endDate": end_date}],
          "metrics": [{"expression": "ga:users"}]
        }
      ]
    }




    var options = {
      "headers" : headers,
      "contentType":'application/json',
      "method" : "post",
      "payload" : JSON.stringify(request),               
      "muteHttpExceptions": true
    };

    try {
      var response = UrlFetchApp.fetch(apiURL, options);
    } 
    catch (e) {
      Logger.log(e);
    }
    Logger.log(response)

    var result = JSON.parse(response.getContentText());        
    console.log(result);

    if (result.error){
      return null;
    }


  }

  else {
    var authorizationUrl = service.getAuthorizationUrl();
    Logger.log('Open the following URL and re-run the script: %s', authorizationUrl);
    return 0;

  }

}

当然,我有一个 OAuth2.0.gs 文件:

function getService() {
  // Create a new service with the given name. The name will be used when
  // persisting the authorized token, so ensure it is unique within the
  // scope of the property store.
  return OAuth2.createService('searchconsole')

      // Set the endpoint URLs, which are the same for all Google services.
      .setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth')
      .setTokenUrl('https://accounts.google.com/o/oauth2/token')


      // Set the client ID and secret, from the Google Developers Console.
      .setClientId(CLIENT_ID)
      .setClientSecret(CLIENT_SECRET)

      // Set the name of the callback function in the script referenced
      // above that should be invoked to complete the OAuth flow.
      .setCallbackFunction('authCallback')

      // Set the property store where authorized tokens should be persisted.
      .setPropertyStore(PropertiesService.getUserProperties())

      // Set the scopes to request (space-separated for Google services).
      // this is Search Console read only scope for write access is:
      // https://www.googleapis.com/auth/webmasters
      .setScope('https://www.googleapis.com/auth/webmasters')

      // Below are Google-specific OAuth2 parameters.

      // Sets the login hint, which will prevent the account chooser screen
      // from being shown to users logged in with multiple accounts.
      .setParam('login_hint', Session.getActiveUser().getEmail())

      // Requests offline access.
      .setParam('access_type', 'offline')

      // Forces the approval prompt every time. This is useful for testing,
      // but not desirable in a production application.
      .setParam('approval_prompt', 'force');
}


function authCallback(request) {
  var searchConsoleService = getService();
  var isAuthorized = searchConsoleService.handleCallback(request);
  if (isAuthorized) {
    return HtmlService.createHtmlOutput('Success! You can close this tab.');
  } else {
    return HtmlService.createHtmlOutput('Denied. You can close this tab');
  }
}

最后我有一个variables.gs文件,其中包含我的不同ID和来自Google Analytics的VIEW ID,对应于我想要从中获取数据的网站。重要的是我在谷歌分析中看到数据,但我不是该网站的所有者;

    //GSC
var CLIENT_ID = '*******************************************';
var CLIENT_SECRET = '*****************';

//GA
var CLIENT_ID2 = '************************************';
var CLIENT_SECRET2 = '**************';
var VIEW_ID = '********';

启用了 Google 搜索控制台和 Google Analytics API。 我的所有功能都可以与 Google 搜索控制台完美配合。

错误是:{"error":{"status":"PERMISSION_DENIED","code":403,"message":"请求的身份验证范围不足。"}} 我注意到的第一件奇怪的事情是,我使用 Google 搜索控制台中的客户端 ID 和客户端密码来进行 google 分析的身份验证(请参阅我的 OAuth2.0.gs 文件),但它似乎有效;否则我会收到 401 错误。

最佳答案

当从 google apps 脚本使用 Google API 时,您将需要使用 Advanced Google Services对于 Analytics Service 。请务必Enable the service在你的脚本中。

启用后,新方法的脚本编辑器中的自动完成功能将可用。输入 AnalyticsReporting. 来查看它。

对于Analytics Reporting batchGet该方法将是AnalyticsReporting.Reports.batchGet(resource)

使用示例:

function get_ga(){
  var now = new Date();
  var start_date=getstart(now);
  var end_date=getend(now);

  var request = {
    "reportRequests":
    [
      {
        "viewId": VIEW_ID,
        "dateRanges": [{"startDate": start_date, "endDate": end_date}],
        "metrics": [{"expression": "ga:users"}]
      }
    ]
  }

  var response = AnalyticsReporting.Reports.batchGet(JSON.stringify(request));

  Logger.log(response)
}

[注意:我使用您的请求对象并假设它是正确的,因为我个人不使用分析,也没有测试代码。然而,Advanced Google Services所有在谷歌应用程序脚本中的工作方式都是相同的。基本上,只需将 Google Analytics Reporting API 中的 JSON 表示对象拼凑在一起即可。并将其用作所需的 API 高级服务方法中的参数。]

关于javascript - 请求报告 apiv4 以进行 Google 分析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45711811/

相关文章:

google-analytics - 如何使用 Google Analytics Mobile SDK 衡量留存率

google-analytics - 分析 API/查询资源管理器和界面之间的巨大差异

php - 使用javascript获取服务器信息

javascript - 立即设置TimeOut

google-apps-script - 如何获取 Google Team Drive 的管理者/贡献者/等?

javascript - 是否可以在 getRange() 中使用单元格引用作为行/列位置?

google-analytics - 谷歌分析核心报告 API;或使用自定义维度过滤

javascript - 如何从 CONNECT 平台内部编程调用中获取输出?

javascript - 将按钮注入(inject)站点(Chrome 扩展内容脚本)

javascript - 访问 for 循环的索引产生 'undefined' 结果