Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

561
Views
Cómo autorizar la API de datos de análisis de Google con OAuth2

Estoy tratando de conectarme a la nueva API de datos de Google Analytics usando C# para solicitar datos del nuevo Google Analytics GA4. La única muestra que puedo encontrar es Quickstart client library .net Esto funciona pero usa una cuenta de servicio. La biblioteca cliente de .net en la nube google-cloud-dotnet solo tiene ejemplos para usar una cuenta de servicio.

Cuando trato de pasarle las credenciales de la aplicación de escritorio para usar la autorización de Oauth, obtengo

Error al crear la credencial desde JSON. Tipo de credencial no reconocido.

 using System; using System.Threading; using System.Threading.Tasks; using Google.Analytics.Data.V1Beta; namespace GoogleAnalyticsExamplesData { class Program { private const string PropertyId = "250796939"; private const string PathToCreds = @"C:\dev\ServiceAccountCred.json"; static async Task Main(string[] args) { Console.WriteLine("Hello World!"); // Check whether the environment variable exists. var environmentVariable = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS"); // If necessary, create it. if (environmentVariable == null) Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", PathToCreds); await SampleRunReport(PropertyId); } static async Task SampleRunReport(string propertyId = "YOUR-GA4-PROPERTY-ID") { // Using a default constructor instructs the client to use the credentials // specified in GOOGLE_APPLICATION_CREDENTIALS environment variable. var client = await BetaAnalyticsDataClient.CreateAsync(CancellationToken.None); var request = new RunReportRequest { Property = "properties/" + PropertyId, Dimensions = {new Dimension {Name = "date"},}, Metrics = {new Metric {Name = "totalUsers"}, new Metric {Name = "newUsers"}}, DateRanges = {new DateRange {StartDate = "2021-04-01", EndDate = "today"},}, }; var response = await client.RunReportAsync(request); Console.WriteLine("Report result:"); foreach (var row in response.Rows) { Console.WriteLine( $"{row.DimensionValues[0].Value}, {row.MetricValues[0].Value}, {row.MetricValues[1].Value}"); } } } }

Enlaces a Google.Analytics.Data.V1Beta Credenciales de cliente web, credenciales de escritorio

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Después de varias horas de investigar, descubrí que puedes usar ICredential usando un constructor. Esto funciona con las credenciales de una aplicación de escritorio, para las aplicaciones instaladas.

 using System; using System.IO; using System.Threading; using System.Threading.Tasks; using Google.Analytics.Data.V1Beta; using Google.Apis.Auth.OAuth2; using Google.Apis.Util.Store; namespace GoogleAnalyticsExamplesData { class Program { private const string PropertyId = "250796939"; private const string PathToCreds = @"C:\dev\credentials.json"; static async Task Main(string[] args) { Console.WriteLine("Hello World!"); await SampleRunReport(PropertyId); } static async Task SampleRunReport(string propertyId = "YOUR-GA4-PROPERTY-ID") { // Using a default constructor instructs the client to use the credentials // specified in GOOGLE_APPLICATION_CREDENTIALS environment variable. //var client = await BetaAnalyticsDataClient.CreateAsync(CancellationToken.None); BetaAnalyticsDataClient client ; await using (var stream = new FileStream(PathToCreds, FileMode.Open, FileAccess.Read)) { // Requesting Authentication or loading previously stored authentication for userName var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, new[] { "https://www.googleapis.com/auth/analytics.readonly"}, "userName", CancellationToken.None, new FileDataStore("credPath", true)).Result; client = await new BetaAnalyticsDataClientBuilder { TokenAccessMethod = credential.GetAccessTokenForRequestAsync }.BuildAsync(); } var request = new RunReportRequest { Property = "properties/" + PropertyId, Dimensions = {new Dimension {Name = "date"},}, Metrics = {new Metric {Name = "totalUsers"}, new Metric {Name = "newUsers"}}, DateRanges = {new DateRange {StartDate = "2021-04-01", EndDate = "today"},}, }; var response = await client.RunReportAsync(request); Console.WriteLine("Report result:"); foreach (var row in response.Rows) { Console.WriteLine( $"{row.DimensionValues[0].Value}, {row.MetricValues[0].Value}, {row.MetricValues[1].Value}"); } } } }
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!