如何使用服务帐户通过 .NET C# 访问 Google Analytics API V3? [英] How do I use a Service Account to Access the Google Analytics API V3 with .NET C#?

查看:15
本文介绍了如何使用服务帐户通过 .NET C# 访问 Google Analytics API V3?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我意识到之前有人问过这个问题,但示例代码的方式很少,所以我再次询问,但至少有一点方向.

I realized this question has been previously asked but with little in the way of example code, so I am asking again but with at least a little bit of direction.

经过数小时的搜索,我想出了以下部分实现.

After hours of searching, I have come up with the following partial implementation.

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"响应,如

I have a couple issues. The call to AssertionFlowClient.GetState(client) results in a "invalid_scope" response as seen in the DotNetOpenAuth log of

2012-10-19 13:27:36,272 (GMT-4) [8] 信息 DotNetOpenAuth - DotNetOpenAuth,版本=4.0.0.11165,Culture=neutral,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] INFO DotNetOpenAuth.Messaging.Channel - 为 https://accounts.google.com/o/oauth2/token:grant_type:断言assertion_type:http://oauth.net/grant_type/jwt/1.0/bearer断言:(一堆编码字符放在这里)

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 - Preparing to send AssertionFlowMessage (2.0) message. 2012-10-19 13:27:36,294 (GMT-4) [8] INFO DotNetOpenAuth.Messaging.Channel - Prepared outgoing AssertionFlowMessage (2.0) message for https://accounts.google.com/o/oauth2/token: grant_type: assertion assertion_type: http://oauth.net/grant_type/jwt/1.0/bearer assertion: (a bunch of encoded characters go here)

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/token2012-10-19 13:27:36,954 (GMT-4) [8] 错误 DotNetOpenAuth.Http - WebException from https:///accounts.google.com/o/oauth2/token:{错误":invalid_scope"}

2012-10-19 13:27:36,296 (GMT-4) [8] DEBUG DotNetOpenAuth.Messaging.Channel - Sending AssertionFlowMessage request. 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 - WebException from https://accounts.google.com/o/oauth2/token: { "error" : "invalid_scope" }

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

I have tried specifying one or both of ServiceAccountId and ServiceAccountUser with no luck.

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

Second, even if I get an IAuthorizationState, I am not sure how I get an IAuthenticator that can be passed to the AnalyticsService constructor.

以下是我用来启用 D​​otNetOpenAuth 日志记录的 web.config.

The following is the web.config I use to enable DotNetOpenAuth logging.

<?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>

推荐答案

以下代码从我的原始问题中更正,基于 Ian Fraser 提供的示例:

The following code, corrected from my original question, is based on the example provided by Ian Fraser at:

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

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

His code addressed three issues:

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

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

In your project, include references to:

  • LibDotNetOpenAuth.dll
  • LibGoogle.Apis.dll
  • LibGoogle.Apis.Authentication.OAuth2.dll
  • ServicesAnalyticsServiceGoogle.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();            
        }

    }
}

这篇关于如何使用服务帐户通过 .NET C# 访问 Google Analytics API V3?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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