繁体   English   中英

使用Javascript和API访问Google Analytics(分析)数据时出现问题

[英]Issue with accessing Google Analytics data with Javascript and API

我想从Google Analytics(分析)中获取访问我们网站的访问者(用户)数量,最好是使用Javascript。

我已经在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>

您的代码有效,因此,我认为您使用的client_id和view_id错误,您尚未启用Google Analytics(分析)Reporting API或API服务器未接受您的主机。

您得到什么错误信息? 您的错误报告功能不会报告对我有用的任何东西,因此我建议更改:

alert(console.error.toString())

至:

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

请发布完整的错误消息以获取更多帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM