从WebApi的Google Analtics报告中获取数据

时间:2018-07-25 12:46:40

标签: c# google-analytics google-analytics-api

我正在构建Web Api,我需要从Google Analytics(分析)报告中获取数据。 我需要从Google Analytics(分析)视图中获取数据。 但是我认为我在凭证方面遇到了问题。

这是我正在使用的代码。

        var filepath = "XXXXXXXXXXXXXXXXx";  
        var viewid = "XXXXXXXXXX";   
        GoogleCredential credentials;
        using (var stream = new FileStream(filepath, FileMode.Open, FileAccess.Read))
        {
            string[] scopes = { AnalyticsReportingService.Scope.AnalyticsReadonly };
            var googleCredential = GoogleCredential.FromStream(stream);
            credentials = googleCredential.CreateScoped(scopes);
        }

        var reportingService = new AnalyticsReportingService(
            new BaseClientService.Initializer
            {
                HttpClientInitializer = credentials
            });
        var dateRange = new DateRange
        {
            StartDate = "2018-06-01",
            EndDate = "2018-06-25"
        };
        var sessions = new Metric
        {
            Expression = "ga:pageviews",
            Alias = "Sessions"
        };
        var date = new Dimension { Name = "ga:date" };

        var reportRequest = new ReportRequest
        {
            DateRanges = new List<DateRange> { dateRange },
            Dimensions = new List<Dimension> { date },
            Metrics = new List<Metric> { sessions },
            ViewId = viewid
        };
        var getReportsRequest = new GetReportsRequest
        {
            ReportRequests = new List<ReportRequest> { reportRequest }
        };
        var batchRequest = reportingService.Reports.BatchGet(getReportsRequest);
        var response = batchRequest.Execute();
        foreach (var x in response.Reports.First().Data.Rows)
        {
            Console.WriteLine(string.Join(", ", x.Dimensions) + "   " + string.Join(", ", x.Metrics.First().Values));
        }

我遇到以下问题:

  Google.GoogleApiException: 'Google.Apis.Requests.RequestError
  User does not have any Google Analytics account. [403]
  Errors [
  Message[User does not have any Google Analytics account.] Location[ - ] 
  Reason[forbidden] Domain[global]

谢谢, 安德烈斯(Andrés)

1 个答案:

答案 0 :(得分:1)

确保凭据用户有权访问您尝试访问的Google Analytics(分析)帐户。 您必须像在其他用户一样,在分析页面中授予它访问权限。