2017-03-17 119 views
2

我試圖從Google Analytics獲取訪問者(用戶)訪問我們網站的數量,最好是使用Javascript。使用JavaScript和API訪問Google Analytics數據的問題

我已經在Google上設置了一個項目和憑據,以便與我的僱主的Google Analytics一起工作,並且能夠獲得生成圖表以正常工作的javascript示例。

但是我需要的是指標的文本數據而不是生成的圖表,以便我可以將數據包含在我的僱主ASP.NET MVC C#Web應用程序中。

圖表示例與文本數據示例一樣,使用身份驗證按鈕,我可以在其中輸入我的僱主的Google Analytics(分析)的登錄名和密碼,這對圖表示例正確工作,並且似乎可以正確使用文本示例,但是文本示例在運行時不會生成數據。

我在這個URL上找到一個例子來從Google Analytics生成文本數據,但它只在我運行時產生錯誤。 https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/web-js

這是我使用的源代碼,在單個HTML文件中,如果出現錯誤請指出。

<!DOCTYPE html> 
<html> 
<head> 
<meta charset="utf-8"> 
<title>Hello Analytics Reporting API V4</title> 
<meta name="google-signin-client_id" content="xxxxxxx"> 
<meta name="google-signin-scope" content="https://www.googleapis.com/auth/analytics.readonly"> 
</head> 
<body> 

<h1>Hello Analytics Reporting API V4</h1> 

<p> 
    <!-- The Sign-in button. This will run `queryReports()` on success. --> 
    <div class="g-signin2" data-onsuccess="queryReports"></div> 
</p> 

<!-- The API response will be printed here. --> 
<textarea cols="80" rows="20" id="query-output"></textarea> 

<script> 
// Replace with your view ID. 
var VIEW_ID = '132296038'; 

// 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": "2017-02-01", 
      "endDate": "2017-03-16" 
      } 
     ], 
     "metrics": [ 
      { 
      "expression": "ga:sessions" 
      } 
     ], 
     "dimensions": [ 
      { "name": "ga:date" } 
     ] 
     } 
    ] 
    } 
    // }).then(displayResults, console.error.bind(console)); 
}).then(displayResults, alert(console.error.toString())); 
} 

function displayResults(response) { 
    var formattedJson = JSON.stringify(response.result, null, 2); 
    document.getElementById('query-output').value = formattedJson; 
} 
</script> 

<!-- Load the JavaScript API client and Sign-in library. --> 
<script src="https://apis.google.com/js/client:platform.js"></script> 

</body> 
</html> 

回答

0

你的代碼的工作,所以在我看來,你正在使用壞CLIENT_ID,view_id的,你有沒有啓用谷歌Analytics(分析)報告API或你的主機不被API服務器所接受。

你會得到什麼錯誤信息?你的錯誤報告功能不爲我報什麼可用的,所以我建議改變:

alert(console.error.toString()) 

到:

function (error) { alert(error.result.error.message); } 

請張貼完整的錯誤消息,以獲得更多幫助。

相關問題