.NET 访问和查询 Google Analytics V3 的服务帐户库
使用服务帐户凭据 OAuth2 轻松访问 Google Analytics
引言
简单的 .NET 项目,用于使用 Google Analytics API v3
厌倦了寻找帮助,但事情对你来说并不奏效?从这里快速开始分析。想按照应该的方式使用分析,这里是你的地方。
本文将带你快速了解分析,并使用 Simple Analytics 开源库,该库在 .NET Google Analytics API 之上提供了一个框架,简化了对 Reporting API 的访问、检索和使用,操作简单
背景
首先,你需要配置你的 Google 开发者帐户,并在云控制台中注册一个项目。
附注:这些说明使用新的控制台,对于旧的控制台用户,你会发现相同的内容,但有些在菜单中名称不同
- 在 Google Cloud Console 上创建一个帐户
- 从控制台创建新项目或选择现有项目
- 在 APIs 和 Auths 下:启用 Analytics API
- 转到 Credentials 页面
- 创建新的 Client ID
- 选择服务帐户
- 系统会提示你下载一个密钥文件,将其保存在安全的地方,因为我们将在身份验证中使用它
- 将向你显示一个包含客户端 ID、电子邮件地址和公钥指纹的服务帐户凭据表
- 复制电子邮件地址,然后登录到你的 Analytics Web 帐户
- 转到管理部分,在其中选择你要访问的配置文件,并在用户帐户下粘贴提供给你的电子邮件
- 在配置文件(网站)和帐户中执行此操作很重要
- 转到 git hub 并下载 Simple Analytics Library
- 在 Visual Studio 中,选择你想要使用的项目,向其中添加 Analytics.dll 库
- 运行以下命令
并执行以下命令,这将在你的项目中安装并引用 Google Analytics API
PM> Install-Package Google.Apis.Analytics.v3 -Pre [PROJECT_NAME]
好的,现在你准备好了
使用代码
使用该库很简单,首先你需要使用 Google Service OAuth2 进行身份验证,只需要一行代码,请注意,下面的电子邮件是在控制台服务帐户部分中提供给你的电子邮件
Analytics.AnalyticsManager manager = new Analytics.AnalyticsManager(Server.MapPath("~/bin/privatekey.p12"), "YOUR_EMAIL");
现在我们需要查询你具有访问权限的配置文件,并设置一个默认配置文件来使用,你可以从 Analytics URL 获取配置文件编号,它是 p 之后的数字
https://www.google.com/analytics/web/?hl=en#management/Settings/a32880022w60002165p61347423/
manager.LoadAnalyticsProfiles();<br />
manager.SetDefaultAnalyticProfile("80425770");
现在我们设置指标和维度,项目中有完整的 Reporting API 命令,因此你可以轻松设置指标和维度
List<Analytics.Data.DataItem> metrics = new List<Analytics.Data.DataItem>();
metrics.Add(Analytics.Data.Visitor.Metrics.visitors);
metrics.Add(Analytics.Data.Session.Metrics.visits);
List<Analytics.Data.DataItem> dimensions = new List<Analytics.Data.DataItem>();
dimensions.Add(Analytics.Data.GeoNetwork.Dimensions.country);
dimensions.Add(Analytics.Data.GeoNetwork.Dimensions.city);
现在你完成了,获取一个带有分析数据的表格
System.Data.DataTable table = manager.GetGaDataTable(DateTime.Today.AddDays(-3),DateTime.Today, metrics, dimensions, null, metrics);
就是这样,你可以通过更改/添加指标和维度属性来轻松获取任何 API 数据
库实现
该库的实现有一个主要的类叫做 AnalyticsManager,AnalyticsManager 允许通过 OAuth2 服务帐户身份验证启动身份验证
var certificate = new X509Certificate2(certificateKeyPath, "notasecret", X509KeyStorageFlags.Exportable);
string x = certificate.IssuerName.Name;
credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(apiEmail)
{
Scopes = new[] { Google.Apis.Analytics.v3.AnalyticsService.Scope.Analytics }
}.FromCertificate(certificate));
analyticsService = new Google.Apis.Analytics.v3.AnalyticsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Jareeda"
});
从传递的密钥创建了一个证书,notasecret
密码是所有来自 Google 的密钥文件的相同密码,尽管签名在密钥本身中有所不同,所以组合给出了不同的签名。
初始化一个服务帐户凭据,并将范围“Analytics”传递给它,这是一个枚举器,你可以在其中将其更改为 AnalyticsReadOnly
、AnalyticsEdit
、AnalyticsManageUsers
,每个都将为你提供不同的访问权限,具体取决于从 Analytics Web 授予的权限。
然后创建 AnalyticsService
对象,该对象将用于后续查询
分析方法需要你传递一个 table_id 或 profile_id
public System.Data.DataTable GetGaDataTable(DateTime startDate, DateTime endDate, List<Data.DataItem> metricsList, List<Data.DataItem> dimensionsList, List<Data.DataItem> filtersList, int? maxResults, Google.Apis.Analytics.v3.DataResource.GaResource.GetRequest.OutputEnum? output, Google.Apis.Analytics.v3.DataResource.GaResource.GetRequest.SamplingLevelEnum? samplingLevel, List<Data.DataItem> segmentList, List<Data.DataItem> sortList, int? startIndex, List<Data.DataItem> fieldsList)
{
if (DefaultProfile == null)
throw new Exception("Please set a default profile first using SetDefaultAnalyticProfile method");
Google.Apis.Analytics.v3.Data.GaData gaData = GetGaData("ga:" + DefaultProfile.Id, startDate, endDate, Data.DataItem.GetString(metricsList), Data.DataItem.GetString(dimensionsList), Data.DataItem.GetString(filtersList), maxResults, output, samplingLevel, Data.DataItem.GetString(segmentList), Data.DataItem.GetString(sortList), startIndex, Data.DataItem.GetString(fieldsList));
System.Data.DataTable table = BuildTableColumns(metricsList, dimensionsList);
if(gaData != null)
table = BuildTableRows(gaData, table);
return table;
}
在此方法中,我传递了从 analytics API 检索 GaData 所需的最大参数,其中传递的 DataItem 列表是根据 Google 完整指标和维度参考指南 组织的完整维度和指标列表,我解析了完整的指南,并为所有维度和指标创建了一个 XML 文件
<DataCategory Name="Session">
<ItemType Name="Dimensions" Value="1">
<DataItem Name="visitLength" APICommand="ga:visitLength" WebViewName="Visit Duration" AppViewName="Session Duration" DataType="STRING" AllowedInSegments="True">The length of a visit to your property measured in seconds and reported in second increments. The value returned is a string.</DataItem>
</ItemType>
<ItemType Name="Metrics" Value="2">
<DataItem Name="visits" APICommand="ga:visits" WebViewName="Visits" AppViewName="Sessions" DataType="INTEGER" AllowedInSegments="True">Counts the total number of sessions.</DataItem>
<DataItem Name="bounces" APICommand="ga:bounces" WebViewName="Bounces" AppViewName="" DataType="INTEGER" AllowedInSegments="True">The total number of single page (or single engagement hit) sessions for your property.</DataItem>
<DataItem Name="timeOnSite" APICommand="ga:timeOnSite" WebViewName="Visit Duration" AppViewName="Session Duration" DataType="TIME" AllowedInSegments="True">The total duration of visitor sessions represented in total seconds.</DataItem>
</ItemType>
<ItemType Name="Calculated" Value="3">
<DataItem Name="visitBounceRate" APICommand="ga:visitBounceRate" WebViewName="Bounce Rate" AppViewName="" DataType="PERCENT" AllowedInSegments="False">The percentage of single-page visits (i.e., visits in which the person left your property from the first page). (ga:bounces / ga:visits ) </DataItem>
<DataItem Name="avgTimeOnSite" APICommand="ga:avgTimeOnSite" WebViewName="Avg. Visit Duration" AppViewName="Avg. Session Duration" DataType="TIME" AllowedInSegments="False">The average duration visitor sessions represented in total seconds. (ga:timeOnSite / ga:visits ) </DataItem>
</ItemType>
</DataCategory>
将 XML 文件放置在项目的资源中,并基于包含指标和维度类的类别生成类,每个类包含 DataItem 对象,这些对象包含从 XML 资源文件中检索属性的命令的完整属性的定义 - 赋予它 .NET 资源使用的风格。
放置在 Session、Visitor 等类中的所有公共变量都具有来自 analytics API 的描述属性,因此你可以轻松地引用这些功能,而无需返回到 API,这允许你在代码中通过智能感知引用这些功能
List<Analytics.Data.DataItem> metrics = new List<Analytics.Data.DataItem>();
metrics.Add(Analytics.Data.Session.Metrics.visits);
metrics.Add(Analytics.Data.Visitor.Metrics.newVisits);
List<Analytics.Data.DataItem> dimensions = new List<Analytics.Data.DataItem>();
dimensions.Add(Analytics.Data.GeoNetwork.Dimensions.country);
dimensions.Add(Analytics.Data.Time.Dimensions.month);
上面提到了 GetGaDataTable
的其他 4 个重载方法
DataTable GetGaDataTable(DateTime startDate, DateTime endDate, List<Data.DataItem> metricsList)
DataTable GetGaDataTable(DateTime startDate, DateTime endDate, List<Data.DataItem> metricsList, List<Data.DataItem> sortList)
DataTable GetGaDataTable(DateTime startDate, DateTime endDate, List<Data.DataItem> metricsList, List<Data.DataItem> dimensionsList, List<Data.DataItem> filtersList, List<Data.DataItem> sortList)
DataTable GetGaDataTable(DateTime startDate, DateTime endDate, List<Data.DataItem> metricsList, List<Data.DataItem> dimensionsList, List<Data.DataItem> filtersList, Google.Apis.Analytics.v3.DataResource.GaResource.GetRequest.SamplingLevelEnum? samplingLevel, List<Data.DataItem> sortList, List<Data.DataItem> fields)
返回的数据表不仅包含数据,还保留了数据的数据类型,因此,字符串、整数、浮点数等类型被分配给这些列,这意味着你可以直接绑定它并开始对这些表进行操作