[C#] 使用 Google Analytics 取得 report資訊

近來有個專案需求是利用Google Analytics 將頁面的報表資訊回傳回來,此篇文章我會先大致介紹一些操作流程,還有如何取得他人已建立的Google Analytics資訊,之後有機會再跟大家介紹怎麼讓網站或blogger可以被Google Analytics追蹤。

Google API 設定

1.先登入個人的google帳號,並建立一個Google Api專案


2.點擊「啟用API和服務」


3.在上方搜尋框 輸入 關鍵字「Analytics」,找到「Google Analytics Reporting API」並啟用


4.建立憑證=>服務帳戶

5.輸入服務帳戶名稱,其他可以不要填,直接儲存到建立完成


6.點擊編輯=>金鑰=>新增金鑰=>建立新的金鑰



7.選擇Json 按建立(此Json檔請勿丟失,無法再建立出同一組金鑰)


新增Google Analytics 使用者

1.前往Google Analytics 點擊「 管理」


2.在三個區塊的 「帳戶存取管理」加入剛剛新增的服務帳戶(Google Api 的 服務帳戶 ID),並選擇給予的權限



實作:

1.建立 GoogleAnalyticsHelper

 /// <summary>
    /// Google Analytics Helper
    /// </summary>
    public static class GoogleAnalyticsHelper
    {
        #region 參數
        ///<summary>
        /// 基礎路徑
        /// </summary>
        private static string BaseDirectory = AppDomain.CurrentDomain.BaseDirectory;
        /// <summary>
        /// Google Analytics Reporting API Key
        /// </summary>
        private static string _GAKeyPath = BaseDirectory + "你下載的金鑰Json.json";
        /// <summary>
        /// Google Analytics 資料檢視Id
        /// </summary>
        private static string _ViewId = "你的資料檢視Id";
        #endregion     
        /// <summary>
        /// 取得 Google Analytics Report
        /// </summary>
        /// <param name="dateTime">查詢日期</param>
        /// <returns></returns>
        public static GetReportsResponse GetGetReportsResponse(DateTime dateTime)
        {
            //建立憑證物件
            var googleCredential = GoogleCredential.FromFile(_GAKeyPath).CreateScoped(AnalyticsReportingService.Scope.Analytics);
            //建立 AnalyticsReportingService 物件
            var analyticsReporting = new AnalyticsReportingService(new BaseClientService.Initializer
            {
                HttpClientInitializer = googleCredential,
                ApplicationName = "GA Lab"
            });
            //建立 Dimension 物件
            var dimension = new Dimension { Name = "ga:pagePath" };
            //建立 Metric 物件
            var users = new Metric { Expression = "ga:users" };
            var pageviews = new Metric { Expression = "ga:pageviews" };
            //建立 DateRange 物件
            var date = dateTime.ToString("yyyy-MM-dd");
            var january = new DateRange { StartDate = date, EndDate = date };

            var reportRequest = new ReportRequest
            {
                ViewId = _ViewId,
                Metrics = new List<Metric> { users, pageviews },
                Dimensions = new List<Dimension> { dimension },
                DateRanges = new List<DateRange> { january }
            };

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

            var response = analyticsReporting.Reports.BatchGet(reportGetRequest).Execute();
            return response;
        }
        /// <summary>
        /// 取得report詳細資訊
        /// </summary>
        /// <param name="reports"></param>
        /// <returns></returns>
        public static StringBuilder GetReportDetailStringBuilder(IList<Report> reports)
        {
            var sb = new StringBuilder();
            if (reports == null || !reports.Any())
            {
                return sb;
            }
            foreach (Report report in reports)
            {
                ColumnHeader header = report.ColumnHeader;
                List<string> dimensionHeaders = (List<string>)header.Dimensions;

                List<MetricHeaderEntry> metricHeaders = (List<MetricHeaderEntry>)header.MetricHeader.MetricHeaderEntries;
                List<ReportRow> rows = (List<ReportRow>)report.Data.Rows;

                foreach (ReportRow row in rows)
                {
                    List<string> dimensions = (List<string>)row.Dimensions;
                    List<DateRangeValues> metrics = (List<DateRangeValues>)row.Metrics;

                    for (int i = 0; i < dimensionHeaders.Count() && i < dimensions.Count(); i++)
                    {
                        sb.AppendLine(dimensionHeaders[i] + ": " + dimensions[i]);
                    }

                    for (int j = 0; j <metrics.Count(); j++)
                    {
                        sb.AppendLine("Date Range (" + j + "): ");
                        DateRangeValues values = metrics[j];
                        for (int k = 0; k < values.Values.Count() && k < metricHeaders.Count(); k++)
                        {
                            sb.AppendLine(metricHeaders[k].Name + ": " + values.Values[k]);
                        }
                    }
                }
            }
            return sb;
        }
    }  
*ViewId在Google Analytics管理=>資料檢視區塊=>點擊「資料檢視設定」





2.查詢與結果

 //查詢日期(昨天)
            var searchDate = DateTime.Now.AddDays(-1);
            //取得 Google Analytics Report
            var report = GoogleAnalyticsHelper.GetGetReportsResponse(searchDate);
            //取得report詳細資訊
            var sb = GoogleAnalyticsHelper.GetReportDetailStringBuilder(report.Reports);
            Console.WriteLine(sb.ToString());
            Console.ReadLine();




相關閱讀:


留言

這個網誌中的熱門文章

[Visual Studio]位於網際網路或是限制區域上 或是檔案上標有 web 字樣 所以無法處理該檔案。若希望處理這些檔案 請移除 web 字樣。

[IIS] IIS執行時,發生拒絕存取路徑 問題

[windows] xcopy 備份至 「網路磁碟機」