浏览下面的代码,这可能会对你有所帮助,它对我来说工作正常。
static void Main(string[] args)
{
try
{
// Setting up webserver client by providing your application clientid,client secretid which are we registered in google api (cloud) console.
var client = new WebServerClient(GoogleAuthenticationServer.Description, "Your ClientID", "Client Secret");
// Authenticating the Web server client and GA account by passing the long lived refresh token
var auth = new OAuth2Authenticator<WebServerClient>(client, Authenticate);
// Initialize the Google analytics service.
// Set the auth parameter to Authenticator in Google analytics service instance
var asv = new Google.Apis.Analytics.v3.AnalyticsService(new BaseClientService.Initializer()
{
Authenticator = auth
});
// Preparing the query request for Google api
string queryDate = "";
queryDate = DateTime.Today.AddDays(-1).ToString("yyyy-MM-dd");
var request = asv.Data.Ga.Get("ga:" + "Your profileid", queryDate, queryDate, "ga:visits,ga:newVisits,ga:bounces,ga:pageviews,ga:timeOnSite,ga:transactionsPerVisit");
// Adding dimensions
request.Dimensions = "ga:date";
// Fecthing data
var data = request.Fetch();
}
catch (Exception ex)
{
}
}
private static IAuthorizationState Authenticate(WebServerClient client)
{
// The refresh token which application captures called as long lived refresh token, and will be used for gat new access token in future.
// In Json format access token and refresh token will be captured and saved in database when user allowd our application to access his analytics data.
// Next time when we are going to access the google analytics data for that user load the refresh token
IAuthorizationState state = new AuthorizationState(new string[] { }) { RefreshToken = "your refresh token" };
// Refresh the access token by passing the long lived refreshed token
client.RefreshToken(state);
// return the IAutherizationSate result
return state;
}
注意:您必须在使用这些方法之前获取刷新令牌