【发布时间】:2015-09-26 05:02:19
【问题描述】:
我正在尝试使用 OAUTH 2.0 身份验证访问 ga:visits 和 ga:transactions 的 Google Analytics(分析)数据。我已按照以下步骤操作:
- 在https://code.google.com/apis/console/ 网站上启用了 Google Analytics API。另外,创建了一个客户端 ID 并保存了 .p12 密钥
- 生成的电子邮件 ID 在 Analytics 网站上提供了读取和分析访问权限。
- 我创建了一个 Windows 窗体应用程序,还使用 package 命令下载了 NuGet 包:- Install-Package Google.Apis.Analytics.v3 包括 Google.Apis,Google.Apis.Analytics.v3,Google.Apis.Auth,Google.Apis.Auth.PlatformServices,Google.Apis.Core,Google.Apis.PlatformServices 在内的所有引用都添加到项目中
此外,在访问数据时遇到错误:-
查找来源
c:\code\google.com\google-api-dotnet-client\default\Tools\Google.Apis.Release\bin\Debug\test\default\Src\GoogleApis.Auth.DotNet4\OAuth2\ServiceAccountCredential.cs
当下面的代码行运行时:
var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { AnalyticsService.Scope.AnalyticsReadonly }
}.FromCertificate(cert));
你能帮我解决这个错误吗? 请在下面找到使用的代码:-
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Google.Apis.Analytics.v3;
using System.Security.Cryptography.X509Certificates;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
namespace WindowsFormsApplication5
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string keyFilePath = "C:\\Fetch GA Data-348e7435108b.p12";
string serviceAccountEmail= "xx@developer.gserviceaccount.com";
string keyPassword = "notasecret";
string websiteCode = "8482xxxx";
AnalyticsService service = null;
//loading the Key file
var certificate = new X509Certificate2(keyFilePath, keyPassword, X509KeyStorageFlags.Exportable);
//Add Scopes
var scopes =
new string[] { AnalyticsService.Scope.Analytics,AnalyticsService.Scope.AnalyticsEdit,AnalyticsService.Scope.AnalyticsManageUsers,AnalyticsService.Scope.AnalyticsReadonly
};
//create a new ServiceAccountCredential
var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
//Scopes = scopes
Scopes = new[] { AnalyticsService.Scope.AnalyticsReadonly }
}.FromCertificate(cert));
//Create a Service
service = new AnalyticsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential
});
DataResource.GaResource.GetRequest request = service.Data.Ga.Get(
"ga:" + websiteCode, "2015-05-27", "2015-05-27","ga:visits");
request.Dimensions = "ga:year,ga:month,ga:day";
var data = request.Execute();
}
}
}
【问题讨论】:
标签: c# google-oauth google-analytics-api google-api-dotnet-client