我意識到這個問題以前曾經被問過,但很少用示例代碼的方式,所以我再次問,但至少有一點點的方向。如何使用服務帳戶以.NET C#訪問Google Analytics API V3?
經過幾個小時的搜索,我想出了以下部分實現。
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 = "[email protected]";
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();
}
}
}
我有幾個問題。如見於的DotNetOpenAuth日誌中 「invalid_scope」 響應於AssertionFlowClient.GetState(client)
結果呼叫
2012年10月19日13:27:36272(GMT-4)[8] INFO DotNetOpenAuth - DotNetOpenAuth,版本= 4.0 .0.11165,Culture = neutral,PublicKeyToken = 2780ccd10d57b246(官方) 2012-10-19 13:27:36,284(GMT-4)[8] DEBUG DotNetOpenAuth.Messaging.Channel - 準備發送AssertionFlowMessage(2.0)消息。 二〇一二年十月一十九日13:27:36294(GMT-4)[8] INFO DotNetOpenAuth.Messaging.Channel - 用於https://accounts.google.com/o/oauth2/token製備傳出AssertionFlowMessage(2.0)消息: grant_type:斷言 assertion_type:http://oauth.net/grant_type/jwt/1.0/bearer 斷言:(一束的編碼字符轉到此處)
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: { 「錯誤」: 「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>
看起來像正確的只讀範圍是https://www.googleapis.com/auth/analytics.readonly。這與將枚舉值轉換爲字符串不同。另外,我不必設置ServiceAccountUser。 –
@BenMills你能澄清你如何驗證?我猜你是在說你將ServiceAccountId設置爲nnnnnnnnnnn.apps.googleusercontent.com的值,但我不確定這是什麼意思。我編輯了代碼將範圍設置爲「analytics.readonly」,因爲這可能是人們使用這種方法的主要方式。 –
對不起,你是對的。我將ServiceAccountId設置爲[email protected]。我不需要以任何方式考慮nnnnnnnnnnn.apps.googleusercontent.com。 –