gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 04:17:20 25 4
gpt4 key购买 nike

今天,我尝试使用报告 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com