Google Analytics use API . NET for pageviews information

Asked

Viewed 150 times

1

How do I search for Pageview information from a particular URL of my website via programming using some Google Analitcs API.

Note that I already have the whole site configured in Google Analytics.

1 answer

1


After much research, and some headaches, I was able to perform the procedure as follows.

DEPENDENCIES

BASIC INSTRUCTIONS

Integration isn’t exactly difficult. Practically, you will have to follow a few steps to achieve the goal.

I’ll list them below, and I’m starting from the pre-presumed that you already have a project created (being monitored) in Google Analytics.

1) Enable Google Analytics Library
Google Developer Console => Your Project => API Library => Search Analytics API => Enable

2) Create a Service account (With key P12)
Google Developer Console => Your Project => IAM and Admin => Service Accounts => Create Service Account
NOTE: When creating the key it must be downloaded.

3) Allow this service account access your profiles / sites in Google Analytics
Google Analytics => Administration => Select Account/Property/Property View => User Management (From property view)

4) Install Nuget Package Google.Apis.Analytics.v3
PM> Install-Package Google.Apis.Analytics.v3

5) Show me the code!

When instantiating the class, pass the Localpath from which you are saving the P12 key you downloaded in step 2 and the account id you created in step 3.

You will primarily consume the method GetAnalyticsData. Its parameters need to be understood. See more in references about dimensions, filters and metrics.

The Filter, is via hard-code in this code in the method BuildAnalyticRequest. Implement to be a parameter too.

public class IntegracaoAnalyticsAPI
    {
        public AnalyticsService Service { get; set; }

        public IntegracaoAnalyticsAPI(string pathChaveP12, string idDaConta)
        {
            try
            {
                var certificate = new X509Certificate2(pathChaveP12, "notasecret", X509KeyStorageFlags.Exportable);


                var credentials = new ServiceAccountCredential(
                   new ServiceAccountCredential.Initializer(idDaConta)
                   {
                       Scopes = new[] { AnalyticsService.Scope.AnalyticsReadonly }
                   }.FromCertificate(certificate));

                Service = new AnalyticsService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credentials,
                    ApplicationName = "NOME DA SUA APLICAÇÃO"
                });
            }
            catch (DirectoryNotFoundException ex1)
            {
               //"Error: The directory specified could not be found."
            }
            catch (IOException ex2)
            {
               //"Error: A file in the directory could not be accessed."
            }
            catch (NullReferenceException ex3)
            {
               //"File must be a .cer file. Program does not have access to that type of file."
            }
            catch (Exception ex4)
            {
               // "xiiii.."
            }
        }

        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;
            request.Filters = "ga:pagePath=@seuFiltro";
            return request;
        }

        public IList<Profile> GetAvailableProfiles()
        {
            var response = Service.Management.Profiles.List("~all", "~all").Execute();
            return response.Items;
        }

        public class AnalyticDataPoint
        {
            public AnalyticDataPoint()
            {
                Rows = new List<IList<string>>();
            }

            public IList<GaData.ColumnHeadersData> ColumnHeaders { get; set; }
            public List<IList<string>> Rows { get; set; }
        }
    }

EXAMPLE OF USE:

var analytics = new IntegracaoAnalyticsAPI("LOCAL_PATH_DA_CHAVE_P12", "ID_CONTA");
var dados = analytics.GetAnalyticsData("ID_DA_VISTA", new string[] { "ga:userType" }, new string[] { "ga:pageviews" }, DateTime.Now.Date.AddDays(-30), DateTime.Now.Date);

REFERENCES

1) Stackoverflow** Basis of this process, but I had to adjust some things.
2) Good Reference
3) Construction work on Query Online (Very useful to help understand the return of your query).
4) Working with Filters
5) Understanding the Metrics
6) Understanding the Dimensions

Browser other questions tagged

You are not signed in. Login or sign up in order to post.