GAHelper.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net.Http;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.Windows.Forms;
  8. namespace RevokeMsgPatcher.Utils
  9. {
  10. /// <summary>
  11. /// 用于软件的 Google Analytics 实现 By huiyadanli
  12. /// 相关文档:
  13. /// 指南 https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide
  14. /// 参数 https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters
  15. /// 测试 https://ga-dev-tools.appspot.com/hit-builder/
  16. /// </summary>
  17. public class GAHelper
  18. {
  19. // 根据实际情况修改
  20. private static readonly HttpClient client = HttpUtil.Client;
  21. private const string GAUrl = "https://www.google-analytics.com/collect";
  22. // 根据实际使用分析账号设置
  23. private const string tid = "UA-80358493-2"; // GA Tracking ID / Property ID.
  24. private static readonly string cid = Device.Value(); // Anonymous Client ID. // Guid.NewGuid().ToString()
  25. // 屏幕分辨率(可选)
  26. private static readonly string sr = Screen.PrimaryScreen.Bounds.Width + "x" + Screen.PrimaryScreen.Bounds.Height;
  27. public string UserAgent { get; set; }
  28. public GAHelper()
  29. {
  30. UserAgent = string.Format("Hui Google Analytics Tracker/1.0 ({0}; {1}; {2})", Environment.OSVersion.Platform.ToString(), Environment.OSVersion.Version.ToString(), Environment.OSVersion.VersionString);
  31. }
  32. public async Task RequestPageViewAsync(string page, string title = null)
  33. {
  34. try
  35. {
  36. if (!page.StartsWith("/"))
  37. {
  38. page = "/" + page;
  39. }
  40. // 请求参数
  41. var values = new Dictionary<string, string>
  42. {
  43. { "v", "1" }, // 当前必填1
  44. { "tid", tid },
  45. { "cid", cid },
  46. { "ua", UserAgent },
  47. { "t", "pageview" },
  48. { "sr", sr },
  49. { "dp", page },
  50. { "dt", title },
  51. };
  52. var content = new FormUrlEncodedContent(values);
  53. var response = await client.PostAsync(GAUrl, content);
  54. }
  55. catch (Exception ex)
  56. {
  57. Console.WriteLine("GAHelper:" + ex.Message);
  58. }
  59. }
  60. public void RequestPageView(string page, string title = null)
  61. {
  62. Task.Run(() => RequestPageViewAsync(page, title));
  63. }
  64. }
  65. }