【问题标题】:How to authorize Google anlaytics data api with OAuth2如何使用 OAuth2 授权 Google 分析数据 API
【发布时间】:2021-07-22 17:54:22
【问题描述】:

我正在尝试使用 C# 连接到新的 Google Analytics Data api,以从新的 Google Analytics GA4 请求数据。我能找到的唯一样本是 Quickstart client libraries .net 这确实有效,但它使用服务帐户。云 .net 客户端库google-cloud-dotnet 仅提供了使用服务帐户的示例。

当我尝试将桌面应用程序凭据传递给它以使用 Oauth 时,我得到了授权

从 JSON 创建凭据时出错。无法识别的凭据类型。

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

链接到Google.Analytics.Data.V1Beta Web client credentials, desktop credentials

【问题讨论】:

    标签: c# google-api google-api-dotnet-client google-analytics-4 google-analytics-data-api


    【解决方案1】:

    经过几个小时的挖掘,我发现您可以使用生成器来使用 ICredential。这适用于已安装的应用程序的桌面应用程序凭据。

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

    【讨论】:

      猜你喜欢
      • 2019-03-26
      • 1970-01-01
      • 2013-08-21
      • 1970-01-01
      • 1970-01-01
      • 2022-09-08
      • 2016-04-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多