I'm trying to get some data from our google analytics instance and I'd like to use the Analytics Reporting API V4 Client Library for .NET (https://developers.google.com/api-client-library/dotnet/apis/analyticsreporting/v4) so that I can bake some of this data into an administration site we have built. I'm having trouble finding any examples of using this code and the documentation seems to be incredibly sparse. I would like to use a service account to authorize as we only need to view data associated with the analytics account which we control.
我正在尝试从谷歌分析实例中获取一些数据,我希望使用分析报告API V4客户端库来为。net (https://developers.google.com/ap-client -library/dotnet/apis/analyticsreporting/v4)提供数据,这样我就可以将这些数据放入我们构建的管理站点中。我找不到任何使用这段代码的例子,而且文档似乎非常稀少。我想使用一个服务帐户进行授权,因为我们只需要查看与我们控制的分析帐户相关的数据。
If anyone could provide some sample code or point me in the right direction to get some basic report data using the .net api, it would be greatly appreciated
如果有人能提供一些示例代码,或者指出我使用。net api获取一些基本报告数据的正确方向,我将非常感激
2 个解决方案
#1
46
Calling the Google Analytics Reporting API from C# is not particularly difficult, however all of the necessary steps do not seem to be outlined very clearly in the Google Analyics API documentation. I will try to list them all out here. While YMMV, I believe these steps to be correct as of 7/20/2016.
从c#调用谷歌分析报告API并不特别困难,但是在谷歌Analyics API文档中似乎没有很清楚地列出所有必要的步骤。我会试着把它们都列出来。而YMMV,我相信这些步骤在2016年7月20日是正确的。
You can start by creating a new C# project. We'll make a console application to test called GoogleAnalyticsApiConsole
. Once the project is created, we'll add a reference to the Google Analytics Reporting API V4 Client Library for .NET using the NuGet Package Manager Console (found under the Tools menu in Visual Studio 2015). Fire up the Console and issue the following command at the PM>
prompt:
您可以从创建一个新的c#项目开始。我们将创建一个控制台应用程序来测试GoogleAnalyticsApiConsole。项目创建后,我们将使用NuGet包管理器控制台(在Visual Studio 2015的Tools菜单下)为. net添加对谷歌Analytics Reporting API V4客户端库的引用。启动控制台并在PM>提示符下发出以下命令:
PM> Install-Package Google.Apis.AnalyticsReporting.v4
点>安装包Google.Apis.AnalyticsReporting.v4
Installing that package will download the client libraries needed to call the Google Analytics Reporting web services along with a number of other dependencies.
安装该包将下载调用谷歌Analytics Reporting web服务所需的客户端库以及其他一些依赖项。
In order to call the web services, you'll need to set up OAuth 2.0 access for your application. The documentation for this setup can be found here, but I will summarize below:
为了调用web服务,您需要为应用程序设置OAuth 2.0访问权限。此设置的文档可以在这里找到,但我将总结如下:
-
Login to the Google Cloud Platform Console: https://console.cloud.google.com/. Be sure to login with an account that has access to the Google Analytics accounts you are trying to query with the reporting API.
登录到谷歌云平台控制台:https://console.cloud.google.com/。请确保登录的帐户具有访问您试图使用报告API查询的谷歌分析帐户的权限。
-
Click the Google Cloud Platform menu and select API Manager.
单击谷歌云平台菜单并选择API管理器。
-
On the left hand side, click Credentials and then create a new project called
Google Analytics API Console
. Give it some time to create the new project.在左边,单击凭据,然后创建一个名为谷歌分析API控制台的新项目。给它一些时间来创建新的项目。
-
After the project is created, click Credentials again if it is not already selected, and then click the OAuth Consent Screen link in the right panel. Set the Product name shown to users to
Google Analytics API Console
and then click Save.创建项目后,如果还没有选择凭据,请再次单击凭据,然后单击右边面板中的OAuth同意书屏幕链接。将显示给用户的产品名称设置为谷歌分析API控制台,然后单击Save。
-
Click Credentials again, and then click Create Credentials, and choose OAuth Client ID. Select Other for Application type and then enter
Google Analytics API Console
as the Name and click Create.再次点击凭证,点击创建凭证,选择OAuth客户端ID,应用类型选择Other,输入谷歌Analytics API控制台作为名称,点击Create。
-
After the credential is created, you will be presented with a client ID and a client secret. You can close the dialog window.
在创建凭据之后,将向您显示一个客户端ID和一个客户端秘密。您可以关闭对话框窗口。
-
Now, under Credentials you should see an entry under OAuth 2.0 client ids. Click the download icon to the far right of that entry to download the
client_secret.json
file (this file will have a much longer name). Add that file to your project at the root level once it has been downloaded and rename it toclient_secret.json
.现在,根据凭证,您应该看到OAuth 2.0客户机id下的条目。单击该条目最右边的下载图标来下载client_secret。json文件(此文件将有一个更长的名称)。下载后将该文件添加到根级别的项目中,并将其重命名为client_secret.json。
- Now that the OAuth 2.0 credential has been created, we need to enable it to call the Reporting API. Select Overview and make sure Google APIs is selected in the right panel. Type in
Reporting
in the search box and select Analytics Reporting API V4 from the list. On the next screen, click Enable. Once this API has been enabled, you should be able to see it under the Enabled APIs list in the right panel. - 现在已经创建了OAuth 2.0凭证,我们需要启用它来调用报告API。选择Overview,并确保在右边的面板中选择谷歌api。在搜索框中输入Reporting并从列表中选择Analytics Reporting API V4。在下一个屏幕上,单击Enable。一旦启用了该API,您应该能够在右侧面板的enabled API列表中看到它。
Now that we've created our project and created our OAuth 2.0 credential, it is time to call the Reporting API V4. The code listed below will use the Google API and the client_secret.json
file to create a Google.Apis.Auth.OAuth2.UserCredential
to query the Reporting API for all sessions between the given date range for a View. The code is adapted from the Java example here.
现在我们已经创建了项目并创建了OAuth 2.0凭据,现在是时候调用Reporting API V4了。下面列出的代码将使用谷歌API和client_secret。创建google . api . auth.oauth2的json文件。UserCredential查询一个视图的给定日期范围之间的所有会话的报告API。代码是根据这里的Java示例进行改编的。
Before executing the code, be sure to set the Build Action on the client_secret.json
file to Content and the Copy to Output Directory setting to Copy if newer. There are also two variables that need to be properly set. First, in the GetCredential()
method, set the loginEmailAddress
value to the email address used to create the OAuth 2.0 credential. Then, in the Main
method, be sure to set the ViewId
in the reportRequest
variable to the view that you want to query using the Reporting API. To find the ViewId
, log in to Google Analytics and select the Admin tab. From there, select the view you want to query in the View dropdown on the far right and select View Settings. The View ID will be displayed under Basic Settings.
在执行代码之前,请确保在client_secret上设置了构建操作。json文件到内容,拷贝到输出目录设置拷贝到更新。还需要正确设置两个变量,首先,在GetCredential()方法中,将loginEmailAddress值设置为用于创建OAuth 2.0凭据的电子邮件地址。然后,在Main方法中,确保将reportRequest变量中的ViewId设置为您希望使用Reporting API查询的视图。要找到ViewId,请登录谷歌Analytics并选择Admin选项卡。从那里,在最右边的视图下拉菜单中选择要查询的视图,并选择视图设置。视图ID将显示在基本设置下。
The first time the code is executed, it will bring up a web page asking if you want to allow the Google Analytics API Console
to have access to the API data. Select Allow to proceed. From then on that permission will be stored in the GoogleAnalyticsApiConsole
FileDataStore
. If that file is deleted, then permission will need to be granted again. That file can be found in the %APPDATA%\GoogleAnalyicsApiConsole
directory.
第一次执行代码时,它将打开一个web页面,询问您是否希望允许谷歌分析API控制台访问API数据。选择允许继续。从那时起,该权限将存储在GoogleAnalyticsApiConsole FileDataStore中。如果该文件被删除,那么需要再次授予权限。该文件可以在%APPDATA%\GoogleAnalyicsApiConsole目录中找到。
Please note that I beleive this scenario will meet the needs of the OP. If this application were to be distributed to clients, then a different OAuth 2.0 scheme would most likely be necessary.
请注意,我相信这个场景将满足opp的需要。如果这个应用程序要分发给客户端,那么很可能需要一个不同的OAuth 2.0方案。
Here is the code:
这是代码:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Google.Apis.AnalyticsReporting.v4;
using Google.Apis.AnalyticsReporting.v4.Data;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Util.Store;
namespace GoogleAnalyticsApiConsole
{
class Program
{
static void Main(string[] args)
{
try
{
var credential = GetCredential().Result;
using(var svc = new AnalyticsReportingService(
new BaseClientService.Initializer
{
HttpClientInitializer = credential,
ApplicationName = "Google Analytics API Console"
}))
{
var dateRange = new DateRange
{
StartDate = "2016-05-01",
EndDate = "2016-05-31"
};
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 = "<<your 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)
{
Console.WriteLine(string.Join(", ", x.Dimensions) +
" " + string.Join(", ", x.Metrics.First().Values));
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
static async Task<UserCredential> GetCredential()
{
using (var stream = new FileStream("client_secret.json",
FileMode.Open, FileAccess.Read))
{
const string loginEmailAddress = "<<your account email address>>";
return await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { AnalyticsReportingService.Scope.Analytics },
loginEmailAddress, CancellationToken.None,
new FileDataStore("GoogleAnalyticsApiConsole"));
}
}
}
}
#2
4
I had the same experience: Google's documentation is pretty in-depth but is pretty terrible at giving clear examples of how to connect with .NET.
我也有同样的经历:谷歌的文档相当深入,但在提供如何与。net连接的示例方面却非常糟糕。
One key thing I finally realized is that you can either connect using an OAuth2 credential or a service account credential. If you own your Analytics account, use a service account. If you're needing to connect to other users' Analytics accounts, use OAuth2.
我最终认识到的一个关键问题是,您可以使用OAuth2凭据或服务账户凭据进行连接。如果你拥有自己的分析账户,使用服务账户。如果您需要连接到其他用户的分析帐户,请使用OAuth2。
There seem to be quite a few examples online of how to get Analytics API data using an OAuth2 credential, but I own my Analytics account and just wanted to pull data from it. I figured out how to connect to the Analytics Reporting API v4 using a ServiceAccountCredential
, and I wrote an answer on a similar Stack Overflow question with all the details.
网上似乎有很多关于如何使用OAuth2凭据获取分析API数据的例子,但我拥有自己的分析账户,只想从中提取数据。我找到了如何使用ServiceAccountCredential连接到分析报告API v4,我在类似的堆栈溢出问题上写了一个答案。
#1
46
Calling the Google Analytics Reporting API from C# is not particularly difficult, however all of the necessary steps do not seem to be outlined very clearly in the Google Analyics API documentation. I will try to list them all out here. While YMMV, I believe these steps to be correct as of 7/20/2016.
从c#调用谷歌分析报告API并不特别困难,但是在谷歌Analyics API文档中似乎没有很清楚地列出所有必要的步骤。我会试着把它们都列出来。而YMMV,我相信这些步骤在2016年7月20日是正确的。
You can start by creating a new C# project. We'll make a console application to test called GoogleAnalyticsApiConsole
. Once the project is created, we'll add a reference to the Google Analytics Reporting API V4 Client Library for .NET using the NuGet Package Manager Console (found under the Tools menu in Visual Studio 2015). Fire up the Console and issue the following command at the PM>
prompt:
您可以从创建一个新的c#项目开始。我们将创建一个控制台应用程序来测试GoogleAnalyticsApiConsole。项目创建后,我们将使用NuGet包管理器控制台(在Visual Studio 2015的Tools菜单下)为. net添加对谷歌Analytics Reporting API V4客户端库的引用。启动控制台并在PM>提示符下发出以下命令:
PM> Install-Package Google.Apis.AnalyticsReporting.v4
点>安装包Google.Apis.AnalyticsReporting.v4
Installing that package will download the client libraries needed to call the Google Analytics Reporting web services along with a number of other dependencies.
安装该包将下载调用谷歌Analytics Reporting web服务所需的客户端库以及其他一些依赖项。
In order to call the web services, you'll need to set up OAuth 2.0 access for your application. The documentation for this setup can be found here, but I will summarize below:
为了调用web服务,您需要为应用程序设置OAuth 2.0访问权限。此设置的文档可以在这里找到,但我将总结如下:
-
Login to the Google Cloud Platform Console: https://console.cloud.google.com/. Be sure to login with an account that has access to the Google Analytics accounts you are trying to query with the reporting API.
登录到谷歌云平台控制台:https://console.cloud.google.com/。请确保登录的帐户具有访问您试图使用报告API查询的谷歌分析帐户的权限。
-
Click the Google Cloud Platform menu and select API Manager.
单击谷歌云平台菜单并选择API管理器。
-
On the left hand side, click Credentials and then create a new project called
Google Analytics API Console
. Give it some time to create the new project.在左边,单击凭据,然后创建一个名为谷歌分析API控制台的新项目。给它一些时间来创建新的项目。
-
After the project is created, click Credentials again if it is not already selected, and then click the OAuth Consent Screen link in the right panel. Set the Product name shown to users to
Google Analytics API Console
and then click Save.创建项目后,如果还没有选择凭据,请再次单击凭据,然后单击右边面板中的OAuth同意书屏幕链接。将显示给用户的产品名称设置为谷歌分析API控制台,然后单击Save。
-
Click Credentials again, and then click Create Credentials, and choose OAuth Client ID. Select Other for Application type and then enter
Google Analytics API Console
as the Name and click Create.再次点击凭证,点击创建凭证,选择OAuth客户端ID,应用类型选择Other,输入谷歌Analytics API控制台作为名称,点击Create。
-
After the credential is created, you will be presented with a client ID and a client secret. You can close the dialog window.
在创建凭据之后,将向您显示一个客户端ID和一个客户端秘密。您可以关闭对话框窗口。
-
Now, under Credentials you should see an entry under OAuth 2.0 client ids. Click the download icon to the far right of that entry to download the
client_secret.json
file (this file will have a much longer name). Add that file to your project at the root level once it has been downloaded and rename it toclient_secret.json
.现在,根据凭证,您应该看到OAuth 2.0客户机id下的条目。单击该条目最右边的下载图标来下载client_secret。json文件(此文件将有一个更长的名称)。下载后将该文件添加到根级别的项目中,并将其重命名为client_secret.json。
- Now that the OAuth 2.0 credential has been created, we need to enable it to call the Reporting API. Select Overview and make sure Google APIs is selected in the right panel. Type in
Reporting
in the search box and select Analytics Reporting API V4 from the list. On the next screen, click Enable. Once this API has been enabled, you should be able to see it under the Enabled APIs list in the right panel. - 现在已经创建了OAuth 2.0凭证,我们需要启用它来调用报告API。选择Overview,并确保在右边的面板中选择谷歌api。在搜索框中输入Reporting并从列表中选择Analytics Reporting API V4。在下一个屏幕上,单击Enable。一旦启用了该API,您应该能够在右侧面板的enabled API列表中看到它。
Now that we've created our project and created our OAuth 2.0 credential, it is time to call the Reporting API V4. The code listed below will use the Google API and the client_secret.json
file to create a Google.Apis.Auth.OAuth2.UserCredential
to query the Reporting API for all sessions between the given date range for a View. The code is adapted from the Java example here.
现在我们已经创建了项目并创建了OAuth 2.0凭据,现在是时候调用Reporting API V4了。下面列出的代码将使用谷歌API和client_secret。创建google . api . auth.oauth2的json文件。UserCredential查询一个视图的给定日期范围之间的所有会话的报告API。代码是根据这里的Java示例进行改编的。
Before executing the code, be sure to set the Build Action on the client_secret.json
file to Content and the Copy to Output Directory setting to Copy if newer. There are also two variables that need to be properly set. First, in the GetCredential()
method, set the loginEmailAddress
value to the email address used to create the OAuth 2.0 credential. Then, in the Main
method, be sure to set the ViewId
in the reportRequest
variable to the view that you want to query using the Reporting API. To find the ViewId
, log in to Google Analytics and select the Admin tab. From there, select the view you want to query in the View dropdown on the far right and select View Settings. The View ID will be displayed under Basic Settings.
在执行代码之前,请确保在client_secret上设置了构建操作。json文件到内容,拷贝到输出目录设置拷贝到更新。还需要正确设置两个变量,首先,在GetCredential()方法中,将loginEmailAddress值设置为用于创建OAuth 2.0凭据的电子邮件地址。然后,在Main方法中,确保将reportRequest变量中的ViewId设置为您希望使用Reporting API查询的视图。要找到ViewId,请登录谷歌Analytics并选择Admin选项卡。从那里,在最右边的视图下拉菜单中选择要查询的视图,并选择视图设置。视图ID将显示在基本设置下。
The first time the code is executed, it will bring up a web page asking if you want to allow the Google Analytics API Console
to have access to the API data. Select Allow to proceed. From then on that permission will be stored in the GoogleAnalyticsApiConsole
FileDataStore
. If that file is deleted, then permission will need to be granted again. That file can be found in the %APPDATA%\GoogleAnalyicsApiConsole
directory.
第一次执行代码时,它将打开一个web页面,询问您是否希望允许谷歌分析API控制台访问API数据。选择允许继续。从那时起,该权限将存储在GoogleAnalyticsApiConsole FileDataStore中。如果该文件被删除,那么需要再次授予权限。该文件可以在%APPDATA%\GoogleAnalyicsApiConsole目录中找到。
Please note that I beleive this scenario will meet the needs of the OP. If this application were to be distributed to clients, then a different OAuth 2.0 scheme would most likely be necessary.
请注意,我相信这个场景将满足opp的需要。如果这个应用程序要分发给客户端,那么很可能需要一个不同的OAuth 2.0方案。
Here is the code:
这是代码:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Google.Apis.AnalyticsReporting.v4;
using Google.Apis.AnalyticsReporting.v4.Data;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Util.Store;
namespace GoogleAnalyticsApiConsole
{
class Program
{
static void Main(string[] args)
{
try
{
var credential = GetCredential().Result;
using(var svc = new AnalyticsReportingService(
new BaseClientService.Initializer
{
HttpClientInitializer = credential,
ApplicationName = "Google Analytics API Console"
}))
{
var dateRange = new DateRange
{
StartDate = "2016-05-01",
EndDate = "2016-05-31"
};
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 = "<<your 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)
{
Console.WriteLine(string.Join(", ", x.Dimensions) +
" " + string.Join(", ", x.Metrics.First().Values));
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
static async Task<UserCredential> GetCredential()
{
using (var stream = new FileStream("client_secret.json",
FileMode.Open, FileAccess.Read))
{
const string loginEmailAddress = "<<your account email address>>";
return await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { AnalyticsReportingService.Scope.Analytics },
loginEmailAddress, CancellationToken.None,
new FileDataStore("GoogleAnalyticsApiConsole"));
}
}
}
}
#2
4
I had the same experience: Google's documentation is pretty in-depth but is pretty terrible at giving clear examples of how to connect with .NET.
我也有同样的经历:谷歌的文档相当深入,但在提供如何与。net连接的示例方面却非常糟糕。
One key thing I finally realized is that you can either connect using an OAuth2 credential or a service account credential. If you own your Analytics account, use a service account. If you're needing to connect to other users' Analytics accounts, use OAuth2.
我最终认识到的一个关键问题是,您可以使用OAuth2凭据或服务账户凭据进行连接。如果你拥有自己的分析账户,使用服务账户。如果您需要连接到其他用户的分析帐户,请使用OAuth2。
There seem to be quite a few examples online of how to get Analytics API data using an OAuth2 credential, but I own my Analytics account and just wanted to pull data from it. I figured out how to connect to the Analytics Reporting API v4 using a ServiceAccountCredential
, and I wrote an answer on a similar Stack Overflow question with all the details.
网上似乎有很多关于如何使用OAuth2凭据获取分析API数据的例子,但我拥有自己的分析账户,只想从中提取数据。我找到了如何使用ServiceAccountCredential连接到分析报告API v4,我在类似的堆栈溢出问题上写了一个答案。