簡體   English   中英

如何使用 OAuth2 授權 Google 分析數據 api

[英]How to authorize Google anlaytics data api with OAuth2

我正在嘗試使用 C# 連接到新的谷歌分析數據 api 以從新的谷歌分析 GA4 請求數據。 我能找到的唯一示例是快速啟動客戶端庫 .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 客戶端憑據、桌面憑據的鏈接

經過幾個小時的挖掘,我發現您可以使用生成器來使用 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}");
            }
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM