【问题标题】:How do I use a Service Account to Access the Google Analytics API V3 with .NET C#?如何使用服务帐户通过 .NET C# 访问 Google Analytics API V3?
【发布时间】:2012-10-10 10:05:04
【问题描述】:

我意识到以前有人问过这个问题,但几乎没有示例代码,所以我再次问,但至少有一点方向。

经过几个小时的搜索,我想出了以下部分实现。

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] 信息 DotNetOpenAuth - DotNetOpenAuth,版本=4.0.0.11165,文化=中性,PublicKeyToken=2780ccd10d57b246(官方) 2012-10-19 13:27:36,284 (GMT-4) [8] 调试 DotNetOpenAuth.Messaging.Channel - 准备发送 AssertionFlowMessage (2.0) 消息。 2012-10-19 13:27:36,294 (GMT-4) [8] 信息 DotNetOpenAuth.Messaging.Channel - 为https://accounts.google.com/o/oauth2/token 准备传出 AssertionFlowMessage (2.0) 消息: grant_type:断言 断言类型:http://oauth.net/grant_type/jwt/1.0/bearer 断言:(这里是一堆编码字符)

2012-10-19 13:27:36,296 (GMT-4) [8] 调试 DotNetOpenAuth.Messaging.Channel - 发送 AssertionFlowMessage 请求。 2012-10-19 13:27:36,830 (GMT-4) [8] 调试 DotNetOpenAuth.Http - HTTP POST https://accounts.google.com/o/oauth2/token 2012-10-19 13:27:36,954 (GMT-4) [8] 错误 DotNetOpenAuth.Http - 来自https://accounts.google.com/o/oauth2/token 的 WebException: { “错误”:“无效范围” }

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

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

以下是我用来启用 D​​otNetOpenAuth 日志记录的 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>

【问题讨论】:

    标签: c# .net oauth-2.0 dotnetopenauth google-analytics-api


    【解决方案1】:

    这是我在此处发布的工作示例 [1]:Automated use of google-api-dotnet-client with OAuth 2.0 我对查找和拼凑代码进行了大量研究,希望这可以节省您一些时间。

    【讨论】:

    • 我相信您在这个解决方案上投入了大量时间。看来您必须达到比我正在使用的 API 更低的级别。但是,您的示例使用的是 NativeApplicationClient 而不是 AssertionFlowClient。感谢您的反馈。
    【解决方案2】:

    以下代码,根据我原来的问题更正,基于 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();            
            }
    
        }
    }
    

    【讨论】:

    • 看起来正确的只读范围是googleapis.com/auth/analytics.readonly。这与将枚举值转换为字符串不同。另外,我不必设置 ServiceAccountUser。
    • @BenMills 你能澄清一下你是如何认证的吗?我猜您是说您将 ServiceAccountId 设置为 nnnnnnnnnnn.apps.googleusercontent.com 值,但我不确定这就是您的意思。我编辑了代码以将范围设置为“analytics.readonly”,因为这可能是人们使用它的主要方式。
    • 在命名空间 Google.Apis.Util 中有一个用于从 AnalyticsService.Scopes 枚举中检索字符串值的扩展方法 AnalyticsService.Scopes.AnalyticsReadonly.GetStringValue()。
    • @RichardCollette 也许您也应该考虑添加标志 X509KeyStorageFlags.MachineKeySet ?否则,应用程序池身份需要一个可以存储证书的配置文件。 new X509Certificate2(@"value-privatekey.p12", "notasecret", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet)
    • 请注意,此示例代码使用截至 2015 年的过时代码。例如,已删除 AssertionFlowClient。我建议改用以下 Ramy 的解决方案:stackoverflow.com/a/21445472/2440
    【解决方案3】:

    关于 Richard Collette 的回答,如果您想在 READONLY 模式下使用 Analytics API,请注意使用他的方法,正确的使用方法是:

    string Scope = "analytics.readonly"
    

    而不是

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

    因为他似乎说有一个错误。实际上,错误在于.toString() 方法返回analyticsreadonly 而不是analytics.readonly,这是Google 喜欢的方式。就是这样。

    【讨论】:

    • 很好的信息。我会说这是枚举中的一个错误。如果您不能使用这些枚举,它们还有什么意义?
    • @RichardCollette 在命名空间 Google.Apis.Util 中有一个用于从 AnalyticsService.Scopes 枚举中检索字符串值的扩展方法 AnalyticsService.Scopes.AnalyticsReadonly.GetStringValue()。
    【解决方案4】:
    string scope = Google.Apis.Util.Utilities.GetStringValue(AnalyticsService.Scopes.AnalyticsReadonly);
    

    【讨论】:

    • 这是一种扩展方法。你不需要这样称呼它。请参阅上面的解决方案。
    【解决方案5】:

    我昨天查看了分析 API,发现它没有记录,也没有样本等。

    无论如何,我创建了一个库,您可以使用它通过几行轻松访问分析,并将返回的数据直接数据绑定到 DataTables,它在 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 文档和资源化的 Metrics、Dimensions、Calculated Features 在我从物理类生成的 XML 中,您可以像上面的示例一样直接使用它很有趣:) 享受

    https://github.com/rmostafa/DotNetAnalyticsAPI

    【讨论】:

      猜你喜欢
      • 2017-08-31
      • 2012-09-30
      • 2013-08-30
      • 2020-07-14
      • 2021-09-05
      • 1970-01-01
      • 2015-02-12
      • 2014-12-17
      • 2019-01-05
      相关资源
      最近更新 更多