C# 手动将数据发送到 Google Analytics
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12653239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Manually sending data to Google Analytics
提问by huesforalice
I was wondering if I can send google analytics tracking data to google by sending custom URL requests. I assumed I could build my own URLs and fire a request to get events tracked something like this: http://google.com/analytics-endpoint?id=UA-34900236-1&event=some_event, I haven't found any documentation about this though and was wondering if this is even possible? If so, could some one point me to the right documents?
我想知道是否可以通过发送自定义 URL 请求将谷歌分析跟踪数据发送给谷歌。我假设我可以构建自己的 URL 并发出一个请求来跟踪这样的事件:http://google.com/analytics-endpoint?id=UA-34900236-1&event=some_event,但我还没有找到任何关于此的文档,并且想知道这是否可能?如果是这样,有人可以指出我正确的文件吗?
The background for anyone who is interested: I'm currently trying to add google analytics support to a Mono for Android application. I could not get any of the c# google analytics libraries to compile, because required .net libraries are missing from Mono for Android.
任何感兴趣的人的背景:我目前正在尝试向 Mono for Android 应用程序添加谷歌分析支持。我无法编译任何 c# google 分析库,因为 Mono for Android 缺少所需的 .net 库。
采纳答案by i.amniels
As an addition to @P.T.'s answer I want to note that Google released an official API to send data to Google Analytics now. This is the Google Analytics Measurement Protocol. This is probably the safest solution because it is an "official" and documented API.
作为对@PT 的回答的补充,我想指出谷歌现在发布了一个官方 API 来将数据发送到谷歌分析。这是Google Analytics 测量协议。这可能是最安全的解决方案,因为它是一个“官方”和文档化的 API。
回答by L0j1k
Yes, this is possible. Because Google Analytics will store every URL page request it is on. Those are visible under Content tab on the left menu, then find URL or Page Content. You can see every page request listed. So if you fired this off due to a link like <a href="more.php?id=8&event=sales">LINK</a>Analytics would store the full URL.
是的,这是可能的。因为 Google Analytics 会存储它所在的每个 URL 页面请求。这些在左侧菜单的“内容”选项卡下可见,然后找到 URL 或页面内容。您可以看到列出的每个页面请求。因此,如果您因为<a href="more.php?id=8&event=sales">LINK</a>Analytics 之类的链接而将其关闭,则会存储完整的 URL。
However, there is no direct route to your Analytics account via the URL you have provided hoping to get a similar answer to: This is the best you can do, I think.
但是,没有通过您提供的 URL 直接路由到您的 Analytics 帐户,希望得到类似的答案:我认为这是您能做的最好的事情。
You could make a page that literally has tracking code on every page. That way, Google Analytics will capture all the stuff going on. Then, you can add your "event" to the end of EVERY link on the page, so that when a user clicks a link, it will redirect to the appropriate page on your site, but it will also record (in the URL from the href of the link) on Google Analytics, because GA sees everything going on inside the page, INCLUDING the full URL of the href value of a link. So, if your link looked like this, Google Analytics would record the whole URL, which you can later retrieve:
您可以制作一个在每个页面上都有跟踪代码的页面。这样,Google Analytics 将捕获所有正在发生的事情。然后,您可以将您的“事件”添加到页面上每个链接的末尾,这样当用户点击链接时,它会重定向到您网站上的相应页面,但它也会记录(在来自链接的 href)在 Google Analytics 上,因为 GA 可以看到页面内发生的所有事情,包括链接的 href 值的完整 URL。所以,如果你的链接看起来像这样,谷歌分析会记录整个 URL,你可以稍后检索:
<a href="page2.php?id=4492&event=clickedCatalog&preference=yellow">Link!</a>
...will record the full URL (page2.php?id=4492&event=clickedCatalog&preference=yellow) in GA, which you can see in the list of URLs visited on your site, by clicking through the menu called Context on the left hand side of Google Analytics main page.
...将page2.php?id=4492&event=clickedCatalog&preference=yellow在 GA 中记录完整的 URL ( ),您可以通过单击 Google Analytics 主页左侧的名为 Context 的菜单,在您网站上访问过的 URL 列表中看到它。
回答by P.T.
Yes, you can do HTTP requests directly to Google Analytics to track arbitrary applications. This is what the existing GA library for Android does for example (it issues HTTP_GET requests with a very specific set of URL parameters).
是的,您可以直接向 Google Analytics 发出 HTTP 请求以跟踪任意应用程序。例如,这就是现有的 Android GA 库所做的(它使用一组非常具体的 URL 参数发出 HTTP_GET 请求)。
There is no official documentation for using the underlying HTTP API as a client, but you can rely on it being pretty stable given the number of ancient javascript snippets lying around on the web, and the fixed library code that is compiled into existing Android applications. The GIF parameter troubleshootingdoc explains the how analytics data is encoded.
没有关于使用底层 HTTP API 作为客户端的官方文档,但鉴于网络上存在大量古老的 javascript 代码片段以及编译到现有 Android 应用程序中的固定库代码,您可以相信它非常稳定。该GIF参数故障排除文档解释了分析数据的编码方式。
Here is an existing project that provides a client library for pure Java applications: http://code.google.com/p/jgoogleanalytics/
这是一个为纯 Java 应用程序提供客户端库的现有项目:http: //code.google.com/p/jgoogleanalytics/
If you want to re-implement this in C#, the magic seems to all be in here: http://code.google.com/p/jgoogleanalytics/source/browse/trunk/src/main/java/com/boxysystems/jgoogleanalytics/GoogleAnalytics_v1_URLBuildingStrategy.java
如果你想在 C# 中重新实现它,魔法似乎都在这里:http: //code.google.com/p/jgoogleanalytics/source/browse/trunk/src/main/java/com/boxysystems/ jgoogleanalytics/GoogleAnalytics_v1_URLBuildingStrategy.java
回答by Oliver
Inspired by @i.amniels answer, I wrote a small wrapper around the Google Analytics Measurement Protocolto track events on the server side of our web application.
受到@i.amniels answer 的启发,我围绕Google Analytics Measurement Protocol编写了一个小包装器来跟踪我们 Web 应用程序服务器端的事件。
Here's a gistwith a class you can start with. It simply wraps the boiler plate code of sending POST request to the Google Analytics measurement protocol endpoint.
这是您可以开始的课程的要点。它只是包装了向 Google Analytics 测量协议端点发送 POST 请求的样板代码。
Using that wrapper you'll be able to write this:
使用该包装器,您将能够编写以下代码:
GoogleAnalyticsApi.TrackEvent("Video", "Play", "Vacation 2014")
回答by Pavel Morshenyuk
Inspired by @Oliver answer, I have updated C# code to be more up to date on sending POST data:
受@Oliver 回答的启发,我更新了 C# 代码,以便在发送 POST 数据时保持最新状态:
namespace Helpers
{
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
// More information about API - see https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide
public class GoogleAnalyticsHelper
{
private readonly string endpoint = "https://www.google-analytics.com/collect";
private readonly string googleVersion = "1";
private readonly string googleTrackingId; // UA-XXXXXXXXX-XX
private readonly string googleClientId; // 555 - any user identifier
public GoogleAnalyticsHelper(string trackingId, string clientId)
{
this.googleTrackingId = trackingId;
this.googleClientId = clientId;
}
public async Task<HttpResponseMessage> TrackEvent(string category, string action, string label, int? value = null)
{
if (string.IsNullOrEmpty(category))
throw new ArgumentNullException(nameof(category));
if (string.IsNullOrEmpty(action))
throw new ArgumentNullException(nameof(action));
using (var httpClient = new HttpClient())
{
var postData = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("v", googleVersion),
new KeyValuePair<string, string>("tid", googleTrackingId),
new KeyValuePair<string, string>("cid", googleClientId),
new KeyValuePair<string, string>("t", "event"),
new KeyValuePair<string, string>("ec", category),
new KeyValuePair<string, string>("ea", action)
};
if (label != null)
{
postData.Add(new KeyValuePair<string, string>("el", label));
}
if (value != null)
{
postData.Add(new KeyValuePair<string, string>("ev", value.ToString()));
}
return await httpClient.PostAsync(endpoint, new FormUrlEncodedContent(postData)).ConfigureAwait(false);
}
}
}
}
Can be found on GitHub Gist
可以在GitHub Gist上找到
Usage:
用法:
var helper = new GoogleAnalyticsHelper("UA-XXXXXXXXX-XX", "555");
var result = helper.TrackEvent("Orders", "Order Checkout", "OrderId #31337").Result;
if (!result.IsSuccessStatusCode)
{
new Exception("something went wrong");
}
回答by Aaron Sherman
In addition to @pavel-morshenyuk answer, if you want to correlate the event to the user who actioned on it, the code below will map the request to the google client id.
除了@pavel-morshenyuk 的回答之外,如果您想将事件与对其进行操作的用户相关联,下面的代码会将请求映射到谷歌客户端 ID。
string clientId = Guid.NewGuid().ToString();
if (Request != null && Request.Cookies != null && Request.Cookies.Get("_ga") != null && Request.Cookies.Get("_ga").Value != null)
{
clientId = Request.Cookies.Get("_ga").Value;
clientId = clientId.Replace("GA1.2.", "");
clientId = clientId.Replace("GA1.1.", "");
}
note at some point, this may need to be tweaked if GA changes their internal cookie tracking.
请注意,如果 GA 更改其内部 cookie 跟踪,则可能需要对此进行调整。

