如何使用服务帐户访问与.NET C#的谷歌Analytics(分析)API V3?(How do I

2019-06-18 13:48发布

我意识到这个问题已经被以前问但在示例代码的方式很少,所以我再次询问,但至少方向的一点点。

经过搜索的时间,我都拿出了以下部分实现。

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:36272(GMT-4)[8] INFO DotNetOpenAuth - DotNetOpenAuth,版本= 4.0.0.11165文化=中性公钥= 2780ccd10d57b246(负责人)2012年10月19日13:27:36284( GMT-4)[8] DEBUG DotNetOpenAuth.Messaging.Channel - 准备发送AssertionFlowMessage(2.0)消息。 2012年10月19日13:27:36294(GMT-4)[8] INFO DotNetOpenAuth.Messaging.Channel -用于制备传出AssertionFlowMessage(2.0)消息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:36296(GMT-4)[8] DEBUG DotNetOpenAuth.Messaging.Channel - 发送AssertionFlowMessage请求。 2012年10月19日13:27:36830(GMT-4)[8] DEBUG DotNetOpenAuth.Http - HTTP POST https://accounts.google.com/o/oauth2/token 2012年10月19日13:27:36954 (GMT-4)[8] ERROR DotNetOpenAuth.Http -引发WebException从https://accounts.google.com/o/oauth2/token :{ “错误”: “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>

Answer 1:

下面的代码,从我原来的问题修正,是基于由伊恩·弗雷泽在所提供的例子:

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
  • 服务\ 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();            
        }

    }
}


Answer 2:

我被检查出的分析API昨天,发现它是多么无证,无样品等。

任何方式,我已经创建了你可以用它来与几行轻松访问分析和进行直接数据绑定到数据表数据返回它是开源的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);

有分类相同的方式,如API为所有谷歌API报告命令直接对应关系,所以你可以甚至没有阅读的API文档,因为在所有的所有功能有记载的属性,我已经写了解析完整的API文档代码资源的指标,维度,在我从物理类生成的,上面很好玩,你可以直接使用,如例如XML计算的特征:)享受

https://github.com/rmostafa/DotNetAnalyticsAPI



Answer 3:

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


Answer 4:

这是我在这里发布[1]的工作例如: 使用OAuth 2.0谷歌的API-的dotnet客户端的自动使用我投入了大量的研究,发现和拼凑的代码放在一起希望这可以节省一些时间。



Answer 5:

关于理查德·科莱特的答案,要小心使用他的方法,如果您要使用Google Analytics API以只读模式,使用它正确的做法是:

string Scope = "analytics.readonly"

并不是

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

他似乎在告诉有一个错误。 其实,这个错误是在.toString()方法返回analyticsreadonly和NOT analytics.readonly这是谷歌喜欢的方式。 而已。



文章来源: How do I use a Service Account to Access the Google Analytics API V3 with .NET C#?