从Google Analytics检索数据? 403错误

时间:2014-02-19 09:58:07

标签: c# .net asp.net-mvc google-analytics-api nopcommerce

我正在尝试从Google AnalyticsAPI中提取一些数据。但是,当我运行应用程序时,我收到403错误 - 执行请求失败:https://www.google.com/analytics/feeds/data?ids=ga:12345678&dimensions=ga:date&metrics=ga:visits&start-date=2014-02-16&end-date=2014-02-19&sort=ga:day

我不确定代码或网址是否有问题?

此行导致错误:

return service.Query(dataQuery);

这是浏览器中的错误:

  

远程服务器返回错误:(403)Forbidden。

     

描述:执行期间发生了未处理的异常   当前的网络请求。请查看堆栈跟踪了解更多信息   有关错误的信息以及它在代码中的起源。

异常详细信息:System.Net.WebException:远程服务器返回错误:(403)Forbidden。

Analytics类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Google.GData.Analytics;
using GoogleChartSharp;
using Nop.Admin.Models;

namespace Nop.Web.Models
{
    public static class Analytics
    {    
        private const int IMAGE_WIDTH = 900;
        private const int IMAGE_HEIGHT = 200;
        private const string DATAFEED_URL = "https://www.google.com/analytics/feeds/data?ids=ga:12345678&dimensions=ga:date&metrics=ga:visits&start-date=2014-02-16&end-date=2014-02-19";    
        private const string USERNAME = "mymail@gmail.com";
        private const string PASSWORD = "mypassword!";
        private const string PROFILE_ID = "ga:12345678";              

        private static DataFeed AnalyticsVisitorsThisMonth()
        {
            // Google Analytics Service. The name dosnt mather.
            var service = new AnalyticsService("WebSiteAnalytics");

            // Add your credentials
            service.setUserCredentials(USERNAME, PASSWORD);

            // The Data Query (What to fetch from google analytics)
            // Read more about it here: http://code.google.com/intl/sv-SE/apis/analytics/
            var dataQuery = new DataQuery(DATAFEED_URL)
            {
                Ids = PROFILE_ID,
                Metrics = "ga:visits",
                Sort = "ga:day",
                Dimensions = "ga:day",
                GAStartDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).ToString("yyyy-MM-dd"),
                GAEndDate = DateTime.Now.ToString("yyyy-MM-dd")
            };

            return service.Query(dataQuery);
        }


        private static int[] FixChartData(List<int> data, out int iMax)
        {
            List<int> chartData = new List<int>();

            iMax = data.Max();
            iMax = (int)(Math.Ceiling(iMax / 10.0d) * 10);

            foreach (var i in data)
            {
                chartData.Add((int)(((double)61 / (double)iMax) * i));
            }

            for (int i = chartData.Count; i < 32; i++)
            {
                chartData.Add(0);
            }
            return chartData.ToArray();
        }


        public static string VisitorsThisMonth()
        {
            // Fetch the datafeed from google analytics
            DataFeed df = AnalyticsVisitorsThisMonth();

            List<int> data = new List<int>();
            int[] chartData;
            int iMax = 1;

            // Create a list of values
            foreach (var ae in df.Entries)
            {
                data.Add(int.Parse(((DataEntry)(ae)).Metrics[0].Value));
            }

            // Fix the data (max value = 61) and add coming days of the month.
            chartData = FixChartData(data, out iMax);

            // Create the chart, here you can laborite yourself
            LineChart chart = new LineChart(IMAGE_WIDTH, IMAGE_HEIGHT, LineChartType.SingleDataSet);
            chart.SetData(chartData.ToArray());
            chart.AddFillArea(new FillArea("ACC3FF", 0));
            chart.SetDatasetColors(new string[] { "000000" });
            chart.SetLegend(new string[] { "Visitors" });

            chart.SetTitle("Visitors this month", "000000", 14);


            ChartAxis leftAxis = new ChartAxis(ChartAxisType.Left);
            leftAxis.SetRange(0, (int)(Math.Ceiling(iMax / 10.0d) * 10));
            chart.AddAxis(leftAxis);

            ChartAxis bottomAxis = new ChartAxis(ChartAxisType.Bottom);
            bottomAxis.SetRange(1, 31);
            chart.AddAxis(bottomAxis);

            return chart.GetUrl();
        }

    }
}

ShopStatisticsController:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Nop.Admin.Models.ShopStatistics;
using Google.GData.Analytics;
using GoogleChartSharp;
using Nop.Web.Models;

namespace Nop.Admin.Controllers
{

    public class ShopStatisticsController : Controller
    {
        //
        // GET: /ShopStatistics/

        public ActionResult Company()
        {
            return View();
        }

    }
}

公司观点:

@using Telerik.Web.Mvc.UI
@using GoogleAnalyticsTracker;
@using Google;
@using GoogleAnalyticsTracker.Web.Mvc;
@{
    ViewBag.Title = "Company";
    Layout = "~/Views/Shared/_AdminLayout.cshtml";
}

<h2>Company</h2>


<img src="@Nop.Web.Models.Analytics.VisitorsThisMonth()" alt="Visitors this month" />

2 个答案:

答案 0 :(得分:1)

403表示您可能无权读取数据。如果您确定使用的是正确的用户名/密码,请确保配置文件ID也正确无误。

当您登录分析时,您的网址类似于https://www.google.com/analytics/web/?hl=en-GB#home/aXXXXXXXXwYYYYYYYYpZZZZZZZZ/

确保您分配给PROFILE_ID的号码是'p'后的号码(在我的情况下为“ga:ZZZZZZZZ”)。

如果这对您没有帮助,我建议您切换到OAuth身份验证,因为您使用的旧方式已被Google弃用,并且无法保证可以正常运行。

答案 1 :(得分:0)

我不相信客户登录适用于您需要使用oauth2的Google分析。代码看起来像这样。

UserCredential credential; 
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
          new ClientSecrets { ClientId = "YourClientId", ClientSecret = "YourClientSecret" },
          new[] { AnalyticsService.Scope.AnalyticsReadonly},
          "user",
          CancellationToken.None,
          new FileDataStore("Drive.Auth.Store")).Result; } 

一旦您拥有身份验证,您只需要创建所有请求的AnaltyicsService然后通过此服务。

AnalyticsService service = new AnalyticsService(
                           new BaseClientService.Initializer() {
                           HttpClientInitializer = credential,
                           ApplicationName = "Analytics API sample", });

Google Analtyics C# tutorial