请求报告谷歌分析的apiv4

时间:2017-08-16 11:02:51

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

今天我尝试使用报告API v4进行请求,以便从Google Analytics中获取数据。我在谷歌应用程序脚本中写道,以在谷歌电子表格中显示数据。

这是我的功能:

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

最后我有一个带有我的不同ID和我的谷歌分析的VIEW ID的variables.gs文件,对应于我想要数据的网站。重要的是我在谷歌分析中看到数据,但我不是网站的所有者;

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

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

启用了谷歌搜索控制台和谷歌分析API。 我的所有功能都与谷歌搜索控制台完美配合。

错误是:{"错误":{"状态":" PERMISSION_DENIED","代码":403,&#34 ;消息":"请求的认证范围不足。"}} 我注意到的第一件奇怪的事情是我使用谷歌搜索控制台的客户端ID和客户端密码来进行谷歌分析的验证(参见我的OAuth2.0.gs文件),但它似乎有效;否则我会收到401错误。

1 个答案:

答案 0 :(得分:0)

使用谷歌应用程序脚本中的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 Apps脚本中的工作方式相同。基本上,只需将Google Analytics Reporting API中的JSON表示对象拼凑在一起,并将其用作所需API高级服务方法中的参数。]