创建您的应用https://code.google.com/apis/console/
为您的应用打开对 Google Analytics 的访问权限,并为您的网站创建 OAuth 2.0 客户端 ID。
浏览到:
https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=YOUR_APP_ID.apps.googleusercontent.com&access_type=offline&scope=https://www.googleapis.com/auth/analytics.readonly&redirect_uri=HTTP://YOUR_CALL_BACK_URL
已将 YOUR_APP_ID、YOUR_CALL_BACK_URL 更改为相关值。
包含 access_type=offline 很重要。
按授予访问权限,这将重定向到 HTTP://YOUR_CALL_BACK_URL?code=THIS_IS_YOUR_CODE。复制网址中的代码。
通过代码,使用 CMD 提示请求刷新令牌。
curl -d "code=THIS_IS_YOUR_CODE&client_id=YOUR_APP_ID.apps.googleusercontent.com&client_secret=YOUR_APPS_SECRET_CODE&redirect_uri=HTTP://YOUR_CALL_BACK_URL&grant_type=authorization_code" https://accounts.google.com/o/oauth2/token
已将 THIS_IS_YOUR_CODE、YOUR_APP_ID、YOUR_APPS_SECRET_CODE、YOUR_CALL_BACK_URL 更改为相关值。
记录返回的refresh_token。
下载最新版本的 Core Reporting V3.0 .net 库
http://code.google.com/p/google-api-dotnet-client/wiki/Downloads
当前版本的 Google.Apis.Analytics.v3.cs 中存在一个错误,要修复此问题,请将此文件中的代码复制到您的本地解决方案中(并且不要引用 Google.Apis.Analytics.v3.bin )
http://code.google.com/p/google-api-dotnet-client/source/browse/Services/Google.Apis.Analytics.v3.cs?repo=samples&name=20111123-1.1.4344-beta
并将属性Dimensions 从List<system.string> 更改为string。
否则你会遇到像我这样的错误,而这家伙做了http://www.evolutiadesign.co.uk/blog/using-the-google-analytics-api-with-c-shar/
然后,您可以使用您的刷新令牌,在没有用户交互的情况下为您生成访问令牌,并使用访问令牌针对 Google Analytics(分析)运行报告。
using System;
using DotNetOpenAuth.OAuth2;
using Google.Apis.Authentication.OAuth2;
using AnalyticsService = Google.Apis.Analytics.v3.AnalyticsService;
class Program
{
public static void Main()
{
var client = new WebServerClient(GoogleAuthenticationServer.Description, "YOUR_APP_ID.apps.googleusercontent.com", "YOUR_APPS_SECRET_CODE");
var auth = new OAuth2Authenticator<WebServerClient>(client, Authenticate);
var asv = new AnalyticsService(auth);
var request = asv.Report.Get("2012-02-20", "2012-01-01", "ga:visitors", "ga:YOUR_GOOGLE_ANALYTICS_ACCOUNT_ID");
request.Dimensions = "ga:pagePath";
request.Sort = "-ga:visitors";
request.MaxResults = 5;
var report = request.Fetch();
Console.ReadLine();
}
private static IAuthorizationState Authenticate(WebServerClient client)
{
IAuthorizationState state = new AuthorizationState(new string[]{}) { RefreshToken = "REFRESH_TOKEN" };
client.RefreshToken(state);
return state;
}
}