【发布时间】:2020-10-16 19:35:50
【问题描述】:
我使用以下 API 代码从 Google 分析中获取数据。 但现在我需要拆分它,因为我需要获得用户授权,然后每小时从不同的服务器创建一个 cron 作业(无需请求其他权限)以获取 GA 数据。
应该做哪些改变?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="google-signin-client_id" content="<REPLACE_WITH_CLIENT_ID>">
<meta name="google-signin-scope" content="https://www.googleapis.com/auth/analytics.readonly">
</head>
<body>
<!-- The Sign-in button. This will run `queryReports()` on success. -->
<p class="g-signin2" data-onsuccess="queryReports"></p>
<script>
// Replace with your view ID.
var VIEW_ID = 'ga:104831427';
// Query the API and print the results to the page.
function queryReports() {
gapi.client.request({
path: '/v4/reports:batchGet',
root: 'https://analyticsreporting.googleapis.com/',
method: 'POST',
body: {
reportRequests: [
{
viewId: VIEW_ID,
dateRanges: [
{
startDate: '7daysAgo',
endDate: 'today'
}
],
"metrics": [
{
"expression": "ga:sessions"
}
],
"dimensions": [
{ "name": "ga:date" }
]
}
]
}
}).then(displayResults, console.error.bind(console));
}
function displayResults(response) {
var formattedJson = JSON.stringify(response.result, null, 2);
window.parent.postMessage({formattedJson:(formattedJson)}, "my-domain.com");
}
</script>
<!-- Load the JavaScript API client and Sign-in library. -->
<script src="https://apis.google.com/js/client:platform.js"></script>
</body>
</html>
【问题讨论】:
标签: google-api google-oauth google-analytics-api