在我的网站上显示谷歌分析数据?

时间:2021-11-14 15:21:42

I'm trying to figure out a way to display data collected from Google Analytics on my web site. I'm using NopCommerce, and I want to display this information/statistics in a view in the Admin Section.

我正在想办法在我的网站上显示从谷歌分析收集的数据。我正在使用NopCommerce,我想在管理部分的视图中显示这些信息/统计信息。

There might be many ways to achieve this, and after searching the web I found some examples using JavaScript, but I couldn't find a good tutorial for this.

可能有很多方法可以实现这一点,在搜索了web之后,我发现了一些使用JavaScript的例子,但是我找不到一个好的教程来说明这一点。

I have also looked into integrating Google Analytics with C#, and I found this example: http://biasecurities.com/2012/02/using-the-google-analytics-api-with-asp-net-mvc/#comment-1310 A demo project can be downloaded from GitHub here: https://github.com/jgeurts/Analytics-Example

我还研究了将谷歌分析与c#进行集成,我发现了这个例子:http://biasecurities.com/2012/02/usinggoogle -analytics-api- asp-net-mvc/# comm-1310一个演示项目可以从GitHub上下载:https://github.com/jgeurts/Analytics-Example。

However the demo project doesn't seem to work as the google URL (https://www.google.com/analytics/feeds/accounts/default) is no longer in use.

然而,这个演示项目似乎并没有发挥作用,因为谷歌的URL (https://www.google.com/analytics/feeds/accounts/default)已不再使用。

As I'm using a MVC application it would be preferable to make this happen by applying the Google Analytics logic within a Controller and displaying it in a view. Or something like that.

在使用MVC应用程序时,最好在控制器中应用谷歌分析逻辑并在视图中显示它。之类的。

Google provides a query tool to experiment with here, so it shouldn't be to hard extracting data from Google Analytics and display the data on the website: https://ga-dev-tools.appspot.com/explorer/

谷歌提供了一个可以在这里进行实验的查询工具,因此不应该很难从谷歌Analytics中提取数据并在网站上显示数据:https://ga-dev-tools.appspot.com/explorer/

Has anyone been able to successfully display Google Analytics data on their website?

是否有人能够成功地在他们的网站上显示谷歌分析数据?

5 个解决方案

#1


5  

In case some one else is having the same problem here's what I did and it pretty much answers the question.

如果其他人也有同样的问题这是我所做的它几乎回答了这个问题。

1.

1。

Here is the basic code for a API client that access data from Google Analytics via your Google Service Account. https://developers.google.com/api-client-library/dotnet/guide/aaa_oauth#service_account

下面是API客户端通过谷歌服务帐户从谷歌分析访问数据的基本代码。https://developers.google.com/api-client-library/dotnet/guide/aaa_oauth service_account

In order to make this application work you need to have several things ready before you start coding.

为了使这个应用程序工作,您需要在开始编写代码之前准备好一些东西。

*Google Analytics Account - once registered a "tracker" code is generated for you to put on each webpage you want to track. You may not see any statistics right away and it can take up to 24h before any statistics are shown in the Google Analytics Dashboard.

*谷歌分析帐户-一旦注册了“跟踪器”代码,你就可以把它放到你想要跟踪的每个网页上。您可能不会马上看到任何统计数据,在谷歌分析仪表板显示任何统计数据之前,可能需要长达24小时。

An OAuth Authorisation (API-Key) with CLIENT_ID, CLIENT SECRET and EMAIL ADRESS (This is not your normal email but a service account email that is created for you when you make an OAuth Authorisation). console.developers.google.com/

具有CLIENT_ID、客户机密和电子邮件地址的OAuth授权(这不是您的普通电子邮件,而是您在进行OAuth授权时为您创建的服务帐户电子邮件)。console.developers.google.com/

A serverkey, can also be created here: console.developers.google.com/. You can also create a browser key, haven't bothered with that though and don't know what it does.

还可以在这里创建一个serverkey: console.developers.google.com/。您还可以创建一个浏览器密钥,但您不必为此烦恼,也不知道它是做什么的。

Finally you need a certificate key. Your application will only be able to access your Google Analytics account by using the key and credentials. The key is an encrypted p.12 file. You can find the key in https://code.google.com/apis/console/.

最后,您需要一个证书密钥。您的应用程序只能使用密钥和凭据访问谷歌分析帐户。密钥是一个加密的p。12个文件。您可以在https://code.google.com/apis/console/中找到密钥。

Here is a guide for the key: http://www.pimcore.org/wiki/display/PIMCORE/Setup+Google+Analytics+Reporting+with+OAuth2+Service+Accounts+(since+1.4.6)

这里有一个关键的指南:http://www.pimcore.org/wiki/display/PIMCORE/Setup+谷歌+Analytics+ report +with+OAuth2+Service+ account +(因为+1.4.6)

2.

2。

Now that you have all keys and credentials you need it is time to start looking at the code I linked in "1". Here is the basic for it again: https://developers.google.com/api-client-library/dotnet/guide/aaa_oauth#service_account

现在您已经拥有了所有的键和凭证,现在是时候开始查看我在“1”中链接的代码了。这里是它的基础:https://developers.google.com/api-client-library/dotnet/guide/aaa_oauth#service_account

Create a console application and implement the code above.

创建一个控制台应用程序并实现上面的代码。

Note: your not making a "Google Plus service" so you have to change those parts for "AnalyticsService". Go to manage nuget and install packages:

注意:您没有做“谷歌+服务”,因此您必须为“AnalyticsService”更改这些部件。去管理nuget和安装包:

  • Google Apis Core Library
  • 谷歌api的核心库
  • Google Apis Client Library
  • 谷歌api客户端库
  • Google Apis Auth Client Library
  • 谷歌api Auth客户端库
  • Google Apis Analytics.v3 Library
  • 谷歌api的分析。v3图书馆
  • Google GData Client (This provides properties used to query data, metrics, demensions etc)
  • 谷歌GData客户端(提供用于查询数据、度量、需求等的属性)
  • Google GData Extensions Library
  • 谷歌GData扩展库
  • Analytics
  • 分析

Might forgot something but here are the namespaces I use:

可能会忘记一些东西,但以下是我使用的命名空间:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Security.Cryptography.X509Certificates;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Analytics.v3;

3

3

Finally, here's is some of my code. Note I'm creating a new Analytics as supposed to "new ServiceAccountCredentials" as in the code from Google. That's the main difference: Retrieve data from Google Analytics API with .NET, multiple metrics?

最后,这是我的一些代码。注意,我正在创建一个新的分析,就像在谷歌的代码中所假定的“新的ServiceAccountCredentials”。这就是主要的区别:从。net的谷歌分析API中检索数据,多指标?

With this I'm able to access and query data from Google Analytics account. The best part is that you don't have to log in to Google for this as the key and credentials gives you access to the account data directly.

有了它,我可以从谷歌分析帐户访问和查询数据。最好的部分是,您不必为此登录到谷歌,因为密钥和凭据使您可以直接访问帐户数据。

I will migrate this code to MVC now I might make an update later on for how to implement this Analytics client in Mvc.

我将把这段代码迁移到MVC,稍后我可能会对如何在MVC中实现这个分析客户端进行更新。

#2


4  

I'd recommend to use the new Google APIs Client Library for .NET (currently in beta). Information about the Analytics API can be found here. Note that the Client Library for .NET (google-api-dotnet-client) supersedes the .NET library for the Google Data API (google-gdata).

我建议为。net使用新的谷歌api客户端库(目前正在测试中)。有关分析API的信息可以在这里找到。注意,net (Google - API -dotnet- Client)的客户端库取代了用于谷歌数据API (Google -gdata)的. net库。

Unfortunately, there is no sample code available yet from Google (see this issue) but this question on SO should help.

不幸的是,谷歌中还没有可用的示例代码(请参阅本问题),但是这个关于SO的问题应该会有所帮助。

If you don't want to login every time you access Analytics data, you can use OAuth 2.0 authorization with offline access. You have to grant initial access to your web application, though. This requires you to login once but you can use a refresh token later on.

如果您不想在每次访问分析数据时都登录,那么可以使用OAuth 2.0授权进行脱机访问。不过,您必须授予对web应用程序的初始访问权。这需要您登录一次,但是您可以稍后使用一个refresh token。

#3


3  

This document explains how to get Google Access tokens and use them to get Google Analytics data to be displayed in our websites.

本文档解释了如何获取谷歌访问令牌,并使用它们将谷歌分析数据显示在我们的网站上。

Example: A live example is available in

示例:有一个活生生的示例

https://newtonjoshua.com

https://newtonjoshua.com

Note: Use the same Gmail account for all the below steps.

注意:在下面的步骤中使用相同的Gmail帐户。


STEP 1: Set Up Google Analytics

Follow the below steps to set up Google Analytics on your website

按照以下步骤在你的网站上建立谷歌分析

  1. Sign in to your Analytics account.
  2. 登录你的分析账户。
  3. Select the Admin tab.
  4. 选择Admin选项卡。
  5. Select an account from the drop-down menu in the ACCOUNT column.
  6. 从account列的下拉菜单中选择account。
  7. Select a property from the drop-down menu in the PROPERTY column.
  8. 从属性列的下拉菜单中选择一个属性。
  9. Under PROPERTY, click Tracking Info -> Tracking Code.
  10. 在属性下,单击“跟踪信息->跟踪代码”。
  11. To collect data, you must copy and paste the Analytics tracking code into the source code on every web page you wish to track.
  12. 要收集数据,您必须将分析跟踪代码复制并粘贴到您希望跟踪的每个web页面的源代码中。
  13. Once you have the JavaScript tracking code snippet for your property, copy the snippet exactly without editing it.
  14. 一旦有了属性的JavaScript跟踪代码片段,就完全复制该代码片段,而无需编辑它。
  15. Paste your tracking code snippet (unaltered, in its entirety) before the closing </head> tag on every web page on your site you wish to track.
  16. 在您希望跟踪的每个web页面上的关闭标记之前,粘贴跟踪代码片段(未做任何修改)。
  17. Once you have successfully installed Analytics tracking, it may take up to 24 hours for data such as traffic referral information, user characteristics, and browsing information to appear in your reports
  18. 一旦您成功地安装了分析跟踪,可能需要24小时才能在报表中显示流量推荐信息、用户特征和浏览信息等数据

Refer to:

请参考:

  1. https://support.google.com/analytics/answer/1008080?hl=en
  2. https://support.google.com/analytics/answer/1008080?hl=en
  3. https://analytics.google.com
  4. https://analytics.google.com

STEP 2: Get Tokens

Google Project:

谷歌计划:

To create a Google Cloud Platform project, open the Google Developers Console (https://console.developers.google.com) and click Create Project.

要创建谷歌云平台项目,请打开谷歌开发人员控制台(https://console.developers.google.com)并单击create project。

Enable OAuth 2.0 API access:

启用OAuth 2.0 API访问:

Your application will need to access user data and contact other Google services on your behalf. Use OAuth 2.0 to grant your app API access.

您的应用程序将需要访问用户数据并代表您联系其他谷歌服务。使用OAuth 2.0授权您的应用程序API访问。

To enable that, you need a client ID:

为此,您需要客户ID:

  1. Open the Google API Console Credentials page (https://console.developers.google.com/apis/credentials).
  2. 打开谷歌API控制台凭据页面(https://console.developers.google.com/apis/credentials)。
  3. From the project, drop-down and select your project.
  4. 从项目中,下拉并选择项目。
  5. Select Create credentials and choose OAuth client ID.
  6. 选择Create凭证并选择OAuth客户端ID。
  7. Under Application type, select Web application, enter a Name and
  8. 在“应用程序类型”下,选择“Web应用程序”,输入名称和
  9. set the Restrictions by entering JavaScript origins, Redirect URIs to point the website where you are planning to display the data, and then click Create.

    通过输入JavaScript源来设置限制,重定向uri以指向要显示数据的网站,然后单击Create。

  10. Make note of the OAuth 2.0 client_id and client_secret. You will need them to configure the UI.

    注意OAuth 2.0 client_id和client_secret。您将需要它们来配置UI。

Get Authorization code:

得到授权代码:

Enter in browser:

在浏览器输入:

https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/analytics.readonly&response_type=code&client_id={{ client_id}}&redirect_uri={{redirect_uri }} &approval_prompt=force&access_type=offline

https://accounts.google.com/o/oauth2/auth?scope=https:/ /www.googleapis.com/auth/analytics.readonly&response_type=code&client_id= { { client_id } } &redirect_uri = { { redirect_uri } } &approval_prompt = force&access_type =离线

You will get redirected to

你会被重定向到

{{redirect_uri }}?code=={{authorization_code}}#

{ { redirect_uri } } ? = = { { authorization_code } } #代码

Get Refresh Token:

得到刷新令牌:

Send a POST request, possibly via a REST console to

发送一个POST请求,可能通过REST控制台发送到

https://www.googleapis.com/oauth2/v3/token?code={{authorization_code}} &client_id={{client_id}}&client_secret={{client_secret}} &redirect_uri={{redirect_uri }}&grant_type=authorization_code

https://www.googleapis.com/oauth2/v3/token?代码= { { authorization_code } } client_id = { { client_id } } client_secret = { { client_secret } } &redirect_uri = { { redirect_uri } } &grant_type = authorization_code

You will get a JSON response with

您将得到JSON响应

{"refresh_token": refresh_token}

{“refresh_token”:refresh_token }

You can use the refresh token to get access token to access to Google APIs.

您可以使用refresh token获取访问令牌来访问谷歌api。

Get the Access Token:

获取访问令牌:

Send a POST request to,

https://www.googleapis.com/oauth2/v3/token?client_id={{client_id}} &client_secret={{client_id}} &grant_type=refresh_token&refresh_token={{refresh_token}}

https://www.googleapis.com/oauth2/v3/token?client_id = { { client_id } } client_secret = { { client_id } } &grant_type = refresh_token&refresh_token = { { refresh_token } }

You will get a JSON with access_token in the response.

在响应中,您将得到一个带有access_token的JSON。

{access_token: {{access_token}}}

{ access_token:{ { access_token } } }

Example:

例子:

var access_token = '';
function getAccessToken(){
    $.post('https://www.googleapis.com/oauth2/v3/token', {
            client_id: {{client_id}},
            client_secret: {{client_secret}},
            grant_type: 'refresh_token',
            refresh_token: {{refresh_token}}
        }, function (data, status) {
            if (status === 'success') {
                access_token = data.access_token;
                // Do something eith the access_token
            }
            else {
                console.error(status);
            }
        });
}

Check Token validity:

检查标记有效性:

Send a POST request to,

https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={{access_token}}

https://www.googleapis.com/oauth2/v1/tokeninfo?access_token= { { access_token } }

Example:

例子:

function checkValidity() {
    $.post('https://www.googleapis.com/oauth2/v1/tokeninfo', {
            access_token:{{access_token}}
        }).done(function (data, status) {
            if (status === 'success') {
                console.debug(data.expires_in);
                var check = false;
                check = data.hasOwnProperty('expires_in');
                if (check) {
                    // Token is valid
                }
                if (!check) {
                    getAccessToken();
                }
            }
            else {
                console.debug(status);
            }

        })
        .fail(function (data) {
            console.error(data);
            getAccessToken();
        });
}

Step 3: Fetch Data

Embed API:

嵌入API:

The GA Embed API is a JavaScript library that allows you to easily create and embed your GA dashboard on your website in a matter of minutes.

GA Embed API是一个JavaScript库,允许您在几分钟内在您的网站上创建和嵌入GA仪表板。

Refer to https://developers.google.com/analytics/devguides/reporting/embed/v1/getting-started.

参考https://developers.google.com/analytics/devguides/reporting/embed/v1/getting-started。

Query Explorer:

查询浏览器:

Visit Embed API Query Explorer and authorize

访问嵌入API查询资源管理器并授权

https://ga-dev-tools.appspot.com/query-explorer/

https://ga-dev-tools.appspot.com/query-explorer/

Select the view for which you want to fetch the data.

选择要获取数据的视图。

Select the required metrics and dimensions.

选择所需的度量和维度。

Example:

例子:

Get Country Data (I want to know the number of users accessing my website from each country).

获取国家数据(我想知道每个国家访问我网站的用户数量)。

To get that data, select the metrics as 'users' and the dimensions as 'country'.

要获取这些数据,请选择“用户”的度量标准和“国家”的维度。

Click on Run Query.

点击运行查询。

You will find the analytics data for the query displayed in a table.

您将找到表中显示的查询的分析数据。

Copy the API Query URI. And add access_token={{access_token}} to the URI.

复制API查询URI。并向URI添加access_token={access_token}。

Example:

例子:

https://www.googleapis.com/analytics/v3/data/ga?ids={{ids}}&start-date=2015-07-01&end-date=today&metrics=ga%3Ausers&dimensions=ga%3Acountry&access_token={{access_token}}

https://www.googleapis.com/analytics/v3/data/ga?ids= { { id } }要求上班日期= 2015 - 07 - 01,结束日期= today&metrics = ga % 3 ausers&dimensions = ga % 3 acountry&access_token = { { access_token } }

Send POST request to the URIs to get the data in your browser.

将POST请求发送到uri以在浏览器中获取数据。

Example:

例子:

function gaGetCountry() {
    $.get('https://www.googleapis.com/analytics/v3/data/ga?' +
        'ids={{ids}}' +
        'start-date=2015-07-01&' +
        'end-date=today&' +
        'metrics=ga%3Ausers&' +
        'dimensions=ga%3Acountry&' +
        'sort=ga%3Ausers&' +
        'filters=ga%3Ausers%3E10&' +
        'max-results=50' +
        '&access_token=' + {{access_token}},
        function (data, status) {
            if (status === 'success') {

                // Display the Data
                drawRegionsMap(data.rows);

            } else {
                console.debug(status);
            }

        });
}

Step 4: Display Data

Now we have gathered the data. Finally we have to display them on our website.

现在我们已经收集了数据。最后,我们必须在我们的网站上展示它们。

"Display live data on your site" is the title of Google Charts. And that is what we are going to do.

“在您的站点上显示实时数据”是谷歌图表的标题。这就是我们要做的。

Refer to https://developers.google.com/chart/.

参考https://developers.google.com/chart/。

The following example will draw a GeoChart in the div with id='countryChart'.

下面的示例将在div中绘制具有id='countryChart'的地理图。

// Draw country chart
function drawRegionsMap(data) {

    var head = data[0];
    head[0] = 'Country';
    head[1] = 'Users';
    for (var i = 1; i < data.length; i++) {
        var d = data[i];
        d[1] = Number(d[1]);
    }

    var chartData = google.visualization.arrayToDataTable(data);
    var options = {
        title: 'My Website is viewed from,',
        domain: '{{Country Code eg: IN for India}}',
        tooltip: {
            textStyle: {
                color: 'navy'
            },
            showColorCode: true
        },
        legend: {
            textStyle: {
                color: 'navy',
                fontSize: 12
            }
        },
        colorAxis: {
            colors: ['#00FFFF', '#0000FF']
        }
    };

    var chart = new google.visualization.GeoChart(document.getElementById('countryChart'));

    chart.draw(chartData, options);
}

Refer to https://newtonjoshua.com to view the above example in action.

参考https://newtonjoshua.com来查看上面的例子。

#4


1  

I spent a couple of days trawling the Internet to get some sample ASP.NET code with no luck. I used Koffe14's method for authentication, and also Linda Lawton's excellent ASP.NET analytics example.

我花了几天时间在网上搜罗一些ASP样本。网络代码运气不好。我使用了Koffe14的认证方法,以及Linda Lawton的优秀ASP。网络分析的例子。

I've posted the code on my website. It's not MVC, but it might help other people who need to get data from Google analytics into an ASP.NET web page using the v3 Google API.

我已经在我的网站上发布了代码。它不是MVC,但它可能帮助其他需要从谷歌分析获得数据的人成为ASP。NET web页面使用v3谷歌API。

#5


0  

Check out embeddedanalytics.com (disclaimer - I work with them).

查看embeddedanalytics.com(免责声明——我与他们合作)。

This is a simple yet powerful solution geared for people that don't want deal with learning the GA API and then having to link it to visualization (e.g. charts/graphs).

这是一个简单而强大的解决方案,适用于那些不想学习GA API,然后不得不将其与可视化(例如图表/图表)联系起来的人。

Basically define your charts and embed a snippet of code where you want the chart to show. We also support mechanisms so that it is easy to integrate into a custom built CMS or other web portal.

基本上定义您的图表,并在您希望图表显示的地方嵌入代码片段。我们还支持机制,以便很容易地集成到自定义构建的CMS或其他web门户中。

#1


5  

In case some one else is having the same problem here's what I did and it pretty much answers the question.

如果其他人也有同样的问题这是我所做的它几乎回答了这个问题。

1.

1。

Here is the basic code for a API client that access data from Google Analytics via your Google Service Account. https://developers.google.com/api-client-library/dotnet/guide/aaa_oauth#service_account

下面是API客户端通过谷歌服务帐户从谷歌分析访问数据的基本代码。https://developers.google.com/api-client-library/dotnet/guide/aaa_oauth service_account

In order to make this application work you need to have several things ready before you start coding.

为了使这个应用程序工作,您需要在开始编写代码之前准备好一些东西。

*Google Analytics Account - once registered a "tracker" code is generated for you to put on each webpage you want to track. You may not see any statistics right away and it can take up to 24h before any statistics are shown in the Google Analytics Dashboard.

*谷歌分析帐户-一旦注册了“跟踪器”代码,你就可以把它放到你想要跟踪的每个网页上。您可能不会马上看到任何统计数据,在谷歌分析仪表板显示任何统计数据之前,可能需要长达24小时。

An OAuth Authorisation (API-Key) with CLIENT_ID, CLIENT SECRET and EMAIL ADRESS (This is not your normal email but a service account email that is created for you when you make an OAuth Authorisation). console.developers.google.com/

具有CLIENT_ID、客户机密和电子邮件地址的OAuth授权(这不是您的普通电子邮件,而是您在进行OAuth授权时为您创建的服务帐户电子邮件)。console.developers.google.com/

A serverkey, can also be created here: console.developers.google.com/. You can also create a browser key, haven't bothered with that though and don't know what it does.

还可以在这里创建一个serverkey: console.developers.google.com/。您还可以创建一个浏览器密钥,但您不必为此烦恼,也不知道它是做什么的。

Finally you need a certificate key. Your application will only be able to access your Google Analytics account by using the key and credentials. The key is an encrypted p.12 file. You can find the key in https://code.google.com/apis/console/.

最后,您需要一个证书密钥。您的应用程序只能使用密钥和凭据访问谷歌分析帐户。密钥是一个加密的p。12个文件。您可以在https://code.google.com/apis/console/中找到密钥。

Here is a guide for the key: http://www.pimcore.org/wiki/display/PIMCORE/Setup+Google+Analytics+Reporting+with+OAuth2+Service+Accounts+(since+1.4.6)

这里有一个关键的指南:http://www.pimcore.org/wiki/display/PIMCORE/Setup+谷歌+Analytics+ report +with+OAuth2+Service+ account +(因为+1.4.6)

2.

2。

Now that you have all keys and credentials you need it is time to start looking at the code I linked in "1". Here is the basic for it again: https://developers.google.com/api-client-library/dotnet/guide/aaa_oauth#service_account

现在您已经拥有了所有的键和凭证,现在是时候开始查看我在“1”中链接的代码了。这里是它的基础:https://developers.google.com/api-client-library/dotnet/guide/aaa_oauth#service_account

Create a console application and implement the code above.

创建一个控制台应用程序并实现上面的代码。

Note: your not making a "Google Plus service" so you have to change those parts for "AnalyticsService". Go to manage nuget and install packages:

注意:您没有做“谷歌+服务”,因此您必须为“AnalyticsService”更改这些部件。去管理nuget和安装包:

  • Google Apis Core Library
  • 谷歌api的核心库
  • Google Apis Client Library
  • 谷歌api客户端库
  • Google Apis Auth Client Library
  • 谷歌api Auth客户端库
  • Google Apis Analytics.v3 Library
  • 谷歌api的分析。v3图书馆
  • Google GData Client (This provides properties used to query data, metrics, demensions etc)
  • 谷歌GData客户端(提供用于查询数据、度量、需求等的属性)
  • Google GData Extensions Library
  • 谷歌GData扩展库
  • Analytics
  • 分析

Might forgot something but here are the namespaces I use:

可能会忘记一些东西,但以下是我使用的命名空间:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Security.Cryptography.X509Certificates;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Analytics.v3;

3

3

Finally, here's is some of my code. Note I'm creating a new Analytics as supposed to "new ServiceAccountCredentials" as in the code from Google. That's the main difference: Retrieve data from Google Analytics API with .NET, multiple metrics?

最后,这是我的一些代码。注意,我正在创建一个新的分析,就像在谷歌的代码中所假定的“新的ServiceAccountCredentials”。这就是主要的区别:从。net的谷歌分析API中检索数据,多指标?

With this I'm able to access and query data from Google Analytics account. The best part is that you don't have to log in to Google for this as the key and credentials gives you access to the account data directly.

有了它,我可以从谷歌分析帐户访问和查询数据。最好的部分是,您不必为此登录到谷歌,因为密钥和凭据使您可以直接访问帐户数据。

I will migrate this code to MVC now I might make an update later on for how to implement this Analytics client in Mvc.

我将把这段代码迁移到MVC,稍后我可能会对如何在MVC中实现这个分析客户端进行更新。

#2


4  

I'd recommend to use the new Google APIs Client Library for .NET (currently in beta). Information about the Analytics API can be found here. Note that the Client Library for .NET (google-api-dotnet-client) supersedes the .NET library for the Google Data API (google-gdata).

我建议为。net使用新的谷歌api客户端库(目前正在测试中)。有关分析API的信息可以在这里找到。注意,net (Google - API -dotnet- Client)的客户端库取代了用于谷歌数据API (Google -gdata)的. net库。

Unfortunately, there is no sample code available yet from Google (see this issue) but this question on SO should help.

不幸的是,谷歌中还没有可用的示例代码(请参阅本问题),但是这个关于SO的问题应该会有所帮助。

If you don't want to login every time you access Analytics data, you can use OAuth 2.0 authorization with offline access. You have to grant initial access to your web application, though. This requires you to login once but you can use a refresh token later on.

如果您不想在每次访问分析数据时都登录,那么可以使用OAuth 2.0授权进行脱机访问。不过,您必须授予对web应用程序的初始访问权。这需要您登录一次,但是您可以稍后使用一个refresh token。

#3


3  

This document explains how to get Google Access tokens and use them to get Google Analytics data to be displayed in our websites.

本文档解释了如何获取谷歌访问令牌,并使用它们将谷歌分析数据显示在我们的网站上。

Example: A live example is available in

示例:有一个活生生的示例

https://newtonjoshua.com

https://newtonjoshua.com

Note: Use the same Gmail account for all the below steps.

注意:在下面的步骤中使用相同的Gmail帐户。


STEP 1: Set Up Google Analytics

Follow the below steps to set up Google Analytics on your website

按照以下步骤在你的网站上建立谷歌分析

  1. Sign in to your Analytics account.
  2. 登录你的分析账户。
  3. Select the Admin tab.
  4. 选择Admin选项卡。
  5. Select an account from the drop-down menu in the ACCOUNT column.
  6. 从account列的下拉菜单中选择account。
  7. Select a property from the drop-down menu in the PROPERTY column.
  8. 从属性列的下拉菜单中选择一个属性。
  9. Under PROPERTY, click Tracking Info -> Tracking Code.
  10. 在属性下,单击“跟踪信息->跟踪代码”。
  11. To collect data, you must copy and paste the Analytics tracking code into the source code on every web page you wish to track.
  12. 要收集数据,您必须将分析跟踪代码复制并粘贴到您希望跟踪的每个web页面的源代码中。
  13. Once you have the JavaScript tracking code snippet for your property, copy the snippet exactly without editing it.
  14. 一旦有了属性的JavaScript跟踪代码片段,就完全复制该代码片段,而无需编辑它。
  15. Paste your tracking code snippet (unaltered, in its entirety) before the closing </head> tag on every web page on your site you wish to track.
  16. 在您希望跟踪的每个web页面上的关闭标记之前,粘贴跟踪代码片段(未做任何修改)。
  17. Once you have successfully installed Analytics tracking, it may take up to 24 hours for data such as traffic referral information, user characteristics, and browsing information to appear in your reports
  18. 一旦您成功地安装了分析跟踪,可能需要24小时才能在报表中显示流量推荐信息、用户特征和浏览信息等数据

Refer to:

请参考:

  1. https://support.google.com/analytics/answer/1008080?hl=en
  2. https://support.google.com/analytics/answer/1008080?hl=en
  3. https://analytics.google.com
  4. https://analytics.google.com

STEP 2: Get Tokens

Google Project:

谷歌计划:

To create a Google Cloud Platform project, open the Google Developers Console (https://console.developers.google.com) and click Create Project.

要创建谷歌云平台项目,请打开谷歌开发人员控制台(https://console.developers.google.com)并单击create project。

Enable OAuth 2.0 API access:

启用OAuth 2.0 API访问:

Your application will need to access user data and contact other Google services on your behalf. Use OAuth 2.0 to grant your app API access.

您的应用程序将需要访问用户数据并代表您联系其他谷歌服务。使用OAuth 2.0授权您的应用程序API访问。

To enable that, you need a client ID:

为此,您需要客户ID:

  1. Open the Google API Console Credentials page (https://console.developers.google.com/apis/credentials).
  2. 打开谷歌API控制台凭据页面(https://console.developers.google.com/apis/credentials)。
  3. From the project, drop-down and select your project.
  4. 从项目中,下拉并选择项目。
  5. Select Create credentials and choose OAuth client ID.
  6. 选择Create凭证并选择OAuth客户端ID。
  7. Under Application type, select Web application, enter a Name and
  8. 在“应用程序类型”下,选择“Web应用程序”,输入名称和
  9. set the Restrictions by entering JavaScript origins, Redirect URIs to point the website where you are planning to display the data, and then click Create.

    通过输入JavaScript源来设置限制,重定向uri以指向要显示数据的网站,然后单击Create。

  10. Make note of the OAuth 2.0 client_id and client_secret. You will need them to configure the UI.

    注意OAuth 2.0 client_id和client_secret。您将需要它们来配置UI。

Get Authorization code:

得到授权代码:

Enter in browser:

在浏览器输入:

https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/analytics.readonly&response_type=code&client_id={{ client_id}}&redirect_uri={{redirect_uri }} &approval_prompt=force&access_type=offline

https://accounts.google.com/o/oauth2/auth?scope=https:/ /www.googleapis.com/auth/analytics.readonly&response_type=code&client_id= { { client_id } } &redirect_uri = { { redirect_uri } } &approval_prompt = force&access_type =离线

You will get redirected to

你会被重定向到

{{redirect_uri }}?code=={{authorization_code}}#

{ { redirect_uri } } ? = = { { authorization_code } } #代码

Get Refresh Token:

得到刷新令牌:

Send a POST request, possibly via a REST console to

发送一个POST请求,可能通过REST控制台发送到

https://www.googleapis.com/oauth2/v3/token?code={{authorization_code}} &client_id={{client_id}}&client_secret={{client_secret}} &redirect_uri={{redirect_uri }}&grant_type=authorization_code

https://www.googleapis.com/oauth2/v3/token?代码= { { authorization_code } } client_id = { { client_id } } client_secret = { { client_secret } } &redirect_uri = { { redirect_uri } } &grant_type = authorization_code

You will get a JSON response with

您将得到JSON响应

{"refresh_token": refresh_token}

{“refresh_token”:refresh_token }

You can use the refresh token to get access token to access to Google APIs.

您可以使用refresh token获取访问令牌来访问谷歌api。

Get the Access Token:

获取访问令牌:

Send a POST request to,

https://www.googleapis.com/oauth2/v3/token?client_id={{client_id}} &client_secret={{client_id}} &grant_type=refresh_token&refresh_token={{refresh_token}}

https://www.googleapis.com/oauth2/v3/token?client_id = { { client_id } } client_secret = { { client_id } } &grant_type = refresh_token&refresh_token = { { refresh_token } }

You will get a JSON with access_token in the response.

在响应中,您将得到一个带有access_token的JSON。

{access_token: {{access_token}}}

{ access_token:{ { access_token } } }

Example:

例子:

var access_token = '';
function getAccessToken(){
    $.post('https://www.googleapis.com/oauth2/v3/token', {
            client_id: {{client_id}},
            client_secret: {{client_secret}},
            grant_type: 'refresh_token',
            refresh_token: {{refresh_token}}
        }, function (data, status) {
            if (status === 'success') {
                access_token = data.access_token;
                // Do something eith the access_token
            }
            else {
                console.error(status);
            }
        });
}

Check Token validity:

检查标记有效性:

Send a POST request to,

https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={{access_token}}

https://www.googleapis.com/oauth2/v1/tokeninfo?access_token= { { access_token } }

Example:

例子:

function checkValidity() {
    $.post('https://www.googleapis.com/oauth2/v1/tokeninfo', {
            access_token:{{access_token}}
        }).done(function (data, status) {
            if (status === 'success') {
                console.debug(data.expires_in);
                var check = false;
                check = data.hasOwnProperty('expires_in');
                if (check) {
                    // Token is valid
                }
                if (!check) {
                    getAccessToken();
                }
            }
            else {
                console.debug(status);
            }

        })
        .fail(function (data) {
            console.error(data);
            getAccessToken();
        });
}

Step 3: Fetch Data

Embed API:

嵌入API:

The GA Embed API is a JavaScript library that allows you to easily create and embed your GA dashboard on your website in a matter of minutes.

GA Embed API是一个JavaScript库,允许您在几分钟内在您的网站上创建和嵌入GA仪表板。

Refer to https://developers.google.com/analytics/devguides/reporting/embed/v1/getting-started.

参考https://developers.google.com/analytics/devguides/reporting/embed/v1/getting-started。

Query Explorer:

查询浏览器:

Visit Embed API Query Explorer and authorize

访问嵌入API查询资源管理器并授权

https://ga-dev-tools.appspot.com/query-explorer/

https://ga-dev-tools.appspot.com/query-explorer/

Select the view for which you want to fetch the data.

选择要获取数据的视图。

Select the required metrics and dimensions.

选择所需的度量和维度。

Example:

例子:

Get Country Data (I want to know the number of users accessing my website from each country).

获取国家数据(我想知道每个国家访问我网站的用户数量)。

To get that data, select the metrics as 'users' and the dimensions as 'country'.

要获取这些数据,请选择“用户”的度量标准和“国家”的维度。

Click on Run Query.

点击运行查询。

You will find the analytics data for the query displayed in a table.

您将找到表中显示的查询的分析数据。

Copy the API Query URI. And add access_token={{access_token}} to the URI.

复制API查询URI。并向URI添加access_token={access_token}。

Example:

例子:

https://www.googleapis.com/analytics/v3/data/ga?ids={{ids}}&start-date=2015-07-01&end-date=today&metrics=ga%3Ausers&dimensions=ga%3Acountry&access_token={{access_token}}

https://www.googleapis.com/analytics/v3/data/ga?ids= { { id } }要求上班日期= 2015 - 07 - 01,结束日期= today&metrics = ga % 3 ausers&dimensions = ga % 3 acountry&access_token = { { access_token } }

Send POST request to the URIs to get the data in your browser.

将POST请求发送到uri以在浏览器中获取数据。

Example:

例子:

function gaGetCountry() {
    $.get('https://www.googleapis.com/analytics/v3/data/ga?' +
        'ids={{ids}}' +
        'start-date=2015-07-01&' +
        'end-date=today&' +
        'metrics=ga%3Ausers&' +
        'dimensions=ga%3Acountry&' +
        'sort=ga%3Ausers&' +
        'filters=ga%3Ausers%3E10&' +
        'max-results=50' +
        '&access_token=' + {{access_token}},
        function (data, status) {
            if (status === 'success') {

                // Display the Data
                drawRegionsMap(data.rows);

            } else {
                console.debug(status);
            }

        });
}

Step 4: Display Data

Now we have gathered the data. Finally we have to display them on our website.

现在我们已经收集了数据。最后,我们必须在我们的网站上展示它们。

"Display live data on your site" is the title of Google Charts. And that is what we are going to do.

“在您的站点上显示实时数据”是谷歌图表的标题。这就是我们要做的。

Refer to https://developers.google.com/chart/.

参考https://developers.google.com/chart/。

The following example will draw a GeoChart in the div with id='countryChart'.

下面的示例将在div中绘制具有id='countryChart'的地理图。

// Draw country chart
function drawRegionsMap(data) {

    var head = data[0];
    head[0] = 'Country';
    head[1] = 'Users';
    for (var i = 1; i < data.length; i++) {
        var d = data[i];
        d[1] = Number(d[1]);
    }

    var chartData = google.visualization.arrayToDataTable(data);
    var options = {
        title: 'My Website is viewed from,',
        domain: '{{Country Code eg: IN for India}}',
        tooltip: {
            textStyle: {
                color: 'navy'
            },
            showColorCode: true
        },
        legend: {
            textStyle: {
                color: 'navy',
                fontSize: 12
            }
        },
        colorAxis: {
            colors: ['#00FFFF', '#0000FF']
        }
    };

    var chart = new google.visualization.GeoChart(document.getElementById('countryChart'));

    chart.draw(chartData, options);
}

Refer to https://newtonjoshua.com to view the above example in action.

参考https://newtonjoshua.com来查看上面的例子。

#4


1  

I spent a couple of days trawling the Internet to get some sample ASP.NET code with no luck. I used Koffe14's method for authentication, and also Linda Lawton's excellent ASP.NET analytics example.

我花了几天时间在网上搜罗一些ASP样本。网络代码运气不好。我使用了Koffe14的认证方法,以及Linda Lawton的优秀ASP。网络分析的例子。

I've posted the code on my website. It's not MVC, but it might help other people who need to get data from Google analytics into an ASP.NET web page using the v3 Google API.

我已经在我的网站上发布了代码。它不是MVC,但它可能帮助其他需要从谷歌分析获得数据的人成为ASP。NET web页面使用v3谷歌API。

#5


0  

Check out embeddedanalytics.com (disclaimer - I work with them).

查看embeddedanalytics.com(免责声明——我与他们合作)。

This is a simple yet powerful solution geared for people that don't want deal with learning the GA API and then having to link it to visualization (e.g. charts/graphs).

这是一个简单而强大的解决方案,适用于那些不想学习GA API,然后不得不将其与可视化(例如图表/图表)联系起来的人。

Basically define your charts and embed a snippet of code where you want the chart to show. We also support mechanisms so that it is easy to integrate into a custom built CMS or other web portal.

基本上定义您的图表,并在您希望图表显示的地方嵌入代码片段。我们还支持机制,以便很容易地集成到自定义构建的CMS或其他web门户中。