如何使用其.NET API的v3检索Google Analytics报告数据?

我一直在尝试使用他们提供的.NET api检索谷歌分析报告,并且真的一直在试图我如何使用最新版本v3检索任何内容,这可以在这里找到: http : //code.google.com /apis/analytics/docs/gdata/v3/gdataLibraries.html

例如,我想检索一个类似这样的报告查询: https : //www.google.com/analytics/feeds/data?dimensions = ga :浏览器&end-date = 2012-01-25&ids=ga : ACCOUNTID&metrics= GA:探访&开始日期= 2011-12-25

我能够使用版本2使用GData返回报告,但是希望在版本2被弃用的情况下获得版本3,但是看到有意义的文档似乎已经过时或不存在而且很困难。我找不到任何例子。

我们刚刚更新了我们的分析服务以使用API​​的v3.0,因为v2.3现已弃用,Google上有迁移指南https://developers.google.com/analytics/resources/articles/gdata-migration -guide可能有所帮助。

我尝试使用支持v3的google dotnet API http://code.google.com/p/google-api-dotnet-client/但由于缺少文档和示例而放弃了。 我们通过net.httpwebrequest调用api,这比尝试解决API中发生的事情更容易。

对于v3,您的电话应该是https://www.googleapis.com/analytics/v3/data/ga?dimensions=ga:browser&end-date=2012-01-25&ids=ga:ACCOUNTID&metrics=ga:visits&start-date=2011 -12-25

现在, 使用最新版本的.NET API ( v1.3.0.15233 )可以轻松实现这一点。 虽然已经发布但没有任何示例,但您可以使用Task示例作为模式来查询GA数据。

以下是您需要添加/更改以使该示例项目适用于GA的内容。

声明AnalyticsService的实例

 private static AnalyticsService _analyticsService; 

将范围更改为Scopes.Analytics

GetAuthorization方法中声明了一个变量scope 。 改变它

 string scope = TasksService.Scopes.TasksReadonly.GetStringValue(); 

 string scope = AnalyticsService.Scopes.Analytics.GetStringValue(); 

初始化您的GA服务

 if (_analyticsService == null) { _analyticsService = new AnalyticsService(new BaseClientService.Initializer() { Authenticator = _authenticator = CreateAuthenticator(); }); } 

进行查询

这是您查询GA配置文件的方法

 // make a request var request = _analyticsService.Data.Ga.Get( "ga:12345678", "2013-01-01", "2013-05-08", "ga:visits,ga:bounces,ga:timeOnSite,ga:avgTimeOnSite"); // run the request and get the data var data = request.Fetch(); 

您会注意到GetRequest有四个必需参数,类似于API Doc中定义的参数。 您可以访问查询资源管理器以了解要与.NET API一起使用的有效指标。

经过几天的搜索实现访问Analitycs,是一个控制台项目框架3.5。

*您必须拥有激活Analytics API服务的Google API控制台项目。
*在Simple API Access中,必须为已安装的应用程序生成Client ID的新密钥。
*下载并添加对Google.Apis.Analytics.v3.dll的引用
*下载并添加对Google.Apis.Authentication.OAuth2.dll的引用
*下载并添加对Google.Apis.dll的引用
*下载并添加对Newtonsoft.Json.Net35.dll的引用
*下载并添加对DotNetOpenAuth.dll的引用

最后实现以下代码:

 private const string Scope = "https://www.googleapis.com/auth/analytics.readonly"; static void Main(string[] args) { try { var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description); provider.ClientIdentifier = "Your_Client_ID"; provider.ClientSecret = "Your_Client_Secret"; var auth = new OAuth2Authenticator(provider, GetAuthentication); var asv = new AnalyticsService(auth); var request = asv.Data.Ga.Get("ga:Your_TrackingID", "2013-08-05", "2013-08-05", "ga:visitors"); request.Dimensions = "ga:visitorType"; var report = request.Fetch(); var rows = report.Rows; var newVisitors = rows[0]; var returnVisitors = rows[1]; Console.WriteLine(newVisitors[0] + ": " + newVisitors[1]); Console.WriteLine(returnVisitors[0] + ": " + returnVisitors[1]); int newV = Int32.Parse(newVisitors[1]); int retV = Int32.Parse(returnVisitors[1]); int sum = newV + retV; Console.WriteLine("Total: " + sum); } catch(Exception ex){ Console.WriteLine("\n Error: \n" + ex); Console.ReadLine(); } } private static IAuthorizationState GetAuthentication(NativeApplicationClient arg) { IAuthorizationState state = new AuthorizationState(new[] { Scope }); state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl); Uri authUri = arg.RequestUserAuthorization(state); System.Diagnostics.Process.Start(authUri.ToString()); Console.Write("Paste authorization code: "); string authCode = Console.ReadLine(); return arg.ProcessUserAuthorization(authCode, state); } 

希望这可以帮助。

我在此处发布了有关如何执行此操作的分步说明: Google V3 Beta API如何操作

服务帐户的附加完整示例。

安装nuget包Google.Apis.Analytics.v3。

 //based on https://github.com/LindaLawton/Google-Dotnet-Samples/tree/master/Google-Analytics using System; using System.Threading.Tasks; using System.Security.Cryptography.X509Certificates; using Google.Apis.Analytics.v3; using Google.Apis.Analytics.v3.Data; using Google.Apis.Auth.OAuth2; using Google.Apis.Util; using System.Collections.Generic; using Google.Apis.Services; namespace GAImport { class Program { static void Main(string[] args) { string[] scopes = new string[] { AnalyticsService.Scope.AnalyticsReadonly }; var keyFilePath = @"path\to\key.p12"; var serviceAccountEmail = "someuser@....gserviceaccount.com"; //loading the Key file var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable); var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = scopes }.FromCertificate(certificate)); var service = new AnalyticsService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "Analytics API Sample", }); var request = service.Data.Ga.Get("ga:1234567", "30daysAgo", "yesterday", "ga:sessions"); request.MaxResults = 1000; var result = request.Execute(); foreach (var headers in result.ColumnHeaders) { Console.WriteLine(String.Format("{0} - {1} - {2}", headers.Name, headers.ColumnType, headers.DataType)); } foreach (List row in result.Rows) { foreach (string col in row) { Console.Write(col + " "); } Console.Write("\r\n"); } Console.ReadLine(); } } }