APNsService.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. using System.Security.Claims;
  2. using System.Security.Cryptography;
  3. using Microsoft.IdentityModel.Tokens;
  4. using System.IdentityModel.Tokens.Jwt;
  5. using static System.Net.Mime.MediaTypeNames;
  6. using Microsoft.Net.Http.Headers;
  7. using Microsoft.Extensions.Configuration;
  8. using NPOI.SS.Formula.Functions;
  9. using System.Net.Http;
  10. using Flurl.Http.Configuration;
  11. using System.Net;
  12. using QuzrtzJob.Factory;
  13. using Org.BouncyCastle.Crypto.Parameters;
  14. using System.IO;
  15. using CurlThin;
  16. using CurlThin.Enums;
  17. using CurlThin.Helpers;
  18. using CurlThin.Native;
  19. using CurlThin.SafeHandles;
  20. namespace OASystem.API.OAMethodLib.APNs
  21. {
  22. public enum NotificationType : int
  23. {
  24. Alert = 0,
  25. Sound = 1,
  26. Badge = 2,
  27. Silent = 3
  28. }
  29. /// <summary>
  30. /// APNs 生成 JWT token,添加服务的时候,使用单利
  31. /// </summary>
  32. public class APNsService : IAPNsService
  33. {
  34. static string token = null;
  35. static string baseUrl = null;
  36. private readonly ILogger<APNsService> _logger;
  37. //private static readonly HttpClient _httpClientFactory = new HttpClient { BaseAddress = new Uri("https://api.push.apple.com:443/3/device/") };
  38. private readonly IConfiguration _configuration;
  39. //private readonly IHttpClientFactory _httpClientFactory;
  40. public APNsService(ILogger<APNsService> logger, IConfiguration configuration)
  41. {
  42. this._configuration = configuration;
  43. //this._httpClientFactory = httpClientFactory;
  44. //APNsService.baseUrl = this._configuration["apple:pushNotificationServer"];
  45. //APNsService.baseUrl = this._configuration["apple:pushNotificationServer_Production"];
  46. //
  47. //APNsService.baseUrl = string.Format("https://api.push.apple.com:443/3/device/");
  48. _logger = logger;
  49. }
  50. /// <summary>
  51. /// 生成 APNs JWT token
  52. /// </summary>
  53. /// <returns></returns>
  54. public string GetnerateAPNsJWTToken()
  55. {
  56. return this.GetnerateAPNsJWTToken(APNsService.token);
  57. }
  58. //private static CngKey GetPrivateKey()
  59. //{
  60. // using (var reader = System.IO.File.OpenText("File/AuthKey_RMV7Y4KM9V.p8"))
  61. // {
  62. // var ecPrivateKeyParameters = (ECPrivateKeyParameters)new PemReader(reader).ReadObject();
  63. // var x = ecPrivateKeyParameters.Parameters.G.AffineXCoord.GetEncoded();
  64. // var y = ecPrivateKeyParameters.Parameters.G.AffineYCoord.GetEncoded();
  65. // var d = ecPrivateKeyParameters.D.ToByteArrayUnsigned();
  66. // return EccKey.New(x, y, d);
  67. // }
  68. //}
  69. /// <summary>
  70. /// 生成 APNs JWT token
  71. /// </summary>
  72. /// <returns></returns>
  73. private string GetnerateAPNsJWTToken(string oldToken)
  74. {
  75. var tokenHandler = new JwtSecurityTokenHandler();
  76. var iat = ((DateTime.UtcNow.Ticks - new DateTime(1970, 1, 1).Ticks) / TimeSpan.TicksPerSecond);
  77. // 判断原 token 是否超过 50 分钟,如果未超过,直接返回
  78. if (string.IsNullOrWhiteSpace(oldToken) == false)
  79. {
  80. JwtPayload oldPayload = tokenHandler.ReadJwtToken(oldToken).Payload;
  81. var oldIat = oldPayload.Claims.FirstOrDefault(c => c.Type == "iat");
  82. if (oldIat != null)
  83. {
  84. if (long.TryParse(oldIat.Value, out long oldIatValue) == true)
  85. {
  86. // 两次间隔小于 50 分钟,使用原 token
  87. if ((iat - oldIatValue) < (50 * 60))
  88. {
  89. return oldToken;
  90. }
  91. }
  92. }
  93. }
  94. var kid = _configuration["apple:kid"];
  95. //var securityKey = _configuration["apple:securityKey"].Replace("\n", "");
  96. var securityKey = string.Format("MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQglyUl7hjI75YJUVMbZLN6TpkiFzuTXUN+UIjuJA7+y8ugCgYIKoZIzj0DAQehRANCAAS8GR7lKNst4KENCp45OXCMyiytvzK0qdRBrx0l+bMaHjiU+Upfox82G+Xy4wd8hI+0wMDh341aNelqEdYUUx3O");
  97. var iss = _configuration["apple:iss"];
  98. var claims = new Claim[]
  99. {
  100. new Claim("iss", iss),
  101. new Claim("iat", iat.ToString())
  102. };
  103. string msg = string.Empty;
  104. msg += $"[GetnerateAPNsJWTToken] 0";
  105. try
  106. {
  107. msg += $"[GetnerateAPNsJWTToken] 1";
  108. var eCDsa = ECDsa.Create();
  109. msg += $"[GetnerateAPNsJWTToken] 2";
  110. eCDsa.ImportPkcs8PrivateKey(Convert.FromBase64String(securityKey), out _);
  111. msg += $"[GetnerateAPNsJWTToken] 3";
  112. var key = new ECDsaSecurityKey(eCDsa);
  113. msg += $"[GetnerateAPNsJWTToken] 4";
  114. key.KeyId = kid;
  115. msg += $"[GetnerateAPNsJWTToken] 5";
  116. var signingCredentials = new SigningCredentials(key, SecurityAlgorithms.EcdsaSha256);
  117. msg += $"[GetnerateAPNsJWTToken] 6";
  118. var jwtHeader = new JwtHeader(signingCredentials);
  119. msg += $"[GetnerateAPNsJWTToken] 7";
  120. var jwtPayload = new JwtPayload(claims);
  121. msg += $"[GetnerateAPNsJWTToken] 8";
  122. var jwtSecurityToken = new JwtSecurityToken(jwtHeader, jwtPayload);
  123. msg += $"[GetnerateAPNsJWTToken] 9";
  124. APNsService.token = tokenHandler.WriteToken(jwtSecurityToken);
  125. }
  126. catch (Exception ex)
  127. {
  128. return msg += $"[GetnerateAPNsJWTToken] --> ExMsg:[{ex.Message}]";
  129. }
  130. return APNsService.token;
  131. }
  132. public async Task<Result> PushNotification1(string apnsTopic, string deviceToken, NotificationType type, string title, string subtitle, string body, bool isTarget, string viewCode, PageParam_PriceAuditH5 pageParam)
  133. {
  134. var res = new Result() { Code = 0, Msg = "", Data = "" };
  135. //This string is for extracting libcurl and ssl libs to the bin directory.
  136. CurlResources.Init();
  137. var global = CurlNative.Init();
  138. var easy = CurlNative.Easy.Init();
  139. string content = string.Empty;
  140. try
  141. {
  142. var token = GetnerateAPNsJWTToken();
  143. var dataCopier = new DataCallbackCopier();
  144. CurlNative.Easy.SetOpt(easy, CURLoption.URL, $"https://api.push.apple.com:443/3/device/{deviceToken}");
  145. CurlNative.Easy.SetOpt(easy, CURLoption.WRITEFUNCTION, dataCopier.DataHandler);
  146. //This string is needed when you call a https endpoint.
  147. CurlNative.Easy.SetOpt(easy, CURLoption.CAINFO, CurlResources.CaBundlePath);
  148. var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, APNsService.baseUrl + deviceToken)
  149. {
  150. Headers =
  151. {
  152. { HeaderNames.Authorization, "bearer " + token },
  153. { "apns-topic", apnsTopic },
  154. { "apns-expiration", "0" }
  155. },
  156. Version = new Version(2, 0)
  157. };
  158. if (isTarget)
  159. {
  160. var notContent = new
  161. {
  162. aps = new
  163. {
  164. alert = new
  165. {
  166. title = title,
  167. subtitle = subtitle,
  168. body = body
  169. }
  170. },
  171. ViewCode = viewCode,
  172. PageParam = pageParam
  173. };
  174. var contentJson = new StringContent(System.Text.Json.JsonSerializer.Serialize(notContent), System.Text.Encoding.UTF8, Application.Json);
  175. CurlNative.Easy.SetOpt(easy, CURLoption.POSTFIELDS, System.Text.Json.JsonSerializer.Serialize(notContent));
  176. }
  177. else
  178. {
  179. var notContent = new
  180. {
  181. aps = new
  182. {
  183. alert = new
  184. {
  185. title = title,
  186. subtitle = subtitle,
  187. body = body
  188. }
  189. }
  190. };
  191. var contentJson = new StringContent(System.Text.Json.JsonSerializer.Serialize(notContent), System.Text.Encoding.UTF8, Application.Json);
  192. CurlNative.Easy.SetOpt(easy, CURLoption.POSTFIELDS, System.Text.Json.JsonSerializer.Serialize(notContent));
  193. }
  194. var headers = CurlNative.Slist.Append(SafeSlistHandle.Null, $"Authorization: Bearer {token}");
  195. CurlNative.Slist.Append(headers, $"apns-topic: {apnsTopic}");
  196. CurlNative.Slist.Append(headers, $"apns-expiration: 0");
  197. CurlNative.Easy.SetOpt(easy, CURLoption.HTTPHEADER, headers.DangerousGetHandle());
  198. //Your set of ciphers, full list is here https://curl.se/docs/ssl-ciphers.html
  199. CurlNative.Easy.SetOpt(easy, CURLoption.SSL_CIPHER_LIST, "ECDHE-RSA-AES256-GCM-SHA384");
  200. res.Msg += $"[PushNotification1] --> 发送请求";
  201. CurlNative.Easy.Perform(easy);
  202. content = Encoding.UTF8.GetString(dataCopier.Stream.ToArray());
  203. }
  204. catch (Exception ex)
  205. {
  206. res.Msg += $"[PushNotification1] ExMsg:{ex.Message}";
  207. if (ex.InnerException != null)
  208. {
  209. res.Msg += $"[PushNotification1] InnerException:{ex.InnerException.Message}";
  210. }
  211. }
  212. finally
  213. {
  214. easy.Dispose();
  215. if (global == CURLcode.OK)
  216. CurlNative.Cleanup();
  217. }
  218. res.Data = content;
  219. return res;
  220. }
  221. /// <summary>
  222. /// 发送推送通知
  223. /// </summary>
  224. /// <param name="apnsTopic">APP Id</param>
  225. /// <param name="deviceToken">设备标识</param>[文件:AuthKey_RMV7Y4KM9V.p8]
  226. /// <param name="type">通知类型</param>
  227. /// <param name="title">标题</param>
  228. /// <param name="subtitle">子标题</param>
  229. /// <param name="body">通知内容</param>
  230. /// <returns></returns>
  231. public async Task<Result> PushNotification(string apnsTopic, string deviceToken, NotificationType type, string title, string subtitle, string body)
  232. {
  233. Result result = new Result() { Code = -1, Msg = "[PushNotification] Start" };
  234. result.Msg += "\r\n[PushNotification] Start";
  235. _logger.LogInformation($"[PushNotification] Start");
  236. var responseData = FailedAPNsReponseData();
  237. var token = this.GetnerateAPNsJWTToken();
  238. try
  239. {
  240. var _httpClientFactory = new HttpClient { BaseAddress = new Uri("https://api.push.apple.com:443/3/device/") };
  241. result.Msg += $"\r\n[PushNotification] --> [HttpClient] --> Init --> jsonStr:{JsonConvert.SerializeObject(_httpClientFactory)}";
  242. var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, APNsService.baseUrl + deviceToken)
  243. {
  244. Headers =
  245. {
  246. { HeaderNames.Authorization, "bearer " + token },
  247. { "apns-topic", apnsTopic },
  248. { "apns-expiration", "0" }
  249. },
  250. Version = new Version(2, 0)
  251. };
  252. result.Msg += $"\r\n[PushNotification] --> [httpRequestMessage] --> Init --> jsonStr:{JsonConvert.SerializeObject(httpRequestMessage)}";
  253. var notContent = new
  254. {
  255. aps = new
  256. {
  257. alert = new
  258. {
  259. title = title,
  260. subtitle = subtitle,
  261. body = body
  262. }
  263. }
  264. };
  265. //var content = new StringContent(JsonSerializerTool.SerializeDefault(notContent), System.Text.Encoding.UTF8, Application.Json);
  266. var content = new StringContent(System.Text.Json.JsonSerializer.Serialize(notContent), System.Text.Encoding.UTF8, Application.Json);
  267. httpRequestMessage.Content = content;
  268. result.Msg += $"\r\n[PushNotification] --> [httpRequestMessage] --> Content --> jsonStr:{JsonConvert.SerializeObject(httpRequestMessage)}";
  269. try
  270. {
  271. //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13;
  272. //HttpClientHandler handler = new HttpClientHandler()
  273. //{
  274. // Proxy = new WebProxy("https://api.push.apple.com:443/3/device/"),
  275. // SslProtocols = System.Security.Authentication.SslProtocols.Tls12, // Enforce TLS 1.2
  276. // UseProxy = true
  277. //};
  278. //HttpClient client = new HttpClient(handler);
  279. //var httpResponseMessage = await client.SendAsync(httpRequestMessage);
  280. var httpResponseMessage = await _httpClientFactory.SendAsync(httpRequestMessage);
  281. if (httpResponseMessage.IsSuccessStatusCode)
  282. {
  283. responseData.Code = 200;
  284. result.Code = 0;
  285. result.Msg = "";
  286. result.Data = responseData;
  287. result.Msg += $"\r\n[PushNotification] End jsonStr[{JsonConvert.SerializeObject(result)}]";
  288. return result;
  289. }
  290. else
  291. {
  292. responseData.Data = httpResponseMessage.StatusCode;
  293. result.Code = -2;
  294. result.Msg = "";
  295. result.Data = responseData;
  296. result.Msg += $"\r\n[PushNotification] End jsonStr[{JsonConvert.SerializeObject(result)}]";
  297. return result;
  298. }
  299. }
  300. catch (Exception e)
  301. {
  302. responseData.Data = e.Message;
  303. result.Code = -3;
  304. result.Msg = "";
  305. result.Data = responseData;
  306. result.Msg += $"\r\n[PushNotification] --> [httpClientFactory] ExceptionMsg:{e.Message}";
  307. result.Msg += $"\r\n[PushNotification] --> [httpClientFactory] InnerExceptionData:{e.InnerException}";
  308. result.Msg += $"\r\n[PushNotification] --> [httpClientFactory] InnerExceptionMsg:{e.InnerException.Message}";
  309. return result;
  310. }
  311. }
  312. catch (Exception ex)
  313. {
  314. result.Msg += $"\r\n[PushNotification] InnerExceptionData:{JsonConvert.SerializeObject(ex.InnerException)}";
  315. result.Msg += $"\r\n[PushNotification] InnerExceptionMsg:{ex.InnerException.Message}";
  316. }
  317. return result;
  318. }
  319. public APNsReponseData FailedAPNsReponseData()
  320. {
  321. return new APNsReponseData() { Code = 400, Data = "" };
  322. }
  323. }
  324. public class APNsReponseData
  325. {
  326. public int Code { get; set; } = 0;
  327. public object Data { get; set; } = "";
  328. }
  329. public class PageParam_PriceAuditH5
  330. {
  331. public string diid { get; set; }
  332. public string uid { get; set; }
  333. }
  334. }