代码使用C#错误连接到Google AnalyticsAPI

时间:2014-08-19 15:05:03

标签: c# api google-analytics

我尝试在C#中使用Google Analytics来获取要在我的网站上显示的统计信息 这是我的代码

      public ActionResult Index()
    {
        string userName = "admin@email.com";
        string passWord = "mypass";
        string profileId = "ga:xxxxxxxx";
        string key = "2d751338cb092ef8da65f716e37a48604386c9sw";
       string dataFeedUrl = "https://www.google.com/analytics/feeds/data"+key;

        var service = new AnalyticsService("API Project");

        service.setUserCredentials(userName, passWord);

        var dataQuery = new DataQuery(dataFeedUrl)
        {
            Ids = profileId,
            Metrics = "ga:pageviews",
            Sort = "ga:pageviews",
            GAStartDate = new DateTime(2010, 3, 1).ToString("yyyy-MM-dd"),
            GAEndDate = DateTime.Now.ToString("yyyy-MM-dd")
        };

        var dataFeed = service.Query(dataQuery);

        var totalEntry = dataFeed.Entries[0];

        ViewData["Total"] = ((DataEntry)(totalEntry)).Metrics[0].Value;

        dataQuery.GAStartDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
        dataQuery.GAEndDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
        dataFeed = service.Query(dataQuery);

        var yesterdayEntry = dataFeed.Entries[0];
        ViewData["Yesterday"] = ((DataEntry)(yesterdayEntry)).Metrics[0].Value;
        dataQuery.GAStartDate = DateTime.Now.ToString("yyyy-MM-dd");
        dataQuery.GAEndDate = DateTime.Now.ToString("yyyy-MM-dd");
        dataFeed = service.Query(dataQuery);

        var todayEntry = dataFeed.Entries[0];
        ViewData["Today"] = ((DataEntry)(todayEntry)).Metrics[0].Value;
        return View(dataFeed.Entries);
    }

但是,当我运行代码时,它总是说" {"无效的凭据"}" 不确定为什么我在检查了很多关于密钥,用户名,密码和profileId的时间时遇到了这个错误 有人遇到这个问题,可以帮帮我吗? 非常感谢

1 个答案:

答案 0 :(得分:0)

我认为你的网址是错误的。尝试这种方式(你缺少?key=)。

string dataFeedUrl = "https://www.google.com/analytics/feeds/data?key="+key;

请参阅此Google example,其中有一个可以帮助您的示例

 public DataFeedExample()
    {

      // Configure GA API.
      AnalyticsService asv = new AnalyticsService("gaExportAPI_acctSample_v2.0");

      // Client Login Authorization.
      asv.setUserCredentials(CLIENT_USERNAME, CLIENT_PASS);

      // GA Data Feed query uri.
      String baseUrl = "https://www.google.com/analytics/feeds/data";

      DataQuery query = new DataQuery(baseUrl);
      query.Ids = TABLE_ID;
      query.Dimensions = "ga:source,ga:medium";
      query.Metrics = "ga:visits,ga:bounces";
      query.Segment = "gaid::-11";
      query.Filters = "ga:medium==referral";
      query.Sort = "-ga:visits";
      query.NumberToRetrieve = 5;
      query.GAStartDate = "2010-03-01";
      query.GAEndDate = "2010-03-15";
      Uri url = query.Uri;
      Console.WriteLine("URL: " + url.ToString());


      // Send our request to the Analytics API and wait for the results to
      // come back.

      feed = asv.Query(query);


    }

另请参阅此guide以配置您的项目

也请按照本指南使用OAuth 2.0