5

Próbuję napisać aplikację online, aby uzyskać dostęp do moich danych Google Analytics za pomocą konta usługi Google. Oto mój kod:Nieprawidłowy błąd odpowiedzi podczas pobierania danych Google Analytics za pomocą konta usługi w języku C# .NET

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); 

     } 
    } 
} 

tej pory mój kod wykonywany, ale pojawia się następujący komunikat:

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. 

Po tym, zakończy działanie nici, a program odmawia wydrukowania jakichkolwiek danych. Problem wydaje się występować pod adresem request.Execute();. Części, które uważam za szczególnie mylące, jest to, że jeśli umieściłem punkt przerwania na Console.WriteLine(data.TotalResults);, widzę dane, które chcę w lokalnej zmiennej data. Zawiera wszystko, co chcę wydrukować, ale nie mogę zidentyfikować przyczyny błędu, uniemożliwiając mu zrobienie czegoś po request.Execute();. Po wielu poszukiwaniach nie znalazłem w ogóle wiele informacji na temat błędu wymienionego powyżej.

Kod, którego używam, opiera się na odpowiedzi udzielonej na to pytanie here. Kilka rzeczy zmieniło się w bibliotekach Google Analytics, ponieważ odpowiedziano na to pytanie, ale większość mojego kodu jest taka sama.

Sprawdziłem i ponownie sprawdziłem wszystkie zmienne specyficzne dla konta. Aby to przetestować, uruchamiam go na moim lokalnym komputerze jako aplikację sieci Web ASP.NET MVC 4.

Każda pomoc lub porady dotyczące sposobu rozwiązania tego problemu są mile widziane. Proszę dać mi znać, jeśli mogę podać więcej informacji, które mogą pomóc. Dziękuje za przeczytanie.

+0

Jest całkiem easy.Problem to nie ma dużo dokumentacja/próbki są tam dostępne. Przekonwertowałem nawet kod java do odpowiednika .net, ponieważ próbka była tylko w java. Dzielę się pewnym kodem, który mam lokalnie dostępny w moim innym systemie. Daj mi znać, czy to pomaga, czy nie. Inne mądre, wyślę ci pełną próbkę roboczą Dzięki –

Odpowiedz

0

spróbuj wykonać jedną

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; 
      } 
     } 
+0

Pamiętaj, że musisz zarejestrować adres e-mail client_id jako administrator w swoim Google Analytics konto –

Powiązane problemy