简体   繁体   English

如何在 Asp.net MVC 中使用 Google Analytics API

[英]How to use Google Analytics API in Asp.net MVC

I'm creating an admin panel for my website and I want to see Google Analytics datas on admin panel of my website.我正在为我的网站创建一个管理面板,我想在我的网站的管理面板上查看 Google Analytics 数据。 I did some reseach and found "Google Analytics API".我做了一些研究,发现了“Google Analytics API”。 How can I use GA API on admin panel of my website.如何在我的网站管理面板上使用 GA API。 I want to create some charts, maps, nice graphics to make it more understandable.我想创建一些图表、地图、漂亮的图形以使其更易于理解。 Also I'm using Asp.net MVC not Php, I couldn't find any information about using GA API on Asp.net, there are infos for Php usage only...另外我使用的是 Asp.net MVC 而不是 Php,我找不到任何关于在 Asp.net 上使用 GA API 的信息,只有 Php 使用的信息......

The first thing you need to understand is that the data returned by the api is in Json you will need to create all the graphs yourself.您需要了解的第一件事是api返回的数据是Json,您需要自己创建所有图表。
Because you will only be connecting to your own data i recommend you look into using a service account.因为您只会连接到自己的数据,所以我建议您考虑使用服务帐户。

Service account Authentication -> serviceaccount.cs服务帐户身份验证 -> serviceaccount.cs

public static class ServiceAccountExample
    {

        /// <summary>
        /// Authenticating to Google using a Service account
        /// Documentation: https://developers.google.com/accounts/docs/OAuth2#serviceaccount
        /// </summary>
        /// <param name="serviceAccountEmail">From Google Developer console https://console.developers.google.com</param>
        /// <param name="serviceAccountCredentialFilePath">Location of the .p12 or Json Service account key file downloaded from Google Developer console https://console.developers.google.com</param>
        /// <returns>AnalyticsService used to make requests against the Analytics API</returns>
        public static AnalyticsreportingService AuthenticateServiceAccount(string serviceAccountEmail, string serviceAccountCredentialFilePath, string[] scopes)
        {
            try
            {
                if (string.IsNullOrEmpty(serviceAccountCredentialFilePath))
                    throw new Exception("Path to the service account credentials file is required.");
                if (!File.Exists(serviceAccountCredentialFilePath))
                    throw new Exception("The service account credentials file does not exist at: " + serviceAccountCredentialFilePath);
                if (string.IsNullOrEmpty(serviceAccountEmail))
                    throw new Exception("ServiceAccountEmail is required.");                

                // For Json file
                if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".json")
                {
                    GoogleCredential credential;
                    using (var stream = new FileStream(serviceAccountCredentialFilePath, FileMode.Open, FileAccess.Read))
                    {
                        credential = GoogleCredential.FromStream(stream)
                             .CreateScoped(scopes);
                    }

                    // Create the  Analytics service.
                    return new AnalyticsreportingService(new BaseClientService.Initializer()
                    {
                        HttpClientInitializer = credential,
                        ApplicationName = "Analyticsreporting Service account Authentication Sample",
                    });
                }
                else if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".p12")
                {   // If its a P12 file

                    var certificate = new X509Certificate2(serviceAccountCredentialFilePath, "notasecret", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);
                    var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
                    {
                        Scopes = scopes
                    }.FromCertificate(certificate));

                    // Create the  Analyticsreporting service.
                    return new AnalyticsreportingService(new BaseClientService.Initializer()
                    {
                        HttpClientInitializer = credential,
                        ApplicationName = "Analyticsreporting Authentication Sample",
                    });
                }
                else
                {
                    throw new Exception("Unsupported Service accounts credentials.");
                }

            }
            catch (Exception ex)
            {                
                throw new Exception("CreateServiceAccountAnalyticsreportingFailed", ex);
            }
        }
    }

things to note注意事项

First quota you can make a limited number of calls to your view per day that being 10,000 there is no way to extend that quota at this time.第一个配额,您每天可以对视图进行有限数量的调用,即 10,000 次,此时无法扩展该配额。 I recomend that you make your request once and the cashe the data in your system and use that to display as the data once processed will not change.我建议您提出一次请求,然后将系统中的数据兑现并使用它来显示,因为数据一旦处理就不会改变。

Processing time.处理时间。 It takes between 24 - 48 hours for data to complete processing on the website that means that the data you will be requesting will not be for the most recent days.数据在网站上完成处理需要 24 - 48 小时,这意味着您将请求的数据不会是最近几天的数据。

There is additional C# sample code here Samples这里有额外的 C# 示例代码Samples

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM