如何使用服务帐户通过.NETC#访问GoogleAnalyticsAPIV3?我意识到这个问题之前已经被问过,但是代码示例的方式很少,所以我再次问,但至少有一点方向。经过数小时的搜索,我想出了以下部分实现。命名空间GoogleAnalyticsAPITest.Console{使用System.Security.Cryptography.X509Certificates;使用DotNetOpenAuth.OAuth2;使用Google.Apis.Analytics.v3;使用Google.Apis.Analytics.v3.Data;使用Google.Apis.Authentication.OAuth2;使用Google.Apis.Authentication.OAuth2.DotNetOpenAuth;类程序{staticvoidMain(string[]args){log4net.Config.XmlConfigurator.Configure();字符串范围=Google.Apis.Analytics.v3.AnalyticsService.Scopes.Analytics.ToString().ToLower();字符串scopeUrl="https://www.googleapis.com/auth/"+范围;conststringServiceAccountId="nnnnnnnnnnn.apps.googleusercontent.com";conststringServiceAccountUser="nnnnnnnnnnn@developer.gserviceaccount.com";AssertionFlowClient客户端=newAssertionFlowClient(GoogleAuthenticationServer.Description,newX509Certificate2(@"7039572692013fc5deada350904f55bad2588a2a-privatekey.p12","notasecret",X509KeyStorageFlags.Exportable)){Scope=scopeUrl,ServiceAccountId=ServiceAccountId//,ServiceAccountUser=ServiceAccountUser};IAuthorizationState状态=AssertionFlowClient.GetState(客户端);AnalyticsServiceservice=newAnalyticsService(authenticator);字符串profileId="ga:xxxxxxxx";字符串开始日期="2010-10-01";字符串结束日期="2010-10-18";stringmetrics="ga:visits";DataResource.GaResource.GetRequestrequest=service.Data.Ga.Get(profileId,startDate,endDate,metrics);request.Dimensions="ga:date";GaDatadata=request.Fetch();我有一些问题,调用AssertionFlowClient.GetState(client)会导致“invalid_scope”响应,如DotNetOpenAuth日志中所示。2012-10-1913:27:36,272(GMT-4)[8]信息DotNetOpenAuth-DotNetOpenAuth,版本=4.0.0.11165,文化=中性,PublicKeyToken=2780ccd10d57b246(官方)2012-10-1913:24:36,28GMT-4)[8]DEBUGDotNetOpenAuth.Messaging.Channel-准备发送AssertionFlowMessage(2.0)消息。2012-10-1913:27:36,294(GMT-4)[8]INFODotNetOpenAuth.Messaging.Channel-为https://accounts.google.com/o/oauth2/token准备的传出AssertionFlowMessage(2.0)消息:grant_type:assertionassertion_type:http://oauth.net/grant_type/jwt/1.0/bearerassertion:(一堆编码字符在这里)2012-10-1913:27:36,296(GMT-4)[8]DEBUGDotNetOpenAuth.Messaging.Channel–发送AssertionFlowMessage请求。2012-10-1913:27:36,830(GMT-4)[8]DEBUGDotNetOpenAuth.Http-HTTPPOSThttps://accounts.google.com/o/oauth2/token2012-10-1913:27:36,954(GMT-4)[8]ErrorDotNetOpenAuth.Http-WebExceptionfromhttps://accounts.google.com/o/oauth2/token:{"error":"invalid_scope"}我试过指定一个或两个不走运服务帐户ID和服务帐户用户。其次,即使我获得了IAuthorizationState,我也不确定如何获得可以传递给AnalyticsService构造函数的IAuthenticator。下面是我用来启用D??otNetOpenAuth日志记录的web.config。下面的代码根据我原来的问题进行了更正,基于IanFraser提供的示例:https://groups.google.com/forum/#!msg/google-search-api-for-shopping/4uUGirzH4Rw/__c0e4hj0ekJ他的代码解决了三个问题:似乎AnalyticsService.Scopes.AnalyticsReadonly不起作用角色,至少不适合我或我的方式。出于某种原因,必须将ServiceAccountUser分配给AssertionFlowClient实例的ServiceAccountId属性。OAuth2Authenticator提供了我正在寻找的IAuthenticator。在您的项目目录中,包含以下内容的引用–namespaceGoogleAnalyticsAPITest.Console{usingSystem.Security.Cryptography.X509Certificates;使用Google.Apis.Analytics.v3;使用Google.Apis.Analytics.v3.Data;使用Google.Apis.Authentication.OAuth2;使用Google.Apis.Authentication.OAuth2.DotNetOpenAuth;使用Google.Apis.Util;类程序{staticvoidMain(string[]args){log4net.Config.XmlConfigurator.Configure();conststringServiceAccountId="nnnnnnnnnnn.apps.googleusercontent.com";conststringServiceAccountUser="nnnnnnnnnnn@developer.gserviceaccount.com";AssertionFlowClientclient=newAssertionFlowClient(GoogleAuthenticationServer.Description,newX509Certificate2(@"value-privatekey.p12","notasecret",X509KeyStorageFlags.Exportable)){Scope=AnalyticsService.Scopes.AnalyticsReadonly.GetStringValue(),ServiceAccountId=ServiceAccountUser//Bug,为什么ServiceAccountUser必须分配给ServiceAccountId//,ServiceAccountUser=ServiceAccountUser};OAuth2Authenticatorauthenticator=newOAuth2Authenticator(client,AssertionFlowClient.GetState);AnalyticsServiceservice=newAnalyticsService(authenticator);字符串profileId="ga:64968920";字符串开始日期="2010-10-01";-10-31";stringmetrics="ga:visits";DataResource.GaResource.GetRequestrequest=service.Data.Ga.Get(profileId,startDate,endDate,metrics);request.Dimensions="ga:date";GaDatadata=request.Fetch();}}}我昨天检查了分析API,发现它没有文档,没有样本等。无论如何,我已经创建了一个库,您可以使用它来轻松访问分析,并用几行代码直接将数据绑定到DataTables,并且它在github上是开源的,所以请随意贡献:)https://github.com/rmostafa/DotNetAnalyticsAPI用法Analytics.AnalyticsManagermanager=newAnalytics.AnalyticsManager(Server.MapPath("~/bin/privatekey.p12"),"YOUR_EMAIL");manager.LoadAnalyticsProfiles();列表指标=newList();metrics.Add(Analytics.Data.Visitor.Metrics.visitors);metrics.Add(Analytics.Data.Session.Metrics.visits);列表维度=newList();dimensions.Add(Analytics.Data.GeoNetwork.Dimensions.country);维度。添加(Analytics.Data.GeoNetwork.Dimensions.city);System.Data.DataTable表=manager.GetGaDataTable(DateTime.Today.AddDays(-3),DateTime.Today,metrics,dimensions,null,metrics);所有GoogleAPI报告命令的直接代码映射都以与API类似的方式分类,因此即使不阅读API文档,因为所有函数都记录在属性中,我编写的代码解析完整的api文档和我使用指标的资源,dimensions,computedfeatures在物理类生成的XML中,你可以直接使用它们,就像上面的例子一样,玩起来很有趣:)Enjoyhttps://github.com/rmostafa/DotNetAnalyticsAPIstringscope=Google.Apis.Util.Utilities.GetStringValue(AnalyticsService.Scopes.AnalyticsReadonly);这是我在此处发布的一个工作示例[1]:使用OAuth2.0自动化google-api-dotnet-client我进行了大量研究,寻找并将代码放在一起希望这可以为您节省一些时间来了解RichardCollette的答案,如果您想在READONLY模式下使用AnalyticsAPI,请注意使用他的方法,正确的使用方法是:stringScope="analytics.readonly"而不是stringScope=AnalyticsService.Scopes.AnalyticsReadOnly.ToString().ToLower()因为他似乎在告诉我有错误。事实上,错误在于.toString()方法返回analyticsreadonly而不是analytics.readonly,这是Google喜欢的方式。就这样。以上是C#学习教程:如何使用服务账号通过.NETC#访问GoogleAnalyticsAPIV3?如果所有分享的内容对你有用,需要进一步了解C#学习教程,希望大家多多关注。本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
