【问题标题】:Google Analytics Realtime API .Net Client谷歌分析实时 API .Net 客户端
【发布时间】:2017-03-20 10:54:43
【问题描述】:

有没有人可以使用 Google.Apis.Analytics.v3 API 和服务器身份验证共享任何示例 c# 代码,以获取我网站上的当前用户数。

背景: 我有一个带有支持仪表板的 MVC 内部网站。它连接到可能不同的 API 以整理一些有用的数据。 我有一个请求,要添加我们网站上当前的用户数量,如 Google Analytics(分析)门户网站所示。

我不想让用户单独使用谷歌帐户登录,我希望我可以使用“ServiceCredentials”方法,但我迷路了。

感谢任何帮助。

谢谢

【问题讨论】:

    标签: c# google-api google-analytics-api google-api-dotnet-client service-accounts


    【解决方案1】:

    确保在帐户级别授予您在 Google 分析中的服务帐户访问权限。

    警告:Google Analytics(分析)API 的配额是每次查看每天 10000 个请求。如果您在一天内发出超过 10000 个请求,您将被锁定。不要试图经常刷新实时数据,理想情况下在后台脚本中每分钟刷新一次。

    授权:

        /// <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 AnalyticsService AuthenticateServiceAccount(string serviceAccountEmail, string serviceAccountCredentialFilePath)
        {
            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.");
    
                // These are the scopes of permissions you need. It is best to request only what you need and not all of them
                string[] scopes = new string[] { AnalyticsReportingService.Scope.Analytics };             // View your Google Analytics data
    
                // 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 AnalyticsService(new BaseClientService.Initializer()
                    {
                        HttpClientInitializer = credential,
                        ApplicationName = "Analytics 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  Analytics service.
                    return new AnalyticsService(new BaseClientService.Initializer()
                    {
                        HttpClientInitializer = credential,
                        ApplicationName = "Analytics Authentication Sample",
                    });
                }
                else
                {
                    throw new Exception("Unsupported Service accounts credentials.");
                }
    
            }
            catch (Exception ex)
            {
                Console.WriteLine("Create service account AnalyticsService failed" + ex.Message);
                throw new Exception("CreateServiceAccountAnalyticsFailed", ex);
            }
        }
    }
    

    请求:

    public static class RealtimeSample
    {
    
        public class RealtimeGetOptionalParms
        {
            /// A comma-separated list of real time dimensions. E.g., 'rt:medium,rt:city'.
            public string Dimensions { get; set; }  
            /// A comma-separated list of dimension or metric filters to be applied to real time data.
            public string Filters { get; set; }  
            /// The maximum number of entries to include in this feed.
            public int Max-results { get; set; }  
            /// A comma-separated list of dimensions or metrics that determine the sort order for real time data.
            public string Sort { get; set; }  
    
        }
    
        /// <summary>
        /// Returns real time data for a view (profile). 
        /// Documentation https://developers.google.com/analytics/v3/reference/realtime/get
        /// Generation Note: This does not always build corectly.  Google needs to standardise things I need to figuer out which ones are wrong.
        /// </summary>
        /// <param name="service">Authenticated analytics service.</param>  
        /// <param name="ids">Unique table ID for retrieving real time data. Table ID is of the form ga:XXXX, where XXXX is the Analytics view (profile) ID.</param>
        /// <param name="metrics">A comma-separated list of real time metrics. E.g., 'rt:activeUsers'. At least one metric must be specified.</param>
        /// <param name="optional">Optional paramaters.</param>        /// <returns>RealtimeDataResponse</returns>
        public static RealtimeData Get(analyticsService service, string ids, string metrics, RealtimeGetOptionalParms optional = null)
        {
            try
            {
                // Initial validation.
                if (service == null)
                    throw new ArgumentNullException("service");
                if (ids == null)
                    throw new ArgumentNullException(ids);
                if (metrics == null)
                    throw new ArgumentNullException(metrics);
    
                // Building the initial request.
                var request = service.Realtime.Get(ids, metrics);
    
                // Applying optional parameters to the request.                
                request = (RealtimeResource.GetRequest)SampleHelpers.ApplyOptionalParms(request, optional);
    
                // Requesting data.
                return request.Execute();
            }
            catch (Exception ex)
            {
                throw new Exception("Request Realtime.Get failed.", ex);
            }
        }
    
    
    }
        public static class SampleHelpers
    {
    
        /// <summary>
        /// Using reflection to apply optional parameters to the request.  
        /// 
        /// If the optonal parameters are null then we will just return the request as is.
        /// </summary>
        /// <param name="request">The request. </param>
        /// <param name="optional">The optional parameters. </param>
        /// <returns></returns>
        public static object ApplyOptionalParms(object request, object optional)
        {
            if (optional == null)
                return request;
    
            System.Reflection.PropertyInfo[] optionalProperties = (optional.GetType()).GetProperties();
    
            foreach (System.Reflection.PropertyInfo property in optionalProperties)
            {
                // Copy value from optional parms to the request.  They should have the same names and datatypes.
                System.Reflection.PropertyInfo piShared = (request.GetType()).GetProperty(property.Name);
                if (property.GetValue(optional, null) != null) // TODO Test that we do not add values for items that are null
                    piShared.SetValue(request, property.GetValue(optional, null), null);
            }
    
            return request;
        }
    }
    

    Google Analytics API v3 的示例项目中提取的代码我还有一个教程,可以在这里找到Google Analytics Real-Time API with C# – What's happening now!

    【讨论】:

      猜你喜欢
      • 2019-05-02
      • 1970-01-01
      • 2017-05-26
      • 2021-11-19
      • 1970-01-01
      • 2017-10-28
      • 1970-01-01
      • 2017-11-11
      • 1970-01-01
      相关资源
      最近更新 更多