如何使用服务帐户在.NET C#中访问Google Analytics API V3?

16

我意识到此问题曾经被问到过,但是缺乏示例代码,因此我再次提问,至少有一点方向。

搜索了数小时后,我得出了以下部分实现。

namespace GoogleAnalyticsAPITest.Console
{
    using System.Security.Cryptography.X509Certificates;
    using DotNetOpenAuth.OAuth2;
    using Google.Apis.Analytics.v3;
    using Google.Apis.Analytics.v3.Data;
    using Google.Apis.Authentication.OAuth2;
    using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;

    class Program
    {
        static void Main(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure();
            string Scope = Google.Apis.Analytics.v3.AnalyticsService.Scopes.Analytics.ToString().ToLower();
            string scopeUrl = "https://www.googleapis.com/auth/" + Scope;
            const string ServiceAccountId = "nnnnnnnnnnn.apps.googleusercontent.com";
            const string ServiceAccountUser = "nnnnnnnnnnn@developer.gserviceaccount.com";
            AssertionFlowClient client = new AssertionFlowClient(
                GoogleAuthenticationServer.Description, new X509Certificate2(@"7039572692013fc5deada350904f55bad2588a2a-privatekey.p12", "notasecret", X509KeyStorageFlags.Exportable))
            {
                Scope = scopeUrl,
                ServiceAccountId = ServiceAccountId//,ServiceAccountUser = ServiceAccountUser
            };
            IAuthorizationState state = AssertionFlowClient.GetState(client);
            AnalyticsService service = new AnalyticsService(authenticator);
            string profileId = "ga:xxxxxxxx";
            string startDate = "2010-10-01";
            string endDate = "2010-10-18";
            string metrics = "ga:visits";
            DataResource.GaResource.GetRequest request = service.Data.Ga.Get(profileId, startDate, endDate, metrics);
            request.Dimensions = "ga:date";
            GaData data = request.Fetch();
        }
    }
}

我有几个问题。调用AssertionFlowClient.GetState(client)会导致“invalid_scope”响应,如DotNetOpenAuth日志中所见:

2012-10-19 13:27:36,272 (GMT-4) [8] INFO DotNetOpenAuth - DotNetOpenAuth, Version=4.0.0.11165, Culture=neutral, PublicKeyToken=2780ccd10d57b246 (official) 2012-10-19 13:27:36,284 (GMT-4) [8] DEBUG DotNetOpenAuth.Messaging.Channel - 准备发送 AssertionFlowMessage (2.0) 消息。 2012-10-19 13:27:36,294 (GMT-4) [8] INFO DotNetOpenAuth.Messaging.Channel - 为 https://accounts.google.com/o/oauth2/token 准备了一个传出的 AssertionFlowMessage (2.0) 消息: grant_type: assertion assertion_type: http://oauth.net/grant_type/jwt/1.0/bearer assertion:(一大串编码字符在这里)

2012-10-19 13:27:36,296 (GMT-4) [8] DEBUG DotNetOpenAuth.Messaging.Channel - 发送 AssertionFlowMessage 请求。 2012-10-19 13:27:36,830 (GMT-4) [8] DEBUG DotNetOpenAuth.Http - HTTP POST https://accounts.google.com/o/oauth2/token 2012-10-19 13:27:36,954 (GMT-4) [8] ERROR DotNetOpenAuth.Http - 来自https://accounts.google.com/o/oauth2/token的WebException: { "error" : "invalid_scope" }

我已尝试指定ServiceAccountId和ServiceAccountUser中的一个或两个,但没有成功。

其次,即使我获得了IAuthorizationState,我也不确定如何获得可以传递给AnalyticsService构造函数的IAuthenticator。

以下是我用来启用DotNetOpenAuth日志记录的web.config。

<?xml version="1.0"?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net, Version=1.2.10.0, Culture=neutral, publicKeyToken=1b44e1d426115821" />
    <!--<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler" requirePermission="false"/>-->
    <sectionGroup name="dotNetOpenAuth" type="DotNetOpenAuth.Configuration.DotNetOpenAuthSection, DotNetOpenAuth">
      <section name="openid" type="DotNetOpenAuth.Configuration.OpenIdElement, DotNetOpenAuth" requirePermission="false" allowLocation="true"/>
      <section name="oauth" type="DotNetOpenAuth.Configuration.OAuthElement, DotNetOpenAuth" requirePermission="false" allowLocation="true"/>
      <section name="messaging" type="DotNetOpenAuth.Configuration.MessagingElement, DotNetOpenAuth" requirePermission="false" allowLocation="true"/>
      <section name="reporting" type="DotNetOpenAuth.Configuration.ReportingElement, DotNetOpenAuth" requirePermission="false" allowLocation="true"/>
    </sectionGroup>
  </configSections>
  <log4net>
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="DotNetOpenAuth.log"/>
      <appendToFile value="true"/>
      <rollingStyle value="Size"/>
      <maxSizeRollBackups value="10"/>
      <maximumFileSize value="100KB"/>
      <staticLogFileName value="true"/>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date (GMT%date{%z}) [%thread] %-5level %logger - %message%newline"/>
      </layout>
    </appender>
    <appender name="TracePageAppender" type="OpenIdProviderWebForms.Code.TracePageAppender, OpenIdProviderWebForms">
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date (GMT%date{%z}) [%thread] %-5level %logger - %message%newline"/>
      </layout>
    </appender>
    <!-- Setup the root category, add the appenders and set the default level -->
    <root>
      <level value="ALL"/>
      <appender-ref ref="RollingFileAppender"/>
      <appender-ref ref="TracePageAppender"/>
    </root>
    <!-- Specify the level for some specific categories -->
    <logger name="DotNetOpenAuth">
      <level value="ALL"/>
    </logger>
  </log4net>
  <dotNetOpenAuth>
    <!-- This is an optional configuration section where aspects of dotnetopenauth can be customized. -->
    <!-- For a complete set of configuration options see http://www.dotnetopenauth.net/developers/code-snippets/configuration-options/ -->
    <!--<messaging clockSkew="00:10:00" lifetime="00:03:00" strict="true">-->
    <!--<messaging>
      <untrustedWebRequest timeout="00:00:30" readWriteTimeout="00:00:01.500" maximumBytesToRead="1048576" maximumRedirections="10">
        <whitelistHosts>
          -->
    <!-- Uncomment to enable communication with localhost (should generally not activate in production!) -->
    <!--
          <add name="localhost"/>            
        </whitelistHosts>
      </untrustedWebRequest>
    </messaging>-->
    <!-- Allow DotNetOpenAuth to publish usage statistics to library authors to improve the library. -->
    <reporting enabled="false"/>
  </dotNetOpenAuth>
  <appSettings>
    <!--<add key="log4net.Internal.Debug" value="true" />-->
  </appSettings>
  <runtime>
  </runtime>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
  </startup>
</configuration>
5个回答

11
以下代码是我原来提问中纠正后的版本,基于Ian Fraser提供的示例:

https://groups.google.com/forum/#!msg/google-search-api-for-shopping/4uUGirzH4Rw/__c0e4hj0ekJ

他的代码解决了三个问题:

  1. 看起来AnalyticsService.Scopes.AnalyticsReadonly不起作用,至少对我或我的方式不起作用。
  2. 由于某种原因,必须将ServiceAccountUser分配给AssertionFlowClient实例的ServiceAccountId属性。
  3. OAuth2Authenticator提供了我正在寻找的IAuthenticator。

在您的项目中,包括对以下内容的引用:

  • Lib\DotNetOpenAuth.dll
  • Lib\Google.Apis.dll
  • Lib\Google.Apis.Authentication.OAuth2.dll
  • Services\AnalyticsService\Google.Apis.Analytics.v3.dll

-

namespace GoogleAnalyticsAPITest.Console
{
    using System.Security.Cryptography.X509Certificates;
    using Google.Apis.Analytics.v3;
    using Google.Apis.Analytics.v3.Data;
    using Google.Apis.Authentication.OAuth2;
    using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
    using Google.Apis.Util;

    class Program
    {
        static void Main(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure();            
            const string ServiceAccountId = "nnnnnnnnnnn.apps.googleusercontent.com";
            const string ServiceAccountUser = "nnnnnnnnnnn@developer.gserviceaccount.com";
            AssertionFlowClient client = new AssertionFlowClient(
                GoogleAuthenticationServer.Description, new X509Certificate2(@"value-privatekey.p12", "notasecret", X509KeyStorageFlags.Exportable))
            {
                Scope = AnalyticsService.Scopes.AnalyticsReadonly.GetStringValue(),
                ServiceAccountId = ServiceAccountUser //Bug, why does ServiceAccountUser have to be assigned to ServiceAccountId
                //,ServiceAccountUser = ServiceAccountUser
            };
            OAuth2Authenticator<AssertionFlowClient> authenticator = new OAuth2Authenticator<AssertionFlowClient>(client, AssertionFlowClient.GetState);            
            AnalyticsService service = new AnalyticsService(authenticator);            
            string profileId = "ga:64968920";
            string startDate = "2010-10-01";
            string endDate = "2010-10-31";
            string metrics = "ga:visits";
            DataResource.GaResource.GetRequest request = service.Data.Ga.Get(profileId, startDate, endDate, metrics);
            request.Dimensions = "ga:date";
            GaData data = request.Fetch();            
        }

    }
}

1
在命名空间Google.Apis.Util中,有一个扩展方法用于从AnalyticsService.Scopes枚举中检索字符串值,即AnalyticsService.Scopes.AnalyticsReadonly.GetStringValue()。 - Johan Petersson
3
@RichardCollette,也许你应该考虑添加标志X509KeyStorageFlags.MachineKeySet?否则,应用程序池身份需要一个可以存储证书的配置文件。新的X509Certificate2(@"value-privatekey.p12","notasecret",X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet) - Johan Petersson
@JohanPettersson - 理解你的意见,这只是一个快速上手并获取数据的示例。 - Richard Collette
@Richard Collette 谢谢,我已经让它工作了。现在只是遇到了一个权限被拒绝的错误,但这应该很容易解决。问题:这段代码是否也可以用于请求YouTube分析API和YouTube数据API的数据? - tutu
1
请注意,此示例代码使用的是2015年已过时的代码。例如,AssertionFlowClient已被移除。我建议使用下面Ramy的解决方案代替:https://dev59.com/Kuo6XIcBkEYKwwoYPR_f#21445472 - Sire
显示剩余6条评论

5
我昨天查看了分析API,并注意到它的文档不完整,也没有示例等等。无论如何,我创建了一个库,您可以使用它轻松访问分析,仅需要几行代码就可以将数据直接绑定到DataTable中。这是开源的,您可以在GitHub上自由贡献 :)

https://github.com/rmostafa/DotNetAnalyticsAPI

使用方法

Analytics.AnalyticsManager manager = new Analytics.AnalyticsManager(Server.MapPath("~/bin/privatekey.p12"), "YOUR_EMAIL");
            manager.LoadAnalyticsProfiles();


List<Analytics.Data.DataItem> metrics = new List<Analytics.Data.DataItem>();
metrics.Add(Analytics.Data.Visitor.Metrics.visitors);
metrics.Add(Analytics.Data.Session.Metrics.visits);
List<Analytics.Data.DataItem> dimensions = new List<Analytics.Data.DataItem>();
dimensions.Add(Analytics.Data.GeoNetwork.Dimensions.country);
dimensions.Add(Analytics.Data.GeoNetwork.Dimensions.city);


System.Data.DataTable table = manager.GetGaDataTable(DateTime.Today.AddDays(-3), DateTime.Today, metrics, dimensions, null, metrics);

所有的 Google API 报告指令都有直接的代码映射,按照 API 分类方式归类,因此您甚至可以不阅读 API 文档就使用它,因为所有功能都在属性中记录,我编写了解析完整 API 文档并提取指标、维度、计算特性的代码,并将其资源化为 XML,从物理类生成,您可以像上面的示例一样直接使用它们,很有趣!享受吧。

https://github.com/rmostafa/DotNetAnalyticsAPI


3
string scope = Google.Apis.Util.Utilities.GetStringValue(AnalyticsService.Scopes.AnalyticsReadonly);

这是一个扩展方法。您不需要以这种方式调用它。请参见上面的解决方案。 - Richard Collette

2

我相信你在这个解决方案上花了很多时间。看起来你不得不比我使用的API更底层。然而,你的示例中使用的是NativeApplicationClient而不是AssertionFlowClient。我很感谢你的反馈。 - Richard Collette

1
关于Richard Collette的回答,请注意,如果您想在READONLY模式下使用Analytics API,则正确的使用方法是:
string Scope = "analytics.readonly"

而不是

string Scope = AnalyticsService.Scopes.AnalyticsReadOnly.ToString().ToLower()

他似乎在说有个漏洞。实际上,这个漏洞是由于 .toString() 方法返回了 analyticsreadonly,而不是 Google 喜欢的 analytics.readonly。就是这样。


1
很棒的信息。我会说这是枚举中的一个错误。如果你不能使用它们,那么这些枚举有什么意义呢? - Richard Collette
1
在名为Google.Apis.Util的命名空间中,有一个扩展方法用于从AnalyticsService.Scopes枚举中检索字符串值,即AnalyticsService.Scopes.AnalyticsReadonly.GetStringValue()。 - Johan Petersson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接