使用Google AnalyticsAPI在C#中显示信息

时间:2022-08-17 15:16:13

I been looking for a good solution all day but google evolve so fast that I can't find something working. What I want to do is that, I have a Web app that has an admin section where user need to be logged in to see the information. In this section I want to show some data from GA, like pageviews for some specific urls. Since it's not the user information that I'm showing but the google analytics'user I want to connect passing information (username/password or APIKey) but I can't find out how. All the sample I found use OAuth2 (witch, if I understand, will ask the visitor to log in using google).

我一整天都在寻找一个好的解决方案,但谷歌进化得如此之快,以至于找不到有用的东西。我想要做的是,我有一个Web应用程序,其中有一个管理部分,用户需要登录才能查看信息。在本节中,我想展示来自GA的一些数据,例如某些特定网址的综合浏览量。由于它不是我正在显示的用户信息,而是谷歌分析用户,我想连接传递信息(用户名/密码或APIKey),但我无法了解如何。我找到的所有样本都使用了OAuth2(如果我理解的话,将要求访问者使用谷歌登录)。

What I found so far :

到目前为止我发现了什么:

Maybe I'm just tired and that tomorrow it will be easy to find a solution but right now I need help!

也许我只是累了,明天很容易找到解决方案,但现在我需要帮助!

Thanks

谢谢

7 个解决方案

#1


29  

I did a lot of search and finally either looking up code from multiple places and then wrapping my own interface around it i came up with the following solution. Not sure if people paste their whole code here, but i guess why not save everyone else time :)

我做了很多搜索,最后要么从多个地方查找代码,然后将自己的界面包裹起来,我想出了以下解决方案。不确定人们是否在这里粘贴了他们的全部代码,但我想为什么不为其他人节省时间:)

Pre-requisites, you will need to install Google.GData.Client and google.gdata.analytics package/dll.

先决条件,您需要安装Google.GData.Client和google.gdata.analytics package / dll。

This is the main class that does the work.

这是完成工作的主要课程。

namespace Utilities.Google
{
    public class Analytics
    {
        private readonly String ClientUserName;
        private readonly String ClientPassword;
        private readonly String TableID;
        private AnalyticsService analyticsService;

        public Analytics(string user, string password, string table)
        {
            this.ClientUserName = user;
            this.ClientPassword = password;
            this.TableID = table;

            // Configure GA API.
            analyticsService = new AnalyticsService("gaExportAPI_acctSample_v2.0");
            // Client Login Authorization.
            analyticsService.setUserCredentials(ClientUserName, ClientPassword);
        }

        /// <summary>
        /// Get the page views for a particular page path
        /// </summary>
        /// <param name="pagePath"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <param name="isPathAbsolute">make this false if the pagePath is a regular expression</param>
        /// <returns></returns>
        public int GetPageViewsForPagePath(string pagePath, DateTime startDate, DateTime endDate, bool isPathAbsolute = true)
        {
            int output = 0;

            // GA Data Feed query uri.
            String baseUrl = "https://www.google.com/analytics/feeds/data";

            DataQuery query = new DataQuery(baseUrl);
            query.Ids = TableID;
            //query.Dimensions = "ga:source,ga:medium";
            query.Metrics = "ga:pageviews";
            //query.Segment = "gaid::-11";
            var filterPrefix = isPathAbsolute ? "ga:pagepath==" : "ga:pagepath=~";
            query.Filters = filterPrefix + pagePath;
            //query.Sort = "-ga:visits";
            //query.NumberToRetrieve = 5;
            query.GAStartDate = startDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
            query.GAEndDate = endDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
            Uri url = query.Uri;
            DataFeed feed = analyticsService.Query(query);
            output = Int32.Parse(feed.Aggregates.Metrics[0].Value);

            return output;
        }

        public Dictionary<string, int> PageViewCounts(string pagePathRegEx, DateTime startDate, DateTime endDate)
        {
            // GA Data Feed query uri.
            String baseUrl = "https://www.google.com/analytics/feeds/data";

            DataQuery query = new DataQuery(baseUrl);
            query.Ids = TableID;
            query.Dimensions = "ga:pagePath";
            query.Metrics = "ga:pageviews";
            //query.Segment = "gaid::-11";
            var filterPrefix = "ga:pagepath=~";
            query.Filters = filterPrefix + pagePathRegEx;
            //query.Sort = "-ga:visits";
            //query.NumberToRetrieve = 5;
            query.GAStartDate = startDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
            query.GAEndDate = endDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
            Uri url = query.Uri;
            DataFeed feed = analyticsService.Query(query);

            var returnDictionary = new Dictionary<string, int>();
            foreach (var entry in feed.Entries)
                returnDictionary.Add(((DataEntry)entry).Dimensions[0].Value, Int32.Parse(((DataEntry)entry).Metrics[0].Value));

            return returnDictionary;
        }
    }
}

And this is the interface and implementation that i use to wrap it up with.

这是我用来包装它的接口和实现。

namespace Utilities
{
    public interface IPageViewCounter
    {
        int GetPageViewCount(string relativeUrl, DateTime startDate, DateTime endDate, bool isPathAbsolute = true);
        Dictionary<string, int> PageViewCounts(string pagePathRegEx, DateTime startDate, DateTime endDate);
    }

    public class GooglePageViewCounter : IPageViewCounter
    {
        private string GoogleUserName
        {
            get
            {
                return ConfigurationManager.AppSettings["googleUserName"];
            }
        }

        private string GooglePassword
        {
            get
            {
                return ConfigurationManager.AppSettings["googlePassword"];
            }
        }

        private string GoogleAnalyticsTableName
        {
            get
            {
                return ConfigurationManager.AppSettings["googleAnalyticsTableName"];
            }
        }

        private Analytics analytics;

        public GooglePageViewCounter()
        {
            analytics = new Analytics(GoogleUserName, GooglePassword, GoogleAnalyticsTableName);
        }

        #region IPageViewCounter Members

        public int GetPageViewCount(string relativeUrl, DateTime startDate, DateTime endDate, bool isPathAbsolute = true)
        {
            int output = 0;
            try
            {
                output = analytics.GetPageViewsForPagePath(relativeUrl, startDate, endDate, isPathAbsolute);
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }

            return output;
        }

        public Dictionary<string, int> PageViewCounts(string pagePathRegEx, DateTime startDate, DateTime endDate)
        {
            var input = analytics.PageViewCounts(pagePathRegEx, startDate, endDate);
            var output = new Dictionary<string, int>();

            foreach (var item in input)
            {
                if (item.Key.Contains('&'))
                {
                    string[] key = item.Key.Split(new char[] { '?', '&' });
                    string newKey = key[0] + "?" + key.FirstOrDefault(k => k.StartsWith("p="));

                    if (output.ContainsKey(newKey))
                        output[newKey] += item.Value;
                    else
                        output[newKey] = item.Value;
                }
                else
                    output.Add(item.Key, item.Value);
            }
            return output;
        }

        #endregion
    }
}

And now the rest is the obvious stuff - you will have to add the web.config values to your application config or webconfig and call IPageViewCounter.GetPageViewCount

现在剩下的就是显而易见的东西 - 您必须将web.config值添加到应用程序配置或webconfig并调用IPageViewCounter.GetPageViewCount

#2


77  

It requires a bit of setup on the google side but it's actually quite simple. I will list step by step.

它需要在谷歌方面进行一些设置,但实际上非常简单。我将逐步列出。

First you will need to create an application in the Google cloud console and enable the Analytics API.

首先,您需要在Google云控制台中创建应用程序并启用Analytics API。

  • Go to http://code.google.com/apis/console
  • 转到http://code.google.com/apis/console
  • Select the drop down and create a project if you do not already have one
  • 如果您还没有项目,请选择下拉菜单并创建项目
  • Once the project is created click on services
  • 创建项目后,单击服务
  • From here enable the Analytics API
  • 从此处启用Analytics API

Now that the Analytics API is enabled the next step will be to enable a service account to access your desired analytics profiles/sites. The service account will allow you to log in without having to prompt a user for credentials.

现在,已启用Analytics API,下一步将是启用服务帐户以访问所需的分析配置文件/站点。该服务帐户将允许您登录,而无需提示用户提供凭据。

  • Go to http://code.google.com/apis/console and choose the project you created from the drop down.
  • 转到http://code.google.com/apis/console,然后从下拉列表中选择您创建的项目。
  • Next go to the "API Access" section and click the "Create another client id" button.
  • 接下来转到“API Access”部分,然后单击“Create another client id”按钮。
  • In the Create Client ID window choose service account and click create client id.
  • 在Create Client ID窗口中,选择service account并单击create client id。
  • Download the public key for this account if it doesn't start the download automatically.You will need this later on when you code for authorization.
  • 如果此帐户没有自动开始下载,请下载该帐户的公钥。稍后您在编写授权代码时将需要此密钥。
  • Before exiting copy the service accounts auto generated email address as you will need this in the next step. The client email looks like @developer.gserviceaccount.com
  • 在退出复制之前,服务帐户会自动生成电子邮件地址,因为您将在下一步中使用此帐户。客户端电子邮件看起来像@ developer.gserviceaccount.com

Now that we have a service account you will need to allow this service account to access to your profiles/sites in Google Analytics.

现在我们有了服务帐户,您需要允许此服务帐户访问Google Analytics中的个人资料/网站。

  • Log into Google Analytics.
  • 登录Google Analytics。
  • Once logged in click on the Admin button to the bottem left on the screen.
  • 登录后,单击Admin屏幕上的bottem按钮。
  • In Admin click the account drop down and select the account/site you would like your service account to be able to access then click on "User Management" under the account section.
  • 在管理员中,点击帐户下拉菜单,然后选择您希望服务帐户访问的帐户/网站,然后点击帐户部分下的“用户管理”。
  • Enter the email address that was generated for your service account and give it read and analyze permission.
  • 输入为您的服务帐户生成的电子邮件地址,并为其提供读取和分析权限。
  • Repeat these steps for any other account/site you would like your service to have access to.
  • 对您希望服务有权访问的任何其他帐户/站点重复这些步骤。

Now that the setup is done for the service account to access Google Analytics through the API we can start to code.

现在,设置已完成,服务帐户可通过API访问Google Analytics,我们可以开始编码。

Get this package from NuGet:

从NuGet获取此包:

Google.Apis.Analytics.v3 Client Library

Google.Apis.Analytics.v3客户端库

Add these usings:

添加这些使用:

using Google.Apis.Analytics.v3;
using Google.Apis.Analytics.v3.Data;
using Google.Apis.Services;
using System.Security.Cryptography.X509Certificates;
using Google.Apis.Auth.OAuth2;
using System.Collections.Generic; 
using System.Linq;

Some things to note are.

有些事情需要注意。

  • The keyPath is the path to the key file you downloaded with a .p12 file extention.
  • keyPath是您使用.p12文件扩展名下载的密钥文件的路径。
  • The accountEmailAddress is the api email we got earlier.
  • accountEmailAddress是我们之前获得的api电子邮件。
  • Scope is an Enum in the Google.Apis.Analytics.v3.AnalyticService class that dictates the url to use in order to authorize (ex: AnalyticsService.Scope.AnalyticsReadonly ).
  • 范围是Google.Apis.Analytics.v3.AnalyticService类中的枚举,它指示要使用的URL以进行授权(例如:AnalyticsService.Scope.AnalyticsReadonly)。
  • Application name is a name of your choosing that tells the google api what is accessing it (aka: it can be what ever you choose).
  • 应用程序名称是您选择的名称,告诉谷歌api访问它的内容(也就是说:它可以是您选择的内容)。

Then the code to do some basic calls is as follows.

然后执行一些基本调用的代码如下。

public class GoogleAnalyticsAPI
{
    public AnalyticsService Service { get; set; }

    public GoogleAnalyticsAPI(string keyPath, string accountEmailAddress)
    {
        var certificate = new X509Certificate2(keyPath, "notasecret", X509KeyStorageFlags.Exportable);

        var credentials = new ServiceAccountCredential(
           new ServiceAccountCredential.Initializer(accountEmailAddress)
           {
               Scopes = new[] { AnalyticsService.Scope.AnalyticsReadonly }
           }.FromCertificate(certificate));

        Service = new AnalyticsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credentials,
                ApplicationName = "WorthlessVariable"
            });
    }

    public AnalyticDataPoint GetAnalyticsData(string profileId, string[] dimensions, string[] metrics, DateTime startDate, DateTime endDate)
    {
        AnalyticDataPoint data = new AnalyticDataPoint();
        if (!profileId.Contains("ga:"))
            profileId = string.Format("ga:{0}", profileId);

        //Make initial call to service.
        //Then check if a next link exists in the response,
        //if so parse and call again using start index param.
        GaData response = null;
        do
        {
            int startIndex = 1;
            if (response != null && !string.IsNullOrEmpty(response.NextLink))
            {
                Uri uri = new Uri(response.NextLink);
                var paramerters = uri.Query.Split('&');
                string s = paramerters.First(i => i.Contains("start-index")).Split('=')[1];
                startIndex = int.Parse(s);
            }

            var request = BuildAnalyticRequest(profileId, dimensions, metrics, startDate, endDate, startIndex);
            response = request.Execute();
            data.ColumnHeaders = response.ColumnHeaders;
            data.Rows.AddRange(response.Rows);

        } while (!string.IsNullOrEmpty(response.NextLink));

        return data;
    }

    private DataResource.GaResource.GetRequest BuildAnalyticRequest(string profileId, string[] dimensions, string[] metrics,
                                                                        DateTime startDate, DateTime endDate, int startIndex)
    {
        DataResource.GaResource.GetRequest request = Service.Data.Ga.Get(profileId, startDate.ToString("yyyy-MM-dd"),
                                                                            endDate.ToString("yyyy-MM-dd"), string.Join(",", metrics));
        request.Dimensions = string.Join(",", dimensions);
        request.StartIndex = startIndex;
        return request;
    }

    public IList<Profile> GetAvailableProfiles()
    {
        var response = Service.Management.Profiles.List("~all", "~all").Execute();
        return response.Items;
    }

    public class AnalyticDataPoint
    {
        public AnalyticDataPoint()
        {
            Rows = new List<IList<string>>();
        }

        public IList<GaData.ColumnHeadersData> ColumnHeaders { get; set; }
        public List<IList<string>> Rows { get; set; }
    }
}

Other Links that will prove helpful:

其他可以证明有用的链接:

Analytic API Explorer - Query API From The Web

Analytic API Explorer - 来自Web的查询API

Analytic API Explorer version 2 - Query API From The Web

Analytic API Explorer版本2 - 从Web查询API

Dimensions and Metrics Reference

维度和指标参考

Hopefully this helps someone trying to do this in the future.

希望这有助于将来尝试这样做的人。

#3


11  

I was hoping just to add a comment to the answer for v3 Beta, but rep points prevent that. However, I thought it would be nice for others to have this information so here it is:

我希望只是为v3 Beta的答案添加评论,但代表点可以防止这种情况发生。但是,我认为其他人拥有这些信息会很好,所以这里是:

using Google.Apis.Authentication.OAuth2;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using System.Security.Cryptography.X509Certificates;
using Google.Apis.Services;

These name spaces are used throughout the code in that post. I always wish people would post name spaces more often, I seem to spend a good bit of time looking for them. I hope this saves some people a few minutes of work.

这些名称空间在该帖子的整个代码中使用。我总是希望人们更频繁地张贴名字空间,我似乎花了很多时间寻找它们。我希望这可以为一些人节省几分钟的工作量。

#4


7  

This answer is for those of you who want access to your own Analytics account and want to use the new Analytics Reporting API v4.

此答案适用于那些希望访问您自己的Google Analytics帐户并希望使用新的Analytics Reporting API v4的用户。

I recently wrote a blog post about how to get Google Analytics data using C#. Read there for all the details.

我最近写了一篇关于如何使用C#获取Google Analytics数据的博文。阅读那里了解所有细节。

You first need to choose between connecting with OAuth2 or a Service Account. I'll assume you own the Analytics account, so you need to create a "Service account key" from the Google APIs Credentials page.

您首先需要在连接OAuth2或服务帐户之间进行选择。我假设您拥有Google Analytics帐户,因此您需要从Google API凭据页面创建“服务帐户密钥”。

Once you create that, download the JSON file and put it in your project (I put mine in my App_Data folder).

创建后,下载JSON文件并将其放入项目中(我将其放入App_Data文件夹中)。

Next, install the Google.Apis.AnalyticsReporting.v4 Nuget package. Also install Newtonsoft's Json.NET.

接下来,安装Google.Apis.AnalyticsReporting.v4 Nuget包。还安装了Newtonsoft的Json.NET。

Include this class somewhere in your project:

在项目的某处包含此类:

public class PersonalServiceAccountCred
{
    public string type { get; set; }
    public string project_id { get; set; }
    public string private_key_id { get; set; }
    public string private_key { get; set; }
    public string client_email { get; set; }
    public string client_id { get; set; }
    public string auth_uri { get; set; }
    public string token_uri { get; set; }
    public string auth_provider_x509_cert_url { get; set; }
    public string client_x509_cert_url { get; set; }
}

And here's what you've been waiting for: a full example!

这就是你一直在等待的东西:一个完整​​的例子!

string keyFilePath = Server.MapPath("~/App_Data/Your-API-Key-Filename.json");
string json = System.IO.File.ReadAllText(keyFilePath);

var cr = JsonConvert.DeserializeObject(json);

var xCred = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(cr.client_email)
{
    Scopes = new[] {
        AnalyticsReportingService.Scope.Analytics
    }
}.FromPrivateKey(cr.private_key));

using (var svc = new AnalyticsReportingService(
    new BaseClientService.Initializer
    {
        HttpClientInitializer = xCred,
        ApplicationName = "[Your Application Name]"
    })
)
{
    // Create the DateRange object.
    DateRange dateRange = new DateRange() { StartDate = "2017-05-01", EndDate = "2017-05-31" };

    // Create the Metrics object.
    Metric sessions = new Metric { Expression = "ga:sessions", Alias = "Sessions" };

    //Create the Dimensions object.
    Dimension browser = new Dimension { Name = "ga:browser" };

    // Create the ReportRequest object.
    ReportRequest reportRequest = new ReportRequest
    {
        ViewId = "[A ViewId in your account]",
        DateRanges = new List() { dateRange },
        Dimensions = new List() { browser },
        Metrics = new List() { sessions }
    };

    List requests = new List();
    requests.Add(reportRequest);

    // Create the GetReportsRequest object.
    GetReportsRequest getReport = new GetReportsRequest() { ReportRequests = requests };

    // Call the batchGet method.
    GetReportsResponse response = svc.Reports.BatchGet(getReport).Execute();
}

We start by deserializing the service account key information from the JSON file and convert it to a PersonalServiceAccountCred object. Then, we create the ServiceAccountCredential and connect to Google via the AnalyticsReportingService. Using that service, we then prepare some basic filters to pass to the API and send off the request.

我们首先从JSON文件反序列化服务帐户密钥信息,然后将其转换为PersonalServiceAccountCred对象。然后,我们创建ServiceAccountCredential并通过AnalyticsReportingService连接到Google。然后,我们使用该服务准备一些基本过滤器以传递给API并发送请求。

It's probably best to set a breakpoint on the line where the response variable is declared, press F10 once, then hover over the variable, so you can see what data is available for you to use in the response.

最好在声明响应变量的行上设置断点,按F10一次,然后将鼠标悬停在变量上,这样您就可以看到哪些数据可供您在响应中使用。

#5


3  

I've setup something pretty similar to the above answer in a nuGet package. It does the following: - connects to a "Service Account" you set up in the API Console - Pulls any Google Analytics data you would like - Displays that data using Google's Charts API and it does all of this in a very easy to modify way. You can see more here: https://www.nuget.org/packages/GoogleAnalytics.GoogleCharts.NET/.

我在nuGet包中设置了与上述答案非常相似的东西。它执行以下操作: - 连接到您在API控制台中设置的“服务帐户” - 提取您想要的任何Google Analytics数据 - 使用Google的图表API显示该数据,并以非常容易修改的方式完成所有这些操作。您可以在此处查看更多信息:https://www.nuget.org/packages/GoogleAnalytics.GoogleCharts.NET/。

#6


1  

Hope google will provide proper documentation someday. Here I am listing all the steps to integrate google analytics server side authentication in ASP.NET C#.

希望谷歌有一天会提供适当的文件。在这里,我列出了在ASP.NET C#中集成Google Analytics分析服务器端身份验证的所有步骤。

Step 1: Create a project in google console

第1步:在谷歌控制台中创建一个项目

Goto the link https://console.developers.google.com/iam-admin/projects and create a project by clicking on "Create Project" button and provide project name in the pop up window and submit it.

转到https://console.developers.google.com/iam-admin/projects链接并点击“创建项目”按钮创建项目,并在弹出窗口中提供项目名称并提交。

Step 2: Create credentials and service account

第2步:创建凭据和服务帐户

After creation of the project, you will be redirected to "API Manager" page. Click on credentials and press "Create Credentials" button. select "service account key" from dropdown you will be redirected to next page. In the service account drop down, select "New service account". Fill in the service account name and download the p12 key. It will have p12 extension. you will get a popup having a password "notasecret" which is default and your private key will be downloaded.

创建项目后,您将被重定向到“API Manager”页面。单击凭据,然后按“创建凭据”按钮。从下拉列表中选择“服务帐户密钥”,您将被重定向到下一页。在服务帐户下拉列表中,选择“新服务帐户”。填写服务帐户名称并下载p12密钥。它将有p12扩展名。您将获得一个密码为“notasecret”的弹出窗口,这是默认密码,您的私钥将被下载。

Step 3: Create 0auth client ID

第3步:创建0auth客户端ID

click on the "create credentials" dropdown and select "0auth client ID" you will be redirected to "0auth consent screen" tab. provide a random name in the project name textbox. select application type as "Web application" and click create button. Copy the generated client ID in a notepad.

单击“创建凭据”下拉列表并选择“0auth客户端ID”,您将被重定向到“0auth同意屏幕”选项卡。在项目名称文本框中提供随机名称。选择应用程序类型为“Web应用程序”并单击“创建”按钮。将生成的客户端ID复制到记事本中。

Step 4: Enable the APIs

第4步:启用API

On the left side click on the "Overview" tab and select "Enabled APIs" from the horizontal tab. In the search bar search for "Analytics API" click on the dropdown and press "Enable" button. Now again search for "Analytics Reporting V4" and enable it.

在左侧单击“概述”选项卡,然后从水平选项卡中选择“已启用的API”。在搜索栏中搜索“Analytics API”,单击下拉列表并按“启用”按钮。现在再次搜索“Analytics Reporting V4”并启用它。

Step 5: Install nuget packages

第5步:安装nuget包

In visual studio, Go to Tools > Nuget Package Manager > Package Manager Console. Copy paste the below code in the console to install the nuget packages.

在visual studio中,转到“工具”>“Nuget包管理器”>“包管理器控制台”。复制粘贴以下代码在控制台中安装nuget包。

Install-Package Google.Apis.Analytics.v3

安装包Google.Apis.Analytics.v3

Install-Package DotNetOpenAuth.Core -Version 4.3.4.13329

安装包DotNetOpenAuth.Core -Version 4.3.4.13329

The above two packages are Google analytics and DotNetOpenAuth nuget packages.

以上两个软件包是Google Analytics和DotNetOpenAuth nuget软件包。

Step 6: Provide 'View and Analyze' permission to service account

第6步:为服务帐户提供“查看和分析”权限

Go to google analytics account and click on "Admin" tab and select "User Management" from left menus,select a domain of which you want to access analytics data and insert the service account email id under it and select "Read and Analyze" permission from the dropdown. Service account email id looks like ex: googleanalytics@googleanalytics.iam.gserviceaccount.com.

转到Google Analytics(分析)帐户,然后单击“管理员”(Admin)选项卡并从左侧菜单中选择“用户管理”(User Management),选择要访问其分析数据的域并在其下插入服务帐户电子邮件ID,然后选择“读取和分析”权限从下拉列表。服务帐户电子邮件ID如下所示:googleanalytics@googleanalytics.iam.gserviceaccount.com。

Working Code

工作守则

FRONT END CODE:

前端代码:

Copy and paste the below analytics embed script in your front end or else you can get this code from google analytics documentation page also.

将以下分析嵌入脚本复制并粘贴到您的前端,否则您也可以从谷歌分析文档页面获取此代码。

 <script>
    (function (w, d, s, g, js, fs) {
        g = w.gapi || (w.gapi = {}); g.analytics = { q: [], ready: function (f) { this.q.push(f); } };
        js = d.createElement(s); fs = d.getElementsByTagName(s)[0];
        js.src = 'https://apis.google.com/js/platform.js';
        fs.parentNode.insertBefore(js, fs); js.onload = function () { g.load('analytics'); };
    }(window, document, 'script'));</script>

Paste the below code in the body tag of your front end page.

将以下代码粘贴到前端页面的正文标记中。

 <asp:HiddenField ID="accessToken" runat="server" />
<div id="chart-1-container" style="width:600px;border:1px solid #ccc;"></div>
        <script>
           var access_token = document.getElementById('<%= accessToken.ClientID%>').value;

            gapi.analytics.ready(function () {
                /**
                 * Authorize the user with an access token obtained server side.
                 */
                gapi.analytics.auth.authorize({
                    'serverAuth': {
                        'access_token': access_token
                    }
                });
                /**
                 * Creates a new DataChart instance showing sessions.
                 * It will be rendered inside an element with the id "chart-1-container".
                 */
                var dataChart1 = new gapi.analytics.googleCharts.DataChart({
                    query: {
                        'ids': 'ga:53861036', // VIEW ID <-- Goto your google analytics account and select the domain whose analytics data you want to display on your webpage. From the URL  ex: a507598w53044903p53861036. Copy the digits after "p". It is your view ID
                        'start-date': '2016-04-01',
                        'end-date': '2016-04-30',
                        'metrics': 'ga:sessions',
                        'dimensions': 'ga:date'
                    },
                    chart: {
                        'container': 'chart-1-container',
                        'type': 'LINE',
                        'options': {
                            'width': '100%'
                        }
                    }
                });
                dataChart1.execute();


                /**
                 * Creates a new DataChart instance showing top 5 most popular demos/tools
                 * amongst returning users only.
                 * It will be rendered inside an element with the id "chart-3-container".
                 */


            });
</script>

You can also get your View ID from https://ga-dev-tools.appspot.com/account-explorer/

您还可以从https://ga-dev-tools.appspot.com/account-explorer/获取您的View ID

BACK END CODE:

后端代码:

 using System;
    using System.Linq;
    using System.Collections.Generic;
    using System.Collections.Specialized;
    using System.Web.Script.Serialization;
    using System.Net;
    using System.Text;
    using Google.Apis.Analytics.v3;
    using Google.Apis.Analytics.v3.Data;
    using Google.Apis.Services;
    using System.Security.Cryptography.X509Certificates;
    using Google.Apis.Auth.OAuth2;
    using Google.Apis.Util;
    using DotNetOpenAuth.OAuth2;
    using System.Security.Cryptography;

    namespace googleAnalytics
    {
        public partial class api : System.Web.UI.Page
        {
            public const string SCOPE_ANALYTICS_READONLY = "https://www.googleapis.com/auth/analytics.readonly";

            string ServiceAccountUser = "googleanalytics@googleanalytics.iam.gserviceaccount.com"; //service account email ID
            string keyFile = @"D:\key.p12"; //file link to downloaded key with p12 extension
            protected void Page_Load(object sender, EventArgs e)
            {

               string Token = Convert.ToString(GetAccessToken(ServiceAccountUser, keyFile, SCOPE_ANALYTICS_READONLY));

               accessToken.Value = Token;

                var certificate = new X509Certificate2(keyFile, "notasecret", X509KeyStorageFlags.Exportable);

                var credentials = new ServiceAccountCredential(

                    new ServiceAccountCredential.Initializer(ServiceAccountUser)
                    {
                        Scopes = new[] { AnalyticsService.Scope.AnalyticsReadonly }
                    }.FromCertificate(certificate));

                var service = new AnalyticsService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credentials,
                    ApplicationName = "Google Analytics API"
                });

                string profileId = "ga:53861036";
                string startDate = "2016-04-01";
                string endDate = "2016-04-30";
                string metrics = "ga:sessions,ga:users,ga:pageviews,ga:bounceRate,ga:visits";

                DataResource.GaResource.GetRequest request = service.Data.Ga.Get(profileId, startDate, endDate, metrics);


                GaData data = request.Execute();
                List<string> ColumnName = new List<string>();
                foreach (var h in data.ColumnHeaders)
                {
                    ColumnName.Add(h.Name);
                }


                List<double> values = new List<double>();
                foreach (var row in data.Rows)
                {
                    foreach (var item in row)
                    {
                        values.Add(Convert.ToDouble(item));
                    }

                }
                values[3] = Math.Truncate(100 * values[3]) / 100;

                txtSession.Text = values[0].ToString();
                txtUsers.Text = values[1].ToString();
                txtPageViews.Text = values[2].ToString();
                txtBounceRate.Text = values[3].ToString();
                txtVisits.Text = values[4].ToString();

            }


         public static dynamic GetAccessToken(string clientIdEMail, string keyFilePath, string scope)
        {
            // certificate
            var certificate = new X509Certificate2(keyFilePath, "notasecret");

            // header
            var header = new { typ = "JWT", alg = "RS256" };

            // claimset
            var times = GetExpiryAndIssueDate();
            var claimset = new
            {
                iss = clientIdEMail,
                scope = scope,
                aud = "https://accounts.google.com/o/oauth2/token",
                iat = times[0],
                exp = times[1],
            };

            JavaScriptSerializer ser = new JavaScriptSerializer();

            // encoded header
            var headerSerialized = ser.Serialize(header);
            var headerBytes = Encoding.UTF8.GetBytes(headerSerialized);
            var headerEncoded = Convert.ToBase64String(headerBytes);

            // encoded claimset
            var claimsetSerialized = ser.Serialize(claimset);
            var claimsetBytes = Encoding.UTF8.GetBytes(claimsetSerialized);
            var claimsetEncoded = Convert.ToBase64String(claimsetBytes);

            // input
            var input = headerEncoded + "." + claimsetEncoded;
            var inputBytes = Encoding.UTF8.GetBytes(input);

            // signature
            var rsa = certificate.PrivateKey as RSACryptoServiceProvider;
            var cspParam = new CspParameters
            {
                KeyContainerName = rsa.CspKeyContainerInfo.KeyContainerName,
                KeyNumber = rsa.CspKeyContainerInfo.KeyNumber == KeyNumber.Exchange ? 1 : 2
            };
            var aescsp = new RSACryptoServiceProvider(cspParam) { PersistKeyInCsp = false };
            var signatureBytes = aescsp.SignData(inputBytes, "SHA256");
            var signatureEncoded = Convert.ToBase64String(signatureBytes);

            // jwt
            var jwt = headerEncoded + "." + claimsetEncoded + "." + signatureEncoded;

            var client = new WebClient();
            client.Encoding = Encoding.UTF8;
            var uri = "https://accounts.google.com/o/oauth2/token";
            var content = new NameValueCollection();

            content["assertion"] = jwt;
            content["grant_type"] = "urn:ietf:params:oauth:grant-type:jwt-bearer";

            string response = Encoding.UTF8.GetString(client.UploadValues(uri, "POST", content));


            var result = ser.Deserialize<dynamic>(response);

            object pulledObject = null;

            string token = "access_token";
            if (result.ContainsKey(token))
            {
                pulledObject = result[token];
            }


            //return result;
            return pulledObject;
        }

        private static int[] GetExpiryAndIssueDate()
        {
            var utc0 = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            var issueTime = DateTime.UtcNow;

            var iat = (int)issueTime.Subtract(utc0).TotalSeconds;
            var exp = (int)issueTime.AddMinutes(55).Subtract(utc0).TotalSeconds;

            return new[] { iat, exp };
        }

        }
    }

#7


0  

Another Working Approach

另一种工作方法

Add below code in the ConfigAuth

在ConfigAuth中添加以下代码

  var googleApiOptions = new GoogleOAuth2AuthenticationOptions()
        {
            AccessType = "offline", // can use only if require
            ClientId = ClientId,
            ClientSecret = ClientSecret,
            Provider = new GoogleOAuth2AuthenticationProvider()
            {
                OnAuthenticated = context =>
                {
                    context.Identity.AddClaim(new Claim("Google_AccessToken", context.AccessToken));

                    if (context.RefreshToken != null)
                    {
                        context.Identity.AddClaim(new Claim("GoogleRefreshToken", context.RefreshToken));
                    }
                    context.Identity.AddClaim(new Claim("GoogleUserId", context.Id));
                    context.Identity.AddClaim(new Claim("GoogleTokenIssuedAt", DateTime.Now.ToBinary().ToString()));
                    var expiresInSec = 10000;
                    context.Identity.AddClaim(new Claim("GoogleTokenExpiresIn", expiresInSec.ToString()));


                    return Task.FromResult(0);
                }
            },

            SignInAsAuthenticationType = DefaultAuthenticationTypes.ApplicationCookie
        };
        googleApiOptions.Scope.Add("openid"); // Need to add for google+ 
        googleApiOptions.Scope.Add("profile");// Need to add for google+ 
        googleApiOptions.Scope.Add("email");// Need to add for google+ 
        googleApiOptions.Scope.Add("https://www.googleapis.com/auth/analytics.readonly");

        app.UseGoogleAuthentication(googleApiOptions);

Add below code, name spaces and relative references

添加以下代码,名称空间和相关引用

 using Google.Apis.Analytics.v3;
 using Google.Apis.Analytics.v3.Data;
 using Google.Apis.Auth.OAuth2;
 using Google.Apis.Auth.OAuth2.Flows;
 using Google.Apis.Auth.OAuth2.Responses;
 using Google.Apis.Services;
 using Microsoft.AspNet.Identity;
 using Microsoft.Owin.Security;
 using System;
 using System.Threading.Tasks;
 using System.Web;
 using System.Web.Mvc;

public class HomeController : Controller
{
    AnalyticsService service;
    public IAuthenticationManager AuthenticationManager
    {
        get
        {
            return HttpContext.GetOwinContext().Authentication;
        }
    }

    public async Task<ActionResult> AccountList()
    {
        service = new AnalyticsService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = await GetCredentialForApiAsync(),
            ApplicationName = "Analytics API sample",
        });


        //Account List
        ManagementResource.AccountsResource.ListRequest AccountListRequest = service.Management.Accounts.List();
        //service.QuotaUser = "MyApplicationProductKey";
        Accounts AccountList = AccountListRequest.Execute();



        return View();
    }

    private async Task<UserCredential> GetCredentialForApiAsync()
    {
        var initializer = new GoogleAuthorizationCodeFlow.Initializer
        {
            ClientSecrets = new ClientSecrets
            {
                ClientId = ClientId,
                ClientSecret = ClientSecret,
            },
            Scopes = new[] { "https://www.googleapis.com/auth/analytics.readonly" }
        };
        var flow = new GoogleAuthorizationCodeFlow(initializer);

        var identity = await AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ApplicationCookie);
        if (identity == null)
        {
            Redirect("/Account/Login");
        }

        var userId = identity.FindFirstValue("GoogleUserId");

        var token = new TokenResponse()
        {
            AccessToken = identity.FindFirstValue("Google_AccessToken"),
            RefreshToken = identity.FindFirstValue("GoogleRefreshToken"),
            Issued = DateTime.FromBinary(long.Parse(identity.FindFirstValue("GoogleTokenIssuedAt"))),
            ExpiresInSeconds = long.Parse(identity.FindFirstValue("GoogleTokenExpiresIn")),
        };

        return new UserCredential(flow, userId, token);
    }
}

Add this in the Application_Start() in Global.asax

在Global.asax中的Application_Start()中添加它

  AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;

#1


29  

I did a lot of search and finally either looking up code from multiple places and then wrapping my own interface around it i came up with the following solution. Not sure if people paste their whole code here, but i guess why not save everyone else time :)

我做了很多搜索,最后要么从多个地方查找代码,然后将自己的界面包裹起来,我想出了以下解决方案。不确定人们是否在这里粘贴了他们的全部代码,但我想为什么不为其他人节省时间:)

Pre-requisites, you will need to install Google.GData.Client and google.gdata.analytics package/dll.

先决条件,您需要安装Google.GData.Client和google.gdata.analytics package / dll。

This is the main class that does the work.

这是完成工作的主要课程。

namespace Utilities.Google
{
    public class Analytics
    {
        private readonly String ClientUserName;
        private readonly String ClientPassword;
        private readonly String TableID;
        private AnalyticsService analyticsService;

        public Analytics(string user, string password, string table)
        {
            this.ClientUserName = user;
            this.ClientPassword = password;
            this.TableID = table;

            // Configure GA API.
            analyticsService = new AnalyticsService("gaExportAPI_acctSample_v2.0");
            // Client Login Authorization.
            analyticsService.setUserCredentials(ClientUserName, ClientPassword);
        }

        /// <summary>
        /// Get the page views for a particular page path
        /// </summary>
        /// <param name="pagePath"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <param name="isPathAbsolute">make this false if the pagePath is a regular expression</param>
        /// <returns></returns>
        public int GetPageViewsForPagePath(string pagePath, DateTime startDate, DateTime endDate, bool isPathAbsolute = true)
        {
            int output = 0;

            // GA Data Feed query uri.
            String baseUrl = "https://www.google.com/analytics/feeds/data";

            DataQuery query = new DataQuery(baseUrl);
            query.Ids = TableID;
            //query.Dimensions = "ga:source,ga:medium";
            query.Metrics = "ga:pageviews";
            //query.Segment = "gaid::-11";
            var filterPrefix = isPathAbsolute ? "ga:pagepath==" : "ga:pagepath=~";
            query.Filters = filterPrefix + pagePath;
            //query.Sort = "-ga:visits";
            //query.NumberToRetrieve = 5;
            query.GAStartDate = startDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
            query.GAEndDate = endDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
            Uri url = query.Uri;
            DataFeed feed = analyticsService.Query(query);
            output = Int32.Parse(feed.Aggregates.Metrics[0].Value);

            return output;
        }

        public Dictionary<string, int> PageViewCounts(string pagePathRegEx, DateTime startDate, DateTime endDate)
        {
            // GA Data Feed query uri.
            String baseUrl = "https://www.google.com/analytics/feeds/data";

            DataQuery query = new DataQuery(baseUrl);
            query.Ids = TableID;
            query.Dimensions = "ga:pagePath";
            query.Metrics = "ga:pageviews";
            //query.Segment = "gaid::-11";
            var filterPrefix = "ga:pagepath=~";
            query.Filters = filterPrefix + pagePathRegEx;
            //query.Sort = "-ga:visits";
            //query.NumberToRetrieve = 5;
            query.GAStartDate = startDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
            query.GAEndDate = endDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
            Uri url = query.Uri;
            DataFeed feed = analyticsService.Query(query);

            var returnDictionary = new Dictionary<string, int>();
            foreach (var entry in feed.Entries)
                returnDictionary.Add(((DataEntry)entry).Dimensions[0].Value, Int32.Parse(((DataEntry)entry).Metrics[0].Value));

            return returnDictionary;
        }
    }
}

And this is the interface and implementation that i use to wrap it up with.

这是我用来包装它的接口和实现。

namespace Utilities
{
    public interface IPageViewCounter
    {
        int GetPageViewCount(string relativeUrl, DateTime startDate, DateTime endDate, bool isPathAbsolute = true);
        Dictionary<string, int> PageViewCounts(string pagePathRegEx, DateTime startDate, DateTime endDate);
    }

    public class GooglePageViewCounter : IPageViewCounter
    {
        private string GoogleUserName
        {
            get
            {
                return ConfigurationManager.AppSettings["googleUserName"];
            }
        }

        private string GooglePassword
        {
            get
            {
                return ConfigurationManager.AppSettings["googlePassword"];
            }
        }

        private string GoogleAnalyticsTableName
        {
            get
            {
                return ConfigurationManager.AppSettings["googleAnalyticsTableName"];
            }
        }

        private Analytics analytics;

        public GooglePageViewCounter()
        {
            analytics = new Analytics(GoogleUserName, GooglePassword, GoogleAnalyticsTableName);
        }

        #region IPageViewCounter Members

        public int GetPageViewCount(string relativeUrl, DateTime startDate, DateTime endDate, bool isPathAbsolute = true)
        {
            int output = 0;
            try
            {
                output = analytics.GetPageViewsForPagePath(relativeUrl, startDate, endDate, isPathAbsolute);
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }

            return output;
        }

        public Dictionary<string, int> PageViewCounts(string pagePathRegEx, DateTime startDate, DateTime endDate)
        {
            var input = analytics.PageViewCounts(pagePathRegEx, startDate, endDate);
            var output = new Dictionary<string, int>();

            foreach (var item in input)
            {
                if (item.Key.Contains('&'))
                {
                    string[] key = item.Key.Split(new char[] { '?', '&' });
                    string newKey = key[0] + "?" + key.FirstOrDefault(k => k.StartsWith("p="));

                    if (output.ContainsKey(newKey))
                        output[newKey] += item.Value;
                    else
                        output[newKey] = item.Value;
                }
                else
                    output.Add(item.Key, item.Value);
            }
            return output;
        }

        #endregion
    }
}

And now the rest is the obvious stuff - you will have to add the web.config values to your application config or webconfig and call IPageViewCounter.GetPageViewCount

现在剩下的就是显而易见的东西 - 您必须将web.config值添加到应用程序配置或webconfig并调用IPageViewCounter.GetPageViewCount

#2


77  

It requires a bit of setup on the google side but it's actually quite simple. I will list step by step.

它需要在谷歌方面进行一些设置,但实际上非常简单。我将逐步列出。

First you will need to create an application in the Google cloud console and enable the Analytics API.

首先,您需要在Google云控制台中创建应用程序并启用Analytics API。

  • Go to http://code.google.com/apis/console
  • 转到http://code.google.com/apis/console
  • Select the drop down and create a project if you do not already have one
  • 如果您还没有项目,请选择下拉菜单并创建项目
  • Once the project is created click on services
  • 创建项目后,单击服务
  • From here enable the Analytics API
  • 从此处启用Analytics API

Now that the Analytics API is enabled the next step will be to enable a service account to access your desired analytics profiles/sites. The service account will allow you to log in without having to prompt a user for credentials.

现在,已启用Analytics API,下一步将是启用服务帐户以访问所需的分析配置文件/站点。该服务帐户将允许您登录,而无需提示用户提供凭据。

  • Go to http://code.google.com/apis/console and choose the project you created from the drop down.
  • 转到http://code.google.com/apis/console,然后从下拉列表中选择您创建的项目。
  • Next go to the "API Access" section and click the "Create another client id" button.
  • 接下来转到“API Access”部分,然后单击“Create another client id”按钮。
  • In the Create Client ID window choose service account and click create client id.
  • 在Create Client ID窗口中,选择service account并单击create client id。
  • Download the public key for this account if it doesn't start the download automatically.You will need this later on when you code for authorization.
  • 如果此帐户没有自动开始下载,请下载该帐户的公钥。稍后您在编写授权代码时将需要此密钥。
  • Before exiting copy the service accounts auto generated email address as you will need this in the next step. The client email looks like @developer.gserviceaccount.com
  • 在退出复制之前,服务帐户会自动生成电子邮件地址,因为您将在下一步中使用此帐户。客户端电子邮件看起来像@ developer.gserviceaccount.com

Now that we have a service account you will need to allow this service account to access to your profiles/sites in Google Analytics.

现在我们有了服务帐户,您需要允许此服务帐户访问Google Analytics中的个人资料/网站。

  • Log into Google Analytics.
  • 登录Google Analytics。
  • Once logged in click on the Admin button to the bottem left on the screen.
  • 登录后,单击Admin屏幕上的bottem按钮。
  • In Admin click the account drop down and select the account/site you would like your service account to be able to access then click on "User Management" under the account section.
  • 在管理员中,点击帐户下拉菜单,然后选择您希望服务帐户访问的帐户/网站,然后点击帐户部分下的“用户管理”。
  • Enter the email address that was generated for your service account and give it read and analyze permission.
  • 输入为您的服务帐户生成的电子邮件地址,并为其提供读取和分析权限。
  • Repeat these steps for any other account/site you would like your service to have access to.
  • 对您希望服务有权访问的任何其他帐户/站点重复这些步骤。

Now that the setup is done for the service account to access Google Analytics through the API we can start to code.

现在,设置已完成,服务帐户可通过API访问Google Analytics,我们可以开始编码。

Get this package from NuGet:

从NuGet获取此包:

Google.Apis.Analytics.v3 Client Library

Google.Apis.Analytics.v3客户端库

Add these usings:

添加这些使用:

using Google.Apis.Analytics.v3;
using Google.Apis.Analytics.v3.Data;
using Google.Apis.Services;
using System.Security.Cryptography.X509Certificates;
using Google.Apis.Auth.OAuth2;
using System.Collections.Generic; 
using System.Linq;

Some things to note are.

有些事情需要注意。

  • The keyPath is the path to the key file you downloaded with a .p12 file extention.
  • keyPath是您使用.p12文件扩展名下载的密钥文件的路径。
  • The accountEmailAddress is the api email we got earlier.
  • accountEmailAddress是我们之前获得的api电子邮件。
  • Scope is an Enum in the Google.Apis.Analytics.v3.AnalyticService class that dictates the url to use in order to authorize (ex: AnalyticsService.Scope.AnalyticsReadonly ).
  • 范围是Google.Apis.Analytics.v3.AnalyticService类中的枚举,它指示要使用的URL以进行授权(例如:AnalyticsService.Scope.AnalyticsReadonly)。
  • Application name is a name of your choosing that tells the google api what is accessing it (aka: it can be what ever you choose).
  • 应用程序名称是您选择的名称,告诉谷歌api访问它的内容(也就是说:它可以是您选择的内容)。

Then the code to do some basic calls is as follows.

然后执行一些基本调用的代码如下。

public class GoogleAnalyticsAPI
{
    public AnalyticsService Service { get; set; }

    public GoogleAnalyticsAPI(string keyPath, string accountEmailAddress)
    {
        var certificate = new X509Certificate2(keyPath, "notasecret", X509KeyStorageFlags.Exportable);

        var credentials = new ServiceAccountCredential(
           new ServiceAccountCredential.Initializer(accountEmailAddress)
           {
               Scopes = new[] { AnalyticsService.Scope.AnalyticsReadonly }
           }.FromCertificate(certificate));

        Service = new AnalyticsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credentials,
                ApplicationName = "WorthlessVariable"
            });
    }

    public AnalyticDataPoint GetAnalyticsData(string profileId, string[] dimensions, string[] metrics, DateTime startDate, DateTime endDate)
    {
        AnalyticDataPoint data = new AnalyticDataPoint();
        if (!profileId.Contains("ga:"))
            profileId = string.Format("ga:{0}", profileId);

        //Make initial call to service.
        //Then check if a next link exists in the response,
        //if so parse and call again using start index param.
        GaData response = null;
        do
        {
            int startIndex = 1;
            if (response != null && !string.IsNullOrEmpty(response.NextLink))
            {
                Uri uri = new Uri(response.NextLink);
                var paramerters = uri.Query.Split('&');
                string s = paramerters.First(i => i.Contains("start-index")).Split('=')[1];
                startIndex = int.Parse(s);
            }

            var request = BuildAnalyticRequest(profileId, dimensions, metrics, startDate, endDate, startIndex);
            response = request.Execute();
            data.ColumnHeaders = response.ColumnHeaders;
            data.Rows.AddRange(response.Rows);

        } while (!string.IsNullOrEmpty(response.NextLink));

        return data;
    }

    private DataResource.GaResource.GetRequest BuildAnalyticRequest(string profileId, string[] dimensions, string[] metrics,
                                                                        DateTime startDate, DateTime endDate, int startIndex)
    {
        DataResource.GaResource.GetRequest request = Service.Data.Ga.Get(profileId, startDate.ToString("yyyy-MM-dd"),
                                                                            endDate.ToString("yyyy-MM-dd"), string.Join(",", metrics));
        request.Dimensions = string.Join(",", dimensions);
        request.StartIndex = startIndex;
        return request;
    }

    public IList<Profile> GetAvailableProfiles()
    {
        var response = Service.Management.Profiles.List("~all", "~all").Execute();
        return response.Items;
    }

    public class AnalyticDataPoint
    {
        public AnalyticDataPoint()
        {
            Rows = new List<IList<string>>();
        }

        public IList<GaData.ColumnHeadersData> ColumnHeaders { get; set; }
        public List<IList<string>> Rows { get; set; }
    }
}

Other Links that will prove helpful:

其他可以证明有用的链接:

Analytic API Explorer - Query API From The Web

Analytic API Explorer - 来自Web的查询API

Analytic API Explorer version 2 - Query API From The Web

Analytic API Explorer版本2 - 从Web查询API

Dimensions and Metrics Reference

维度和指标参考

Hopefully this helps someone trying to do this in the future.

希望这有助于将来尝试这样做的人。

#3


11  

I was hoping just to add a comment to the answer for v3 Beta, but rep points prevent that. However, I thought it would be nice for others to have this information so here it is:

我希望只是为v3 Beta的答案添加评论,但代表点可以防止这种情况发生。但是,我认为其他人拥有这些信息会很好,所以这里是:

using Google.Apis.Authentication.OAuth2;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using System.Security.Cryptography.X509Certificates;
using Google.Apis.Services;

These name spaces are used throughout the code in that post. I always wish people would post name spaces more often, I seem to spend a good bit of time looking for them. I hope this saves some people a few minutes of work.

这些名称空间在该帖子的整个代码中使用。我总是希望人们更频繁地张贴名字空间,我似乎花了很多时间寻找它们。我希望这可以为一些人节省几分钟的工作量。

#4


7  

This answer is for those of you who want access to your own Analytics account and want to use the new Analytics Reporting API v4.

此答案适用于那些希望访问您自己的Google Analytics帐户并希望使用新的Analytics Reporting API v4的用户。

I recently wrote a blog post about how to get Google Analytics data using C#. Read there for all the details.

我最近写了一篇关于如何使用C#获取Google Analytics数据的博文。阅读那里了解所有细节。

You first need to choose between connecting with OAuth2 or a Service Account. I'll assume you own the Analytics account, so you need to create a "Service account key" from the Google APIs Credentials page.

您首先需要在连接OAuth2或服务帐户之间进行选择。我假设您拥有Google Analytics帐户,因此您需要从Google API凭据页面创建“服务帐户密钥”。

Once you create that, download the JSON file and put it in your project (I put mine in my App_Data folder).

创建后,下载JSON文件并将其放入项目中(我将其放入App_Data文件夹中)。

Next, install the Google.Apis.AnalyticsReporting.v4 Nuget package. Also install Newtonsoft's Json.NET.

接下来,安装Google.Apis.AnalyticsReporting.v4 Nuget包。还安装了Newtonsoft的Json.NET。

Include this class somewhere in your project:

在项目的某处包含此类:

public class PersonalServiceAccountCred
{
    public string type { get; set; }
    public string project_id { get; set; }
    public string private_key_id { get; set; }
    public string private_key { get; set; }
    public string client_email { get; set; }
    public string client_id { get; set; }
    public string auth_uri { get; set; }
    public string token_uri { get; set; }
    public string auth_provider_x509_cert_url { get; set; }
    public string client_x509_cert_url { get; set; }
}

And here's what you've been waiting for: a full example!

这就是你一直在等待的东西:一个完整​​的例子!

string keyFilePath = Server.MapPath("~/App_Data/Your-API-Key-Filename.json");
string json = System.IO.File.ReadAllText(keyFilePath);

var cr = JsonConvert.DeserializeObject(json);

var xCred = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(cr.client_email)
{
    Scopes = new[] {
        AnalyticsReportingService.Scope.Analytics
    }
}.FromPrivateKey(cr.private_key));

using (var svc = new AnalyticsReportingService(
    new BaseClientService.Initializer
    {
        HttpClientInitializer = xCred,
        ApplicationName = "[Your Application Name]"
    })
)
{
    // Create the DateRange object.
    DateRange dateRange = new DateRange() { StartDate = "2017-05-01", EndDate = "2017-05-31" };

    // Create the Metrics object.
    Metric sessions = new Metric { Expression = "ga:sessions", Alias = "Sessions" };

    //Create the Dimensions object.
    Dimension browser = new Dimension { Name = "ga:browser" };

    // Create the ReportRequest object.
    ReportRequest reportRequest = new ReportRequest
    {
        ViewId = "[A ViewId in your account]",
        DateRanges = new List() { dateRange },
        Dimensions = new List() { browser },
        Metrics = new List() { sessions }
    };

    List requests = new List();
    requests.Add(reportRequest);

    // Create the GetReportsRequest object.
    GetReportsRequest getReport = new GetReportsRequest() { ReportRequests = requests };

    // Call the batchGet method.
    GetReportsResponse response = svc.Reports.BatchGet(getReport).Execute();
}

We start by deserializing the service account key information from the JSON file and convert it to a PersonalServiceAccountCred object. Then, we create the ServiceAccountCredential and connect to Google via the AnalyticsReportingService. Using that service, we then prepare some basic filters to pass to the API and send off the request.

我们首先从JSON文件反序列化服务帐户密钥信息,然后将其转换为PersonalServiceAccountCred对象。然后,我们创建ServiceAccountCredential并通过AnalyticsReportingService连接到Google。然后,我们使用该服务准备一些基本过滤器以传递给API并发送请求。

It's probably best to set a breakpoint on the line where the response variable is declared, press F10 once, then hover over the variable, so you can see what data is available for you to use in the response.

最好在声明响应变量的行上设置断点,按F10一次,然后将鼠标悬停在变量上,这样您就可以看到哪些数据可供您在响应中使用。

#5


3  

I've setup something pretty similar to the above answer in a nuGet package. It does the following: - connects to a "Service Account" you set up in the API Console - Pulls any Google Analytics data you would like - Displays that data using Google's Charts API and it does all of this in a very easy to modify way. You can see more here: https://www.nuget.org/packages/GoogleAnalytics.GoogleCharts.NET/.

我在nuGet包中设置了与上述答案非常相似的东西。它执行以下操作: - 连接到您在API控制台中设置的“服务帐户” - 提取您想要的任何Google Analytics数据 - 使用Google的图表API显示该数据,并以非常容易修改的方式完成所有这些操作。您可以在此处查看更多信息:https://www.nuget.org/packages/GoogleAnalytics.GoogleCharts.NET/。

#6


1  

Hope google will provide proper documentation someday. Here I am listing all the steps to integrate google analytics server side authentication in ASP.NET C#.

希望谷歌有一天会提供适当的文件。在这里,我列出了在ASP.NET C#中集成Google Analytics分析服务器端身份验证的所有步骤。

Step 1: Create a project in google console

第1步:在谷歌控制台中创建一个项目

Goto the link https://console.developers.google.com/iam-admin/projects and create a project by clicking on "Create Project" button and provide project name in the pop up window and submit it.

转到https://console.developers.google.com/iam-admin/projects链接并点击“创建项目”按钮创建项目,并在弹出窗口中提供项目名称并提交。

Step 2: Create credentials and service account

第2步:创建凭据和服务帐户

After creation of the project, you will be redirected to "API Manager" page. Click on credentials and press "Create Credentials" button. select "service account key" from dropdown you will be redirected to next page. In the service account drop down, select "New service account". Fill in the service account name and download the p12 key. It will have p12 extension. you will get a popup having a password "notasecret" which is default and your private key will be downloaded.

创建项目后,您将被重定向到“API Manager”页面。单击凭据,然后按“创建凭据”按钮。从下拉列表中选择“服务帐户密钥”,您将被重定向到下一页。在服务帐户下拉列表中,选择“新服务帐户”。填写服务帐户名称并下载p12密钥。它将有p12扩展名。您将获得一个密码为“notasecret”的弹出窗口,这是默认密码,您的私钥将被下载。

Step 3: Create 0auth client ID

第3步:创建0auth客户端ID

click on the "create credentials" dropdown and select "0auth client ID" you will be redirected to "0auth consent screen" tab. provide a random name in the project name textbox. select application type as "Web application" and click create button. Copy the generated client ID in a notepad.

单击“创建凭据”下拉列表并选择“0auth客户端ID”,您将被重定向到“0auth同意屏幕”选项卡。在项目名称文本框中提供随机名称。选择应用程序类型为“Web应用程序”并单击“创建”按钮。将生成的客户端ID复制到记事本中。

Step 4: Enable the APIs

第4步:启用API

On the left side click on the "Overview" tab and select "Enabled APIs" from the horizontal tab. In the search bar search for "Analytics API" click on the dropdown and press "Enable" button. Now again search for "Analytics Reporting V4" and enable it.

在左侧单击“概述”选项卡,然后从水平选项卡中选择“已启用的API”。在搜索栏中搜索“Analytics API”,单击下拉列表并按“启用”按钮。现在再次搜索“Analytics Reporting V4”并启用它。

Step 5: Install nuget packages

第5步:安装nuget包

In visual studio, Go to Tools > Nuget Package Manager > Package Manager Console. Copy paste the below code in the console to install the nuget packages.

在visual studio中,转到“工具”>“Nuget包管理器”>“包管理器控制台”。复制粘贴以下代码在控制台中安装nuget包。

Install-Package Google.Apis.Analytics.v3

安装包Google.Apis.Analytics.v3

Install-Package DotNetOpenAuth.Core -Version 4.3.4.13329

安装包DotNetOpenAuth.Core -Version 4.3.4.13329

The above two packages are Google analytics and DotNetOpenAuth nuget packages.

以上两个软件包是Google Analytics和DotNetOpenAuth nuget软件包。

Step 6: Provide 'View and Analyze' permission to service account

第6步:为服务帐户提供“查看和分析”权限

Go to google analytics account and click on "Admin" tab and select "User Management" from left menus,select a domain of which you want to access analytics data and insert the service account email id under it and select "Read and Analyze" permission from the dropdown. Service account email id looks like ex: googleanalytics@googleanalytics.iam.gserviceaccount.com.

转到Google Analytics(分析)帐户,然后单击“管理员”(Admin)选项卡并从左侧菜单中选择“用户管理”(User Management),选择要访问其分析数据的域并在其下插入服务帐户电子邮件ID,然后选择“读取和分析”权限从下拉列表。服务帐户电子邮件ID如下所示:googleanalytics@googleanalytics.iam.gserviceaccount.com。

Working Code

工作守则

FRONT END CODE:

前端代码:

Copy and paste the below analytics embed script in your front end or else you can get this code from google analytics documentation page also.

将以下分析嵌入脚本复制并粘贴到您的前端,否则您也可以从谷歌分析文档页面获取此代码。

 <script>
    (function (w, d, s, g, js, fs) {
        g = w.gapi || (w.gapi = {}); g.analytics = { q: [], ready: function (f) { this.q.push(f); } };
        js = d.createElement(s); fs = d.getElementsByTagName(s)[0];
        js.src = 'https://apis.google.com/js/platform.js';
        fs.parentNode.insertBefore(js, fs); js.onload = function () { g.load('analytics'); };
    }(window, document, 'script'));</script>

Paste the below code in the body tag of your front end page.

将以下代码粘贴到前端页面的正文标记中。

 <asp:HiddenField ID="accessToken" runat="server" />
<div id="chart-1-container" style="width:600px;border:1px solid #ccc;"></div>
        <script>
           var access_token = document.getElementById('<%= accessToken.ClientID%>').value;

            gapi.analytics.ready(function () {
                /**
                 * Authorize the user with an access token obtained server side.
                 */
                gapi.analytics.auth.authorize({
                    'serverAuth': {
                        'access_token': access_token
                    }
                });
                /**
                 * Creates a new DataChart instance showing sessions.
                 * It will be rendered inside an element with the id "chart-1-container".
                 */
                var dataChart1 = new gapi.analytics.googleCharts.DataChart({
                    query: {
                        'ids': 'ga:53861036', // VIEW ID <-- Goto your google analytics account and select the domain whose analytics data you want to display on your webpage. From the URL  ex: a507598w53044903p53861036. Copy the digits after "p". It is your view ID
                        'start-date': '2016-04-01',
                        'end-date': '2016-04-30',
                        'metrics': 'ga:sessions',
                        'dimensions': 'ga:date'
                    },
                    chart: {
                        'container': 'chart-1-container',
                        'type': 'LINE',
                        'options': {
                            'width': '100%'
                        }
                    }
                });
                dataChart1.execute();


                /**
                 * Creates a new DataChart instance showing top 5 most popular demos/tools
                 * amongst returning users only.
                 * It will be rendered inside an element with the id "chart-3-container".
                 */


            });
</script>

You can also get your View ID from https://ga-dev-tools.appspot.com/account-explorer/

您还可以从https://ga-dev-tools.appspot.com/account-explorer/获取您的View ID

BACK END CODE:

后端代码:

 using System;
    using System.Linq;
    using System.Collections.Generic;
    using System.Collections.Specialized;
    using System.Web.Script.Serialization;
    using System.Net;
    using System.Text;
    using Google.Apis.Analytics.v3;
    using Google.Apis.Analytics.v3.Data;
    using Google.Apis.Services;
    using System.Security.Cryptography.X509Certificates;
    using Google.Apis.Auth.OAuth2;
    using Google.Apis.Util;
    using DotNetOpenAuth.OAuth2;
    using System.Security.Cryptography;

    namespace googleAnalytics
    {
        public partial class api : System.Web.UI.Page
        {
            public const string SCOPE_ANALYTICS_READONLY = "https://www.googleapis.com/auth/analytics.readonly";

            string ServiceAccountUser = "googleanalytics@googleanalytics.iam.gserviceaccount.com"; //service account email ID
            string keyFile = @"D:\key.p12"; //file link to downloaded key with p12 extension
            protected void Page_Load(object sender, EventArgs e)
            {

               string Token = Convert.ToString(GetAccessToken(ServiceAccountUser, keyFile, SCOPE_ANALYTICS_READONLY));

               accessToken.Value = Token;

                var certificate = new X509Certificate2(keyFile, "notasecret", X509KeyStorageFlags.Exportable);

                var credentials = new ServiceAccountCredential(

                    new ServiceAccountCredential.Initializer(ServiceAccountUser)
                    {
                        Scopes = new[] { AnalyticsService.Scope.AnalyticsReadonly }
                    }.FromCertificate(certificate));

                var service = new AnalyticsService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credentials,
                    ApplicationName = "Google Analytics API"
                });

                string profileId = "ga:53861036";
                string startDate = "2016-04-01";
                string endDate = "2016-04-30";
                string metrics = "ga:sessions,ga:users,ga:pageviews,ga:bounceRate,ga:visits";

                DataResource.GaResource.GetRequest request = service.Data.Ga.Get(profileId, startDate, endDate, metrics);


                GaData data = request.Execute();
                List<string> ColumnName = new List<string>();
                foreach (var h in data.ColumnHeaders)
                {
                    ColumnName.Add(h.Name);
                }


                List<double> values = new List<double>();
                foreach (var row in data.Rows)
                {
                    foreach (var item in row)
                    {
                        values.Add(Convert.ToDouble(item));
                    }

                }
                values[3] = Math.Truncate(100 * values[3]) / 100;

                txtSession.Text = values[0].ToString();
                txtUsers.Text = values[1].ToString();
                txtPageViews.Text = values[2].ToString();
                txtBounceRate.Text = values[3].ToString();
                txtVisits.Text = values[4].ToString();

            }


         public static dynamic GetAccessToken(string clientIdEMail, string keyFilePath, string scope)
        {
            // certificate
            var certificate = new X509Certificate2(keyFilePath, "notasecret");

            // header
            var header = new { typ = "JWT", alg = "RS256" };

            // claimset
            var times = GetExpiryAndIssueDate();
            var claimset = new
            {
                iss = clientIdEMail,
                scope = scope,
                aud = "https://accounts.google.com/o/oauth2/token",
                iat = times[0],
                exp = times[1],
            };

            JavaScriptSerializer ser = new JavaScriptSerializer();

            // encoded header
            var headerSerialized = ser.Serialize(header);
            var headerBytes = Encoding.UTF8.GetBytes(headerSerialized);
            var headerEncoded = Convert.ToBase64String(headerBytes);

            // encoded claimset
            var claimsetSerialized = ser.Serialize(claimset);
            var claimsetBytes = Encoding.UTF8.GetBytes(claimsetSerialized);
            var claimsetEncoded = Convert.ToBase64String(claimsetBytes);

            // input
            var input = headerEncoded + "." + claimsetEncoded;
            var inputBytes = Encoding.UTF8.GetBytes(input);

            // signature
            var rsa = certificate.PrivateKey as RSACryptoServiceProvider;
            var cspParam = new CspParameters
            {
                KeyContainerName = rsa.CspKeyContainerInfo.KeyContainerName,
                KeyNumber = rsa.CspKeyContainerInfo.KeyNumber == KeyNumber.Exchange ? 1 : 2
            };
            var aescsp = new RSACryptoServiceProvider(cspParam) { PersistKeyInCsp = false };
            var signatureBytes = aescsp.SignData(inputBytes, "SHA256");
            var signatureEncoded = Convert.ToBase64String(signatureBytes);

            // jwt
            var jwt = headerEncoded + "." + claimsetEncoded + "." + signatureEncoded;

            var client = new WebClient();
            client.Encoding = Encoding.UTF8;
            var uri = "https://accounts.google.com/o/oauth2/token";
            var content = new NameValueCollection();

            content["assertion"] = jwt;
            content["grant_type"] = "urn:ietf:params:oauth:grant-type:jwt-bearer";

            string response = Encoding.UTF8.GetString(client.UploadValues(uri, "POST", content));


            var result = ser.Deserialize<dynamic>(response);

            object pulledObject = null;

            string token = "access_token";
            if (result.ContainsKey(token))
            {
                pulledObject = result[token];
            }


            //return result;
            return pulledObject;
        }

        private static int[] GetExpiryAndIssueDate()
        {
            var utc0 = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            var issueTime = DateTime.UtcNow;

            var iat = (int)issueTime.Subtract(utc0).TotalSeconds;
            var exp = (int)issueTime.AddMinutes(55).Subtract(utc0).TotalSeconds;

            return new[] { iat, exp };
        }

        }
    }

#7


0  

Another Working Approach

另一种工作方法

Add below code in the ConfigAuth

在ConfigAuth中添加以下代码

  var googleApiOptions = new GoogleOAuth2AuthenticationOptions()
        {
            AccessType = "offline", // can use only if require
            ClientId = ClientId,
            ClientSecret = ClientSecret,
            Provider = new GoogleOAuth2AuthenticationProvider()
            {
                OnAuthenticated = context =>
                {
                    context.Identity.AddClaim(new Claim("Google_AccessToken", context.AccessToken));

                    if (context.RefreshToken != null)
                    {
                        context.Identity.AddClaim(new Claim("GoogleRefreshToken", context.RefreshToken));
                    }
                    context.Identity.AddClaim(new Claim("GoogleUserId", context.Id));
                    context.Identity.AddClaim(new Claim("GoogleTokenIssuedAt", DateTime.Now.ToBinary().ToString()));
                    var expiresInSec = 10000;
                    context.Identity.AddClaim(new Claim("GoogleTokenExpiresIn", expiresInSec.ToString()));


                    return Task.FromResult(0);
                }
            },

            SignInAsAuthenticationType = DefaultAuthenticationTypes.ApplicationCookie
        };
        googleApiOptions.Scope.Add("openid"); // Need to add for google+ 
        googleApiOptions.Scope.Add("profile");// Need to add for google+ 
        googleApiOptions.Scope.Add("email");// Need to add for google+ 
        googleApiOptions.Scope.Add("https://www.googleapis.com/auth/analytics.readonly");

        app.UseGoogleAuthentication(googleApiOptions);

Add below code, name spaces and relative references

添加以下代码,名称空间和相关引用

 using Google.Apis.Analytics.v3;
 using Google.Apis.Analytics.v3.Data;
 using Google.Apis.Auth.OAuth2;
 using Google.Apis.Auth.OAuth2.Flows;
 using Google.Apis.Auth.OAuth2.Responses;
 using Google.Apis.Services;
 using Microsoft.AspNet.Identity;
 using Microsoft.Owin.Security;
 using System;
 using System.Threading.Tasks;
 using System.Web;
 using System.Web.Mvc;

public class HomeController : Controller
{
    AnalyticsService service;
    public IAuthenticationManager AuthenticationManager
    {
        get
        {
            return HttpContext.GetOwinContext().Authentication;
        }
    }

    public async Task<ActionResult> AccountList()
    {
        service = new AnalyticsService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = await GetCredentialForApiAsync(),
            ApplicationName = "Analytics API sample",
        });


        //Account List
        ManagementResource.AccountsResource.ListRequest AccountListRequest = service.Management.Accounts.List();
        //service.QuotaUser = "MyApplicationProductKey";
        Accounts AccountList = AccountListRequest.Execute();



        return View();
    }

    private async Task<UserCredential> GetCredentialForApiAsync()
    {
        var initializer = new GoogleAuthorizationCodeFlow.Initializer
        {
            ClientSecrets = new ClientSecrets
            {
                ClientId = ClientId,
                ClientSecret = ClientSecret,
            },
            Scopes = new[] { "https://www.googleapis.com/auth/analytics.readonly" }
        };
        var flow = new GoogleAuthorizationCodeFlow(initializer);

        var identity = await AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ApplicationCookie);
        if (identity == null)
        {
            Redirect("/Account/Login");
        }

        var userId = identity.FindFirstValue("GoogleUserId");

        var token = new TokenResponse()
        {
            AccessToken = identity.FindFirstValue("Google_AccessToken"),
            RefreshToken = identity.FindFirstValue("GoogleRefreshToken"),
            Issued = DateTime.FromBinary(long.Parse(identity.FindFirstValue("GoogleTokenIssuedAt"))),
            ExpiresInSeconds = long.Parse(identity.FindFirstValue("GoogleTokenExpiresIn")),
        };

        return new UserCredential(flow, userId, token);
    }
}

Add this in the Application_Start() in Global.asax

在Global.asax中的Application_Start()中添加它

  AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;