【问题标题】:How do I retrieve Google Analytics report data using v3 of their .NET api?如何使用他们的 .NET api 的 v3 检索 Google Analytics 报告数据?
【发布时间】:2012-01-24 23:19:50
【问题描述】:

我一直在尝试使用他们提供的 .NET api 检索 Google 分析报告,并且一直在摸索如何使用最新版本 v3 实际检索任何内容,该版本可在此处获得:http://code.google.com/apis/analytics/docs/gdata/v3/gdataLibraries.html

例如,我想检索这样一个报告查询:https://www.google.com/analytics/feeds/data?dimensions=ga:browser&end-date=2012-01-25&ids=ga:ACCOUNTID&metrics=ga:visits&start-date=2011-12-25

我能够使用使用 GData 的版本 2 很好地返回报告,但希望在版本 2 被弃用的情况下继续使用版本 3,但是在看到有意义的文档似乎已经过时或没有时遇到了很多麻烦-existant,但我找不到任何示例。

【问题讨论】:

  • 真的吗?我的问题是在您链接到的问题前 3 个月发布的。

标签: c# asp.net .net google-analytics-api google-api-client


【解决方案1】:

现在可以使用the latest release of the .NET API (v1.3.0.15233) 轻松实现这一点。虽然没有发布示例,但您可以使用the Task sample 作为模式来查询 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 文档中定义的参数。您可以visit the query explorer 了解与 .NET API 一起使用的有效指标。

【讨论】:

  • 是否已弃用用于拨打电话的旧 Google.GData.Analytics.dll 文件?使用这些 dll 编写的用于获取数据的代码会发生什么情况?
【解决方案2】:

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

* 您必须有一个激活了 Analytics API 服务的 google APIs 控制台项目。
* 在简单 API 访问中,必须为已安装应用程序的客户端 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<NativeApplicationClient>(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);
    }

希望这会有所帮助。

【讨论】:

    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

      带有服务帐户的其他完整示例。

      安装 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<string> row in result.Rows)
                  {
                      foreach (string col in row)
                      {
                          Console.Write(col + " "); 
                      }
                      Console.Write("\r\n");
      
                  }
      
      
                  Console.ReadLine();
              }
      
          }
      }
      

      【讨论】:

        【解决方案5】:

        我们刚刚更新了我们的分析服务以使用 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

        【讨论】:

        • 您愿意在某处分享此代码吗? gist.github.com 或博客文章?谢谢
        • 虽然我仍然想知道如何使用 Google 提供的框架来做到这一点,但我会接受这个作为答案,因为其他人似乎没有任何想法。感谢您的努力。
        猜你喜欢
        • 1970-01-01
        • 2014-03-23
        • 2014-03-29
        • 2012-12-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-03
        • 2017-04-27
        相关资源
        最近更新 更多