2017-08-16 236 views
1

今天我试着做一个请求与报告的API V4从谷歌分析数据。我在谷歌应用程序脚本中写入,以在Google电子表格中显示数据。要求报告apiv4谷歌分析

这里是我的功能:

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和我的观点一个variables.gs文件来自谷歌分析的ID,对应于我想要的数据来自的网站。重要的是,我看到谷歌分析数据,但我不是网站的所有者;

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

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

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

错误是:{“error”:{“status”:“PERMISSION_DENIED”,“code”:403,“message”:“请求的认证范围不足”}} 我注意到的第一件事是我使用Google搜索控制台的客户端ID和客户端密钥来验证Google Analytics(请参阅我的OAuth2.0.gs文件),但它似乎有效;否则我会得到一个401错误。

回答

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

[注意:使用你的请求对象,并假设它是正确的,因为我不亲自使用分析 Im和尚未测试代码。但是,Advanced Google Services在谷歌应用程序脚本中的工作方式都一样。基本上,只需拼凑起Google Analytics Reporting API中的JSON表示对象,并将其用作所需API高级服务方法中的参数。]

+0

与初学者一样,我在API API控制台中启用了API,而不是在对话框中启用。你的功能很完美,谢谢你,你实际上拯救了我的生命。 – JeanSec

+0

@JeanSec您应该将此标记为已勾选勾选的答案 – noogui