希望谷歌有一天会提供适当的文档。在这里,我列出了在 ASP.NET C# 中集成谷歌分析服务器端身份验证的所有步骤。
第 1 步:在 google 控制台中创建一个项目
转到链接https://console.developers.google.com/iam-admin/projects并通过单击“创建项目”按钮创建项目并在弹出窗口中提供项目名称并提交。
第 2 步:创建凭据和服务帐户
创建项目后,您将被重定向到“API Manager”页面。单击凭据,然后按“创建凭据”按钮。从下拉列表中选择“服务帐户密钥”,您将被重定向到下一页。在服务帐户下拉菜单中,选择“新建服务帐户”。填写服务帐号名称并下载 p12 密钥。它将具有 p12 扩展名。您将看到一个弹出窗口,其中包含默认密码“ notasecret ”,您的私钥将被下载。
第 3 步:创建 0auth 客户端 ID
单击“创建凭据”下拉菜单并选择“0auth 客户端 ID”,您将被重定向到“0auth 同意屏幕”选项卡。在项目名称文本框中提供一个随机名称。选择应用程序类型为“Web 应用程序”,然后单击创建按钮。在记事本中复制生成的客户端 ID。
第 4 步:启用 API
在左侧单击“Overview”选项卡,然后从水平选项卡中选择“Enabled APIs”。在搜索栏中搜索“Analytics API”,单击下拉菜单并按“启用”按钮。现在再次搜索“Analytics Reporting V4”并启用它。
第 5 步:安装 nuget 包
在 Visual Studio 中,转到工具 > Nuget 包管理器 > 包管理器控制台。将以下代码复制粘贴到控制台中以安装 nuget 包。
安装包 Google.Apis.Analytics.v3
安装包 DotNetOpenAuth.Core -版本 4.3.4.13329
以上两个包是谷歌分析和DotNetOpenAuth nuget包。
第 6 步:为服务帐户提供“查看和分析”权限
转到谷歌分析帐户并单击“管理”选项卡并从左侧菜单中选择“用户管理”,选择您要访问分析数据的域并在其下插入服务帐户电子邮件 ID,然后选择“读取和分析”权限从下拉列表中。服务帐户电子邮件 ID 类似于 ex:googleanalytics@googleanalytics.iam.gserviceaccount.com。
工作代码
前端代码:
将以下分析嵌入脚本复制并粘贴到您的前端,否则您也可以从谷歌分析文档页面获取此代码。
<script>
(function (w, d, s, g, js, fs) {
g = w.gapi || (w.gapi = {}); g.analytics = { q: [], ready: function (f) { this.q.push(f); } };
js = d.createElement(s); fs = d.getElementsByTagName(s)[0];
js.src = 'https://apis.google.com/js/platform.js';
fs.parentNode.insertBefore(js, fs); js.onload = function () { g.load('analytics'); };
}(window, document, 'script'));</script>
将以下代码粘贴到前端页面的正文标记中。
<asp:HiddenField ID="accessToken" runat="server" />
<div id="chart-1-container" style="width:600px;border:1px solid #ccc;"></div>
<script>
var access_token = document.getElementById('<%= accessToken.ClientID%>').value;
gapi.analytics.ready(function () {
/**
* Authorize the user with an access token obtained server side.
*/
gapi.analytics.auth.authorize({
'serverAuth': {
'access_token': access_token
}
});
/**
* Creates a new DataChart instance showing sessions.
* It will be rendered inside an element with the id "chart-1-container".
*/
var dataChart1 = new gapi.analytics.googleCharts.DataChart({
query: {
'ids': 'ga:53861036', // VIEW ID <-- Goto your google analytics account and select the domain whose analytics data you want to display on your webpage. From the URL ex: a507598w53044903p53861036. Copy the digits after "p". It is your view ID
'start-date': '2016-04-01',
'end-date': '2016-04-30',
'metrics': 'ga:sessions',
'dimensions': 'ga:date'
},
chart: {
'container': 'chart-1-container',
'type': 'LINE',
'options': {
'width': '100%'
}
}
});
dataChart1.execute();
/**
* Creates a new DataChart instance showing top 5 most popular demos/tools
* amongst returning users only.
* It will be rendered inside an element with the id "chart-3-container".
*/
});
</script>
您还可以从https://ga-dev-tools.appspot.com/account-explorer/获取您的视图 ID
后端代码:
using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Web.Script.Serialization;
using System.Net;
using System.Text;
using Google.Apis.Analytics.v3;
using Google.Apis.Analytics.v3.Data;
using Google.Apis.Services;
using System.Security.Cryptography.X509Certificates;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Util;
using DotNetOpenAuth.OAuth2;
using System.Security.Cryptography;
namespace googleAnalytics
{
public partial class api : System.Web.UI.Page
{
public const string SCOPE_ANALYTICS_READONLY = "https://www.googleapis.com/auth/analytics.readonly";
string ServiceAccountUser = "googleanalytics@googleanalytics.iam.gserviceaccount.com"; //service account email ID
string keyFile = @"D:\key.p12"; //file link to downloaded key with p12 extension
protected void Page_Load(object sender, EventArgs e)
{
string Token = Convert.ToString(GetAccessToken(ServiceAccountUser, keyFile, SCOPE_ANALYTICS_READONLY));
accessToken.Value = Token;
var certificate = new X509Certificate2(keyFile, "notasecret", X509KeyStorageFlags.Exportable);
var credentials = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(ServiceAccountUser)
{
Scopes = new[] { AnalyticsService.Scope.AnalyticsReadonly }
}.FromCertificate(certificate));
var service = new AnalyticsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credentials,
ApplicationName = "Google Analytics API"
});
string profileId = "ga:53861036";
string startDate = "2016-04-01";
string endDate = "2016-04-30";
string metrics = "ga:sessions,ga:users,ga:pageviews,ga:bounceRate,ga:visits";
DataResource.GaResource.GetRequest request = service.Data.Ga.Get(profileId, startDate, endDate, metrics);
GaData data = request.Execute();
List<string> ColumnName = new List<string>();
foreach (var h in data.ColumnHeaders)
{
ColumnName.Add(h.Name);
}
List<double> values = new List<double>();
foreach (var row in data.Rows)
{
foreach (var item in row)
{
values.Add(Convert.ToDouble(item));
}
}
values[3] = Math.Truncate(100 * values[3]) / 100;
txtSession.Text = values[0].ToString();
txtUsers.Text = values[1].ToString();
txtPageViews.Text = values[2].ToString();
txtBounceRate.Text = values[3].ToString();
txtVisits.Text = values[4].ToString();
}
public static dynamic GetAccessToken(string clientIdEMail, string keyFilePath, string scope)
{
// certificate
var certificate = new X509Certificate2(keyFilePath, "notasecret");
// header
var header = new { typ = "JWT", alg = "RS256" };
// claimset
var times = GetExpiryAndIssueDate();
var claimset = new
{
iss = clientIdEMail,
scope = scope,
aud = "https://accounts.google.com/o/oauth2/token",
iat = times[0],
exp = times[1],
};
JavaScriptSerializer ser = new JavaScriptSerializer();
// encoded header
var headerSerialized = ser.Serialize(header);
var headerBytes = Encoding.UTF8.GetBytes(headerSerialized);
var headerEncoded = Convert.ToBase64String(headerBytes);
// encoded claimset
var claimsetSerialized = ser.Serialize(claimset);
var claimsetBytes = Encoding.UTF8.GetBytes(claimsetSerialized);
var claimsetEncoded = Convert.ToBase64String(claimsetBytes);
// input
var input = headerEncoded + "." + claimsetEncoded;
var inputBytes = Encoding.UTF8.GetBytes(input);
// signature
var rsa = certificate.PrivateKey as RSACryptoServiceProvider;
var cspParam = new CspParameters
{
KeyContainerName = rsa.CspKeyContainerInfo.KeyContainerName,
KeyNumber = rsa.CspKeyContainerInfo.KeyNumber == KeyNumber.Exchange ? 1 : 2
};
var aescsp = new RSACryptoServiceProvider(cspParam) { PersistKeyInCsp = false };
var signatureBytes = aescsp.SignData(inputBytes, "SHA256");
var signatureEncoded = Convert.ToBase64String(signatureBytes);
// jwt
var jwt = headerEncoded + "." + claimsetEncoded + "." + signatureEncoded;
var client = new WebClient();
client.Encoding = Encoding.UTF8;
var uri = "https://accounts.google.com/o/oauth2/token";
var content = new NameValueCollection();
content["assertion"] = jwt;
content["grant_type"] = "urn:ietf:params:oauth:grant-type:jwt-bearer";
string response = Encoding.UTF8.GetString(client.UploadValues(uri, "POST", content));
var result = ser.Deserialize<dynamic>(response);
object pulledObject = null;
string token = "access_token";
if (result.ContainsKey(token))
{
pulledObject = result[token];
}
//return result;
return pulledObject;
}
private static int[] GetExpiryAndIssueDate()
{
var utc0 = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
var issueTime = DateTime.UtcNow;
var iat = (int)issueTime.Subtract(utc0).TotalSeconds;
var exp = (int)issueTime.AddMinutes(55).Subtract(utc0).TotalSeconds;
return new[] { iat, exp };
}
}
}