【问题标题】:Invalid Response Error when Retrieving Google Analytics Data with a Service Account in C# .NET在 C# .NET 中使用服务帐户检索 Google Analytics 数据时出现无效响应错误
【发布时间】:2013-07-15 01:55:59
【问题描述】:

我正在尝试编写一个在线应用程序来使用谷歌服务帐户访问我的谷歌分析数据。这是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace GA_server2server_POC.Models
{
    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;
    using Google.Apis.Services;
    using Google.Apis.Requests;

    public class Oauth_With_API
    {
        public static void ApiTest()
        {
            log4net.Config.XmlConfigurator.Configure();
            const string ServiceAccountId = "xxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com";
            const string ServiceAccountUser = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxdeveloper.gserviceaccount.com";
            AssertionFlowClient client = new AssertionFlowClient(
                GoogleAuthenticationServer.Description, new X509Certificate2("C:\\Users\\rcarter\\Downloads\\xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-privatekey.p12", "notasecret", X509KeyStorageFlags.Exportable))
            {
                Scope = "https://www.googleapis.com/auth/analytics.readonly",
                ServiceAccountId = ServiceAccountUser
            };



            OAuth2Authenticator<AssertionFlowClient> authenticator = new OAuth2Authenticator<AssertionFlowClient>(client, AssertionFlowClient.GetState);

            AnalyticsService service = new AnalyticsService(new BaseClientService.Initializer()
            {
                Authenticator = authenticator
            });

            string profileId = "ga:xxxxxxxx";
            string startDate = "2013-07-01";
            string endDate = "2013-07-15";
            string metrics = "ga:visits";
            DataResource.GaResource.GetRequest request = service.Data.Ga.Get(profileId, startDate, endDate, metrics);
            request.Dimensions = "ga:date";
            GaData data = request.Execute(); //error occurs here. After this, thread exits.

            Console.WriteLine(data.TotalResults);

        }
    }
}

到目前为止,我的代码执行完毕,但得到以下输出:

WebDev.WebServer40.exe Information: 0 : DotNetOpenAuth, Version=4.0.0.11165, Culture=neutral, PublicKeyToken=2780ccd10d57b246 (official)
WebDev.WebServer40.exe Information: 0 : Preparing to send AssertionFlowMessage (2.0) message.
WebDev.WebServer40.exe Information: 0 : Sending AssertionFlowMessage request.
WebDev.WebServer40.exe Information: 0 : HTTP POST https://accounts.google.com/o/oauth2/token
WebDev.WebServer40.exe Information: 0 : The following required parameters were missing from the DotNetOpenAuth.OAuth2.Messages.AccessTokenFailedResponse message: {error,
}
WebDev.WebServer40.exe Information: 0 : Received UnauthorizedResponse response.

此后,线程退出,程序拒绝打印任何数据。问题似乎发生在request.Execute();。我发现特别令人困惑的部分是,如果我在Console.WriteLine(data.TotalResults); 上放置一个断点,我可以在局部变量data 中看到我想要的数据。它包含我想要打印的所有内容,但我无法确定错误的原因,使其在request.Execute(); 之后无法执行任何操作。经过大量搜索,我对上面列出的错误完全没有发现。

我使用的代码基于对这个问题here 的回答。自从回答了这个问题以来,谷歌分析库中发生了一些变化,但我的大部分代码是相同的。

我已经检查并重新检查了所有帐户特定的变量。为了测试这一点,我在本地机器上将它作为 ASP.NET MVC 4 Web 应用程序运行。

感谢任何有关如何解决此问题的帮助或建议。如果我能提供更多可能有帮助的信息,请告诉我。谢谢阅读。

【问题讨论】:

  • 这很容易。问题是那里没有太多可用的文档/示例。我什至已经将一些 java 代码转换为 .net 等价物,因为示例仅在 java 中。我正在分享一些我在其他系统本地可用的代码。让我知道它是否有帮助。否则我会向您发送完整的工作示例谢谢

标签: c# web-services google-analytics-api google-oauth service-accounts


【解决方案1】:

尝试关注一个

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;
using Google.Apis.Services;


        private void TestMethod()
        {
            try
            {
                string scope_url = "https://www.googleapis.com/auth/analytics.readonly";

                //client_id: This is the "Email Address" one, not the "Client ID" one... oddly...
                string client_id = "************-***********************@developer.gserviceaccount.com";

                //key_file: This is the physical path to the key file you downloaded when you created your Service Account
                string key_file = @"***************************************-privatekey.p12";

                //key_pass: This is probably the password for all key files, but if you're given a different one, use that.
                string key_pass = "notasecret";


                AuthorizationServerDescription desc = GoogleAuthenticationServer.Description;

                //key: Load up and decrypt the key
                X509Certificate2 key = new X509Certificate2(key_file, key_pass, X509KeyStorageFlags.Exportable);

                //client: we're using the AssertionFlowClient, because we're logging in with our certificate
                AssertionFlowClient client = new AssertionFlowClient(desc, key) { ServiceAccountId = client_id, Scope = scope_url };
                OAuth2Authenticator<AssertionFlowClient> auth = new OAuth2Authenticator<AssertionFlowClient>(client, AssertionFlowClient.GetState);

                //gas: An instance of the AnalyticsService we can query
                // AnalyticsService gas = null;// new AnalyticsService(auth);

                var gas = new AnalyticsService(new BaseClientService.Initializer()
                {
                    Authenticator = auth
                });
                //r: Creating our query
                DataResource.GaResource.GetRequest r = gas.Data.Ga.Get("ga:*******", "2012-09-26", "2012-10-10", "ga:visitors");

                //d: Execute and fetch the results of our query
                GaData d = r.Fetch();
            }
            catch (Exception ex)
            {

                throw;
            }
        }

【讨论】:

  • 请记住,您必须在您的谷歌分析帐户中将 client_id 电子邮件注册为管理员用户
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-11
  • 1970-01-01
  • 2014-03-23
  • 2018-03-16
  • 1970-01-01
  • 2014-02-06
  • 1970-01-01
相关资源
最近更新 更多