[英]Using GS to Import data from GA4 runRealtimeReport into Google Sheets
在 Google AppsScript 上,我一直在嘗試將實時用戶數據從 GA4 屬性中提取到 Google 表格中。 但是,我不斷收到以下錯誤消息:“此 API 不支持 API 密鑰。預期的 OAuth2 訪問令牌或其他身份驗證憑據...”
下面是我的嘗試:
async function test4() {
var theAuthorization = "Bearer " + [[oAuthtoken]];
var theRequestBody = {"dimensions":[{"name":"country"}],"metrics":[{"name":"activeUsers"}],"limit":"10","orderBys":[{"metric":{"metricName":"activeUsers"},"desc":true}],"returnPropertyQuota":true,"minuteRanges":[{"name":"1minute","startMinutesAgo":2,"endMinutesAgo":0}]};
var theOptions = {method: 'POST',headers: {'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': theAuthorization}, body: theRequestBody};
const response = await UrlFetchApp.fetch("https://analyticsdata.googleapis.com/v1beta/properties/[GA4property]:runRealtimeReport?key=[[API key]]", theOptions);
Logger.log(JSON.parse(response));
}
我已經啟用了必要的 API 和范圍。
我已經在https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runRealtimeReport上測試了請求正文,它可以工作。
預先感謝您的意見。
我不確定您是如何提出[[oAuthtoken]]
的,但我想這不是有效的oAuthToken
。
為了得到它,你應該:
https://www.googleapis.com/auth/analytics.readonly
)。 例如,您可以將其設置為顯式 scope 。const oAuthtoken = ScriptApp.getOAuthToken();
)。另外,您是對的,API 密鑰不是必需的。 由於您提供了 OAuth 令牌,因此 API 密鑰完全是多余的。
調用此 API 的更簡單方法是使用Analytics Data Service :
AnalyticsData.Properties.runRealtimeReport(theRequestBody, yourProperty);
在這種情況下,Apps 腳本會為您處理授權,因此您不必擔心 OAuth 令牌。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.