Use Google Analytics API to show information in C#

后端 未结 7 1387
难免孤独
难免孤独 2020-12-02 05:07

I been looking for a good solution all day but google evolve so fast that I can\'t find something working. What I want to do is that, I have a Web app that has an admin sect

7条回答
  •  攒了一身酷
    2020-12-02 05:54

    It requires a bit of setup on the google side but it's actually quite simple. I will list step by step.

    First you will need to create an application in the Google cloud console and enable the Analytics API.

    • Go to http://code.google.com/apis/console
    • Select the drop down and create a project if you do not already have one
    • Once the project is created click on services
    • From here enable the Analytics API

    Now that the Analytics API is enabled the next step will be to enable a service account to access your desired analytics profiles/sites. The service account will allow you to log in without having to prompt a user for credentials.

    • Go to http://code.google.com/apis/console and choose the project you created from the drop down.
    • Next go to the "API Access" section and click the "Create another client id" button.
    • In the Create Client ID window choose service account and click create client id.
    • Download the public key for this account if it doesn't start the download automatically.You will need this later on when you code for authorization.
    • Before exiting copy the service accounts auto generated email address as you will need this in the next step. The client email looks like @developer.gserviceaccount.com

    Now that we have a service account you will need to allow this service account to access to your profiles/sites in Google Analytics.

    • Log into Google Analytics.
    • Once logged in click on the Admin button to the bottem left on the screen.
    • In Admin click the account drop down and select the account/site you would like your service account to be able to access then click on "User Management" under the account section.
    • Enter the email address that was generated for your service account and give it read and analyze permission.
    • Repeat these steps for any other account/site you would like your service to have access to.

    Now that the setup is done for the service account to access Google Analytics through the API we can start to code.

    Get this package from NuGet:

    Google.Apis.Analytics.v3 Client Library

    Add these usings:

    using Google.Apis.Analytics.v3;
    using Google.Apis.Analytics.v3.Data;
    using Google.Apis.Services;
    using System.Security.Cryptography.X509Certificates;
    using Google.Apis.Auth.OAuth2;
    using System.Collections.Generic; 
    using System.Linq;
    

    Some things to note are.

    • The keyPath is the path to the key file you downloaded with a .p12 file extention.
    • The accountEmailAddress is the api email we got earlier.
    • Scope is an Enum in the Google.Apis.Analytics.v3.AnalyticService class that dictates the url to use in order to authorize (ex: AnalyticsService.Scope.AnalyticsReadonly ).
    • Application name is a name of your choosing that tells the google api what is accessing it (aka: it can be what ever you choose).

    Then the code to do some basic calls is as follows.

    public class GoogleAnalyticsAPI
    {
        public AnalyticsService Service { get; set; }
    
        public GoogleAnalyticsAPI(string keyPath, string accountEmailAddress)
        {
            var certificate = new X509Certificate2(keyPath, "notasecret", X509KeyStorageFlags.Exportable);
    
            var credentials = new ServiceAccountCredential(
               new ServiceAccountCredential.Initializer(accountEmailAddress)
               {
                   Scopes = new[] { AnalyticsService.Scope.AnalyticsReadonly }
               }.FromCertificate(certificate));
    
            Service = new AnalyticsService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credentials,
                    ApplicationName = "WorthlessVariable"
                });
        }
    
        public AnalyticDataPoint GetAnalyticsData(string profileId, string[] dimensions, string[] metrics, DateTime startDate, DateTime endDate)
        {
            AnalyticDataPoint data = new AnalyticDataPoint();
            if (!profileId.Contains("ga:"))
                profileId = string.Format("ga:{0}", profileId);
    
            //Make initial call to service.
            //Then check if a next link exists in the response,
            //if so parse and call again using start index param.
            GaData response = null;
            do
            {
                int startIndex = 1;
                if (response != null && !string.IsNullOrEmpty(response.NextLink))
                {
                    Uri uri = new Uri(response.NextLink);
                    var paramerters = uri.Query.Split('&');
                    string s = paramerters.First(i => i.Contains("start-index")).Split('=')[1];
                    startIndex = int.Parse(s);
                }
    
                var request = BuildAnalyticRequest(profileId, dimensions, metrics, startDate, endDate, startIndex);
                response = request.Execute();
                data.ColumnHeaders = response.ColumnHeaders;
                data.Rows.AddRange(response.Rows);
    
            } while (!string.IsNullOrEmpty(response.NextLink));
    
            return data;
        }
    
        private DataResource.GaResource.GetRequest BuildAnalyticRequest(string profileId, string[] dimensions, string[] metrics,
                                                                            DateTime startDate, DateTime endDate, int startIndex)
        {
            DataResource.GaResource.GetRequest request = Service.Data.Ga.Get(profileId, startDate.ToString("yyyy-MM-dd"),
                                                                                endDate.ToString("yyyy-MM-dd"), string.Join(",", metrics));
            request.Dimensions = string.Join(",", dimensions);
            request.StartIndex = startIndex;
            return request;
        }
    
        public IList GetAvailableProfiles()
        {
            var response = Service.Management.Profiles.List("~all", "~all").Execute();
            return response.Items;
        }
    
        public class AnalyticDataPoint
        {
            public AnalyticDataPoint()
            {
                Rows = new List>();
            }
    
            public IList ColumnHeaders { get; set; }
            public List> Rows { get; set; }
        }
    }
    

    Other Links that will prove helpful:

    Analytic API Explorer - Query API From The Web

    Analytic API Explorer version 2 - Query API From The Web

    Dimensions and Metrics Reference

    Hopefully this helps someone trying to do this in the future.

提交回复
热议问题