我正在尝试遵循分析报告的文档,但我对 Oauth2 的文档(在 C# 中,但我无法开始工作)和分析报告 API 的文档之间感到非常困惑(它有 Java 和 Python 中的示例,但没有 C#)。我一直在阅读以下文档:
https://developers.google.com/analytics/devguides/reporting/core/v4/
https://developers.google.com/analytics/devguides/reporting/core/v4/
https://developers.google.com/api-client-library/dotnet/guide/aaa_oauth
适用于 .NET 的 Analytics Reporting API V4 客户端库
我已经根据 Stack Overflow 答案和 Google Developers关于 Oauth2 for Asp.NET MVC的文档整理了一些代码。这是我的代码:
class GoogleAnalyticsUtil
{
public List<AnalyticsPage> GetReport(DateTime startDate)
{
List<AnalyticsPage> report = new List<AnalyticsPage>();
try
{
var credentialTask = GetCredential();
credentialTask.Wait();
var credential = credentialTask.Result;
using (var svc = new AnalyticsReportingService(
new BaseClientService.Initializer
{
HttpClientInitializer = credential,
ApplicationName = "Google Analytics API Console"
}))
{
var dateRange = new DateRange
{
StartDate = startDate.ToString("yyyy-MM-dd"),
EndDate = DateTime.Now.ToString("yyyy-MM-dd")
};
var sessions = new Metric
{
Expression = "ga:sessions",
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 = "<<view id>>"
};
var getReportsRequest = new GetReportsRequest
{
ReportRequests = new List<ReportRequest> { reportRequest }
};
var batchRequest = svc.Reports.BatchGet(getReportsRequest);
var response = batchRequest.Execute();
foreach (var x in response.Reports.First().Data.Rows)
{
report.Add(new AnalyticsPage()
{
Path = x.Dimensions.First(),
Views = x.Metrics.First().Values
});
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
return report;
}
static async Task<UserCredential> GetCredential()
{
var clientSecretPath = HttpRuntime.AppDomainAppPath + "client_secret.json";
var credPath = HttpRuntime.AppDomainAppPath + "credentials/GoogleAnalyticsApiConsole/";
UserCredential credential;
using (var stream = new FileStream(clientSecretPath,
FileMode.Open, FileAccess.Read))
{
var secrets = GoogleClientSecrets.Load(stream).Secrets;
credential = await dsAuthorizationBroker.AuthorizeAsync(
secrets,
new[] {AnalyticsReportingService.Scope.Analytics},
"<<username>>",
CancellationToken.None,
new FileDataStore(credPath, true));
return credential;
}
}
}
class AnalyticsPage
{
public string Path { get; set; }
public IList<string> Views { get; set; }
public string ViewString { get; set; }
}
public class dsAuthorizationBroker : GoogleWebAuthorizationBroker
{
public static string RedirectUri = "https://<<my website>>/AuthCallback/IndexAsync";
public new static async Task<UserCredential> AuthorizeAsync(
ClientSecrets clientSecrets,
IEnumerable<string> scopes,
string user,
CancellationToken taskCancellationToken,
IDataStore dataStore = null)
{
var initializer = new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = clientSecrets,
};
return await AuthorizeAsyncCore(initializer, scopes, user,
taskCancellationToken, dataStore).ConfigureAwait(false);
}
private static async Task<UserCredential> AuthorizeAsyncCore(
GoogleAuthorizationCodeFlow.Initializer initializer,
IEnumerable<string> scopes,
string user,
CancellationToken taskCancellationToken,
IDataStore dataStore)
{
initializer.Scopes = scopes;
initializer.DataStore = dataStore ?? new FileDataStore(Folder);
var flow = new dsAuthorizationCodeFlow(initializer);
return await new AuthorizationCodeInstalledApp(flow,
new LocalServerCodeReceiver())
.AuthorizeAsync(user, taskCancellationToken).ConfigureAwait(false);
}
}
public class dsAuthorizationCodeFlow : GoogleAuthorizationCodeFlow
{
public dsAuthorizationCodeFlow(Initializer initializer)
: base(initializer) { }
public override AuthorizationCodeRequestUrl
CreateAuthorizationCodeRequest(string redirectUri)
{
return base.CreateAuthorizationCodeRequest(dsAuthorizationBroker.RedirectUri);
}
}
namespace MySite.Web.Controllers.WebAPI
{
public class AuthCallbackController : Google.Apis.Auth.OAuth2.Mvc.Controllers.AuthCallbackController
{
protected override Google.Apis.Auth.OAuth2.Mvc.FlowMetadata FlowData
{
get { return new AppFlowMetadata(); }
}
[System.Web.Mvc.HttpGet]
public async Task IndexAsync(CancellationToken cancellationToken)
{
var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()).
AuthorizeAsync(cancellationToken);
if (result.Credential != null)
{
var service = new DriveService(new BaseClientService.Initializer
{
HttpClientInitializer = result.Credential,
ApplicationName = "PMA"
});
// YOUR CODE SHOULD BE HERE..
// SAMPLE CODE:
//var list = await service.Files.List().ExecuteAsync();
}
Response.Redirect(result.RedirectUri);
}
}
}
授权GetCredential()
失败,出现错误
当我尝试直接访问 mysite.com/AuthCallback/IndexAsync 时,我得到一个 404,所以这可能是问题所在?但我不确定控制器出了什么问题,或者为什么会导致授权失败。我正在使用 Web 应用程序 Auth2.0 客户端 ID,但我也尝试使用在参数中不采用 RedirectUrls 的“其他”类型,但这也不起作用。我可以在不重定向任何地方的情况下对其进行授权吗?我需要credential.result
授权才能继续使用我的其余代码,还是在 C# 中有另一种方法可以让我从 Google Analytics Reporting API 获取数据?