L'SDK C # di Universal Analytics è compatibile con GA4?

Nov 14 2020

Sto usando la Google.Apis.AnalyticsReporting.v4libreria per le vecchie visualizzazioni di Google Analytics. Come converto questo codice in GA4? Non riesco a trovare una riga sul passaggio dell'ID di visualizzazione a qualcos'altro nel codice.

Ho controllato questo post "Come ottengo l'ID di visualizzazione in GA4" , ma le mie proprietà esistono già e non vedo l'opzione per modificarle dopo la creazione.

using (var svc = new AnalyticsReportingService(authInitializer.CreateInitializer()))
{
    var dateRange = new DateRange
    {
        StartDate = analyticsParams.From.ToString("yyyy-MM-dd"),
        EndDate = analyticsParams.To.ToString("yyyy-MM-dd")
    };
    var sessions = new Metric
    {
        Expression = "ga:sessions",
        Alias = "Sessions"
    };
    var date = new Dimension { Name = "ga:date" };

    var reportRequest = new ReportRequest
    {
        DateRanges = new List<DateRange> { dateRange },
        Dimensions = new List<Dimension> { date },
        Metrics = new List<Metric> { sessions },
        ViewId = analyticsParams.ViewId, // <------------------------- My view id
    };

    var getReportsRequest = new GetReportsRequest
    {
        ReportRequests = new List<ReportRequest> { reportRequest }
    };

    var batchRequest = svc.Reports.BatchGet(getReportsRequest);
    var response = batchRequest.Execute();

    var reports = response.Reports.First();

    return reports.Data.Rows.Select(x => new DataEntry()
    {
        Date = DateTime.ParseExact(x.Dimensions[0], "yyyyMMdd", CultureInfo.InvariantCulture),
        Value = int.Parse(x.Metrics[0].Values[0]),
    }).ToList();
}

Risposte

IlyaKuleshov Nov 14 2020 at 03:56

È necessario utilizzare l' API dei dati di Google Analytics V1 (attualmente in versione alpha) per accedere alle proprietà GA4. Ecco un esempio di avvio rapido per .NET che sembra simile a quello che stai cercando di fare.

using Google.Analytics.Data.V1Alpha;
using System;

namespace AnalyticsSamples
{
    class QuickStart
    {
        static void SampleRunReport(string propertyId)
        {
            // Using a default constructor instructs the client to use the credentials
            // specified in GOOGLE_APPLICATION_CREDENTIALS environment variable.
            AlphaAnalyticsDataClient client = AlphaAnalyticsDataClient.Create();

            // Initialize request argument(s)
            RunReportRequest request = new RunReportRequest
            {
                Entity = new Entity{ PropertyId = propertyId },
                Dimensions = { new Dimension{ Name="city"}, },
                Metrics = { new Metric{ Name="activeUsers"}, },
                DateRanges = { new DateRange{ StartDate="2020-03-31", EndDate="today"}, },
            };

            // Make the request
            RunReportResponse response = client.RunReport(request);

            Console.WriteLine("Report result:");
            foreach( Row row in response.Rows )
            {
                Console.WriteLine("{0}, {1}", row.DimensionValues[0].Value, row.MetricValues[0].Value);
            }
        }

        static int Main(string[] args)
        {
            if (args.Length == 0 || args.Length > 2)
            {
                Console.WriteLine("Arguments: <GA4 property ID>");
                Console.WriteLine("A GA4 property id parameter is required to make a query to the Google Analytics Data API.");
                return 1;
            }
            string propertyId = args[0];
            SampleRunReport(propertyId);
            return 0;
        }
    }
}
MichelePisani Nov 14 2020 at 01:44

Al momento non sono disponibili API per la proprietà GA4. Inoltre GA4 non fornisce le visualizzazioni, devi utilizzare BigQuery per ottenere i dati in modo programmatico.