.NET的Analytics Reporting API V4客户端库 [英] Analytics Reporting API V4 Client Library for .NET

查看:96
本文介绍了.NET的Analytics Reporting API V4客户端库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从我们的Google Analytics(分析)实例中获取一些数据,并且我想使用.NET的Analytics Reporting API V4客户端库(


  1. 在左侧,点击凭据,然后创建一个名为 Google Analytics(分析)API控制台的新项目。给它一些时间来创建新项目。


  2. 创建项目后,如果尚未选择凭据,请再次单击它。 ,然后单击右侧面板中的 OAuth同意屏幕链接。将显示给用户的产品名称设置为 Google Analytics API控制台,然后单击保存。


  3. 再次单击凭据,然后单击创建凭据,然后选择 OAuth客户端ID 。为应用程序类型选择 Other ,然后输入 Google Analytics API控制台作为名称,然后单击创建


  4. 创建凭据后,将显示一个客户端ID和一个客户端密码。您可以关闭对话框窗口。


  5. 现在,在凭据下,您应该在 OAuth 2.0客户端ID 。单击该条目最右边的下载图标,以下载 client_secret.json 文件(此文件的名称将更长)。下载该文件后,将其添加到根级别的项目中,并将其重命名为 client_secret.json



  1. 现在,已经创建了OAuth 2.0凭据,我们需要启用它以调用Reporting API。选择概述,并确保在右侧面板中选择了 Google API 。在搜索框中输入 Reporting ,然后从列表中选择 Analytics Reporting API V4 。在下一个屏幕上,点击启用。启用此API后,您应该可以在右侧面板的 Enabled API 列表中看到它。



现在我们已经创建了项目并创建了OAuth 2.0凭据,现在该了调用Reporting API V4。下面列出的代码将使用Google API和 client_secret.json 文件创建 Google.Apis.Auth.OAuth2.UserCredential 来查询报表API,以查看视图在给定日期范围之间的所有会话。该代码改编自



请注意,我认为这种情况将满足OP的需求。如果要将此应用程序分发给客户端,则很可能需要使用其他OAuth 2.0方案。



这是代码:

 使用系统; 
使用System.Collections.Generic;
使用System.IO;
使用System.Linq;
使用System.Threading;
使用System.Threading.Tasks;
使用Google.Apis.AnalyticsReporting.v4;
使用Google.Apis.AnalyticsReporting.v4.Data;
使用Google.Apis.Auth.OAuth2;
使用Google.Apis.Services;
使用Google.Apis.Util.Store;

命名空间GoogleAnalyticsApiConsole
{
class Program
{
static void Main(string [] args)
{
try
{
var credential = GetCredential()。Result;
using(var svc = new AnalyticsReportingService(
new BaseClientService.Initializer
{
HttpClientInitializer =凭据,
ApplicationName = Google Analytics API控制台
} ))
{
var dateRange =新的DateRange
{
StartDate = 2016-05-01,
EndDate = 2016-05-31
};
var会话=新指标
{
Expression = ga:sessions,
Alias = Sessions
};
var date = new Dimension {Name = ga:date};

var reportRequest = new ReportRequest
{
DateRanges = new List< DateRange> {dateRange},
Dimensions = new List< Dimension> {date},
Metrics = new List< Metric> {个会话},
ViewId =<<您的视图ID>>
};
var getReportsRequest = new GetReportsRequest {
ReportRequests = new List< ReportRequest> {reportRequest}};
var batchRequest = svc.Reports.BatchGet(getReportsRequest);
var response = batchRequest.Execute();
foreach(响应时为varx。Reports.First()。Data.Rows)
{
Console.WriteLine(string.Join(,,x.Dimensions)+
+ string.Join(,,x.Metrics.First()。Values));
}
}
}
catch(例外)
{
Console.WriteLine(ex.ToString());
}
}

静态异步任务< UserCredential> GetCredential()
{
using(var stream = new FileStream( client_secret.json,
FileMode.Open,FileAccess.Read))
{
const字符串loginEmailAddress =<<您的帐户电子邮件地址>>;
return等待a GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
新[] {AnalyticsReportingService.Scope.Analytics},
loginEmailAddress,CancellationToken.None,
新FileDataStore( GoogleAnalyticsApiConsole));
}
}
}
}


I'm trying to get some data from our google analytics instance and I'd like to use the Analytics Reporting API V4 Client Library for .NET (https://developers.google.com/api-client-library/dotnet/apis/analyticsreporting/v4) so that I can bake some of this data into an administration site we have built. I'm having trouble finding any examples of using this code and the documentation seems to be incredibly sparse. I would like to use a service account to authorize as we only need to view data associated with the analytics account which we control.

If anyone could provide some sample code or point me in the right direction to get some basic report data using the .net api, it would be greatly appreciated

解决方案

Calling the Google Analytics Reporting API from C# is not particularly difficult, however all of the necessary steps do not seem to be outlined very clearly in the Google Analytics API documentation. I will try to list them all out here. While YMMV, I believe these steps to be correct as of 7/20/2016.

You can start by creating a new C# project. We'll make a console application to test called GoogleAnalyticsApiConsole. Once the project is created, we'll add a reference to the Google Analytics Reporting API V4 Client Library for .NET using the NuGet Package Manager Console (found under the Tools menu in Visual Studio 2015). Fire up the Console and issue the following command at the PM> prompt:

PM> Install-Package Google.Apis.AnalyticsReporting.v4

Installing that package will download the client libraries needed to call the Google Analytics Reporting web services along with a number of other dependencies.

In order to call the web services, you'll need to set up OAuth 2.0 access for your application. The documentation for this setup can be found here, but I will summarize below:

  1. Login to the Google Cloud Platform Console: https://console.cloud.google.com/. Be sure to login with an account that has access to the Google Analytics accounts you are trying to query with the reporting API.

  2. Click the Google Cloud Platform menu and select API Manager.

  1. On the left hand side, click Credentials and then create a new project called Google Analytics API Console. Give it some time to create the new project.

  2. After the project is created, click Credentials again if it is not already selected, and then click the OAuth Consent Screen link in the right panel. Set the Product name shown to users to Google Analytics API Console and then click Save.

  3. Click Credentials again, and then click Create Credentials, and choose OAuth Client ID. Select Other for Application type and then enter Google Analytics API Console as the Name and click Create.

  4. After the credential is created, you will be presented with a client ID and a client secret. You can close the dialog window.

  5. Now, under Credentials you should see an entry under OAuth 2.0 client ids. Click the download icon to the far right of that entry to download the client_secret.json file (this file will have a much longer name). Add that file to your project at the root level once it has been downloaded and rename it to client_secret.json.

  1. Now that the OAuth 2.0 credential has been created, we need to enable it to call the Reporting API. Select Overview and make sure Google APIs is selected in the right panel. Type in Reporting in the search box and select Analytics Reporting API V4 from the list. On the next screen, click Enable. Once this API has been enabled, you should be able to see it under the Enabled APIs list in the right panel.

Now that we've created our project and created our OAuth 2.0 credential, it is time to call the Reporting API V4. The code listed below will use the Google API and the client_secret.json file to create a Google.Apis.Auth.OAuth2.UserCredential to query the Reporting API for all sessions between the given date range for a View. The code is adapted from the Java example here.

Before executing the code, be sure to set the Build Action on the client_secret.json file to Content and the Copy to Output Directory setting to Copy if newer. There are also two variables that need to be properly set. First, in the GetCredential() method, set the loginEmailAddress value to the email address used to create the OAuth 2.0 credential. Then, in the Main method, be sure to set the ViewId in the reportRequest variable to the view that you want to query using the Reporting API. To find the ViewId, log in to Google Analytics and select the Admin tab. From there, select the view you want to query in the View dropdown on the far right and select View Settings. The View ID will be displayed under Basic Settings.

The first time the code is executed, it will bring up a web page asking if you want to allow the Google Analytics API Console to have access to the API data. Select Allow to proceed. From then on that permission will be stored in the GoogleAnalyticsApiConsole FileDataStore. If that file is deleted, then permission will need to be granted again. That file can be found in the %APPDATA%\GoogleAnalyicsApiConsole directory.

Please note that I believe this scenario will meet the needs of the OP. If this application were to be distributed to clients, then a different OAuth 2.0 scheme would most likely be necessary.

Here is the code:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Google.Apis.AnalyticsReporting.v4;
using Google.Apis.AnalyticsReporting.v4.Data;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Util.Store;

namespace GoogleAnalyticsApiConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                var credential = GetCredential().Result;
                using(var svc = new AnalyticsReportingService(
                    new BaseClientService.Initializer
                    {
                        HttpClientInitializer = credential,
                        ApplicationName = "Google Analytics API Console"
                    }))
                {    
                    var dateRange = new DateRange
                    {
                        StartDate = "2016-05-01",
                        EndDate = "2016-05-31"
                    };
                    var sessions = new Metric
                    {
                        Expression = "ga:sessions",
                        Alias = "Sessions"
                    };
                    var date = new Dimension { Name = "ga:date" };

                    var reportRequest = new ReportRequest
                    {
                        DateRanges = new List<DateRange> { dateRange },
                        Dimensions = new List<Dimension> { date },
                        Metrics = new List<Metric> { sessions },
                        ViewId = "<<your view id>>"
                    };
                    var getReportsRequest = new GetReportsRequest {
                        ReportRequests = new List<ReportRequest> { reportRequest } };
                    var batchRequest = svc.Reports.BatchGet(getReportsRequest);
                    var response = batchRequest.Execute();
                    foreach (var x in response.Reports.First().Data.Rows)
                    {
                        Console.WriteLine(string.Join(", ", x.Dimensions) +
                        "   " + string.Join(", ", x.Metrics.First().Values));
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }

        static async Task<UserCredential> GetCredential()
        {
            using (var stream = new FileStream("client_secret.json", 
                 FileMode.Open, FileAccess.Read))
            {
                const string loginEmailAddress = "<<your account email address>>";
                return await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    new[] { AnalyticsReportingService.Scope.Analytics },
                    loginEmailAddress, CancellationToken.None, 
                    new FileDataStore("GoogleAnalyticsApiConsole"));
            }
        }
    }
}

这篇关于.NET的Analytics Reporting API V4客户端库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆