APNsService.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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 iss = _configuration["apple:iss"];
  97. var claims = new Claim[]
  98. {
  99. new Claim("iss", iss),
  100. new Claim("iat", iat.ToString())
  101. };
  102. try
  103. {
  104. var eCDsa = ECDsa.Create();
  105. eCDsa.ImportPkcs8PrivateKey(Convert.FromBase64String(securityKey), out _);
  106. var key = new ECDsaSecurityKey(eCDsa);
  107. key.KeyId = kid;
  108. var signingCredentials = new SigningCredentials(key, SecurityAlgorithms.EcdsaSha256);
  109. var jwtHeader = new JwtHeader(signingCredentials);
  110. var jwtPayload = new JwtPayload(claims);
  111. var jwtSecurityToken = new JwtSecurityToken(jwtHeader, jwtPayload);
  112. APNsService.token = tokenHandler.WriteToken(jwtSecurityToken);
  113. }
  114. catch (Exception ex)
  115. {
  116. return $"[ECDsa] ExMsg:[{ex.Message}]";
  117. }
  118. return APNsService.token;
  119. }
  120. public async Task<Result> PushNotification1(string apnsTopic, string deviceToken, NotificationType type, string title, string subtitle, string body)
  121. {
  122. var res = new Result() { Code = 0, Msg = "", Data = "" };
  123. res.Msg += $"[PushNotification1] --> Start\t\t\t\t\t";
  124. //This string is for extracting libcurl and ssl libs to the bin directory.
  125. CurlResources.Init();
  126. var global = CurlNative.Init();
  127. var easy = CurlNative.Easy.Init();
  128. string content=string.Empty;
  129. try
  130. {
  131. var token = GetnerateAPNsJWTToken(); ;
  132. res.Msg += $"[PushNotification1] --> Token:[{token}]\t\t\t\t\t";
  133. var dataCopier = new DataCallbackCopier();
  134. CurlNative.Easy.SetOpt(easy, CURLoption.URL, $"https://api.push.apple.com:443/3/device/{deviceToken}");
  135. CurlNative.Easy.SetOpt(easy, CURLoption.WRITEFUNCTION, dataCopier.DataHandler);
  136. //This string is needed when you call a https endpoint.
  137. CurlNative.Easy.SetOpt(easy, CURLoption.CAINFO, CurlResources.CaBundlePath);
  138. var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, APNsService.baseUrl + deviceToken)
  139. {
  140. Headers =
  141. {
  142. { HeaderNames.Authorization, "bearer " + token },
  143. { "apns-topic", apnsTopic },
  144. { "apns-expiration", "0" }
  145. },
  146. Version = new Version(2, 0)
  147. };
  148. res.Msg += $"[PushNotification1] --> httpRequestMessage:baseUrl[{APNsService.baseUrl + deviceToken}]\t\t\t\t\t";
  149. var notContent = new
  150. {
  151. aps = new
  152. {
  153. alert = new
  154. {
  155. title = title,
  156. subtitle = subtitle,
  157. body = body
  158. }
  159. }
  160. };
  161. var headers = CurlNative.Slist.Append(SafeSlistHandle.Null, $"Authorization: Bearer {token}");
  162. CurlNative.Slist.Append(headers, $"apns-topic: {apnsTopic}");
  163. CurlNative.Slist.Append(headers, $"apns-expiration: 0");
  164. CurlNative.Easy.SetOpt(easy, CURLoption.HTTPHEADER, headers.DangerousGetHandle());
  165. var contentJson = new StringContent(System.Text.Json.JsonSerializer.Serialize(notContent), System.Text.Encoding.UTF8, Application.Json);
  166. CurlNative.Easy.SetOpt(easy, CURLoption.POSTFIELDS, System.Text.Json.JsonSerializer.Serialize(notContent));
  167. //Your set of ciphers, full list is here https://curl.se/docs/ssl-ciphers.html
  168. CurlNative.Easy.SetOpt(easy, CURLoption.SSL_CIPHER_LIST, "ECDHE-RSA-AES256-GCM-SHA384");
  169. res.Msg += $"[PushNotification1] --> 发送请求\t\t\t\t\t";
  170. CurlNative.Easy.Perform(easy);
  171. content = Encoding.UTF8.GetString(dataCopier.Stream.ToArray());
  172. }
  173. catch (Exception ex)
  174. {
  175. res.Msg += $"[PushNotification1] ExMsg:{ex.Message}";
  176. if (ex.InnerException != null)
  177. {
  178. res.Msg += $"[PushNotification1] InnerException:{ex.InnerException.Message}";
  179. }
  180. }
  181. finally
  182. {
  183. easy.Dispose();
  184. if (global == CURLcode.OK)
  185. CurlNative.Cleanup();
  186. }
  187. res.Data = content;
  188. return res;
  189. }
  190. /// <summary>
  191. /// 发送推送通知
  192. /// </summary>
  193. /// <param name="apnsTopic">APP Id</param>
  194. /// <param name="deviceToken">设备标识</param>[文件:AuthKey_RMV7Y4KM9V.p8]
  195. /// <param name="type">通知类型</param>
  196. /// <param name="title">标题</param>
  197. /// <param name="subtitle">子标题</param>
  198. /// <param name="body">通知内容</param>
  199. /// <returns></returns>
  200. public async Task<Result> PushNotification(string apnsTopic, string deviceToken, NotificationType type, string title, string subtitle, string body)
  201. {
  202. Result result = new Result() { Code = -1, Msg = "[PushNotification] Start" };
  203. result.Msg += "\r\n[PushNotification] Start";
  204. _logger.LogInformation($"[PushNotification] Start");
  205. var responseData = FailedAPNsReponseData();
  206. var token = this.GetnerateAPNsJWTToken();
  207. try
  208. {
  209. var _httpClientFactory = new HttpClient { BaseAddress = new Uri("https://api.push.apple.com:443/3/device/") };
  210. result.Msg += $"\r\n[PushNotification] --> [HttpClient] --> Init --> jsonStr:{JsonConvert.SerializeObject(_httpClientFactory)}";
  211. var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, APNsService.baseUrl + deviceToken)
  212. {
  213. Headers =
  214. {
  215. { HeaderNames.Authorization, "bearer " + token },
  216. { "apns-topic", apnsTopic },
  217. { "apns-expiration", "0" }
  218. },
  219. Version = new Version(2, 0)
  220. };
  221. result.Msg += $"\r\n[PushNotification] --> [httpRequestMessage] --> Init --> jsonStr:{JsonConvert.SerializeObject(httpRequestMessage)}";
  222. var notContent = new
  223. {
  224. aps = new
  225. {
  226. alert = new
  227. {
  228. title = title,
  229. subtitle = subtitle,
  230. body = body
  231. }
  232. }
  233. };
  234. //var content = new StringContent(JsonSerializerTool.SerializeDefault(notContent), System.Text.Encoding.UTF8, Application.Json);
  235. var content = new StringContent(System.Text.Json.JsonSerializer.Serialize(notContent), System.Text.Encoding.UTF8, Application.Json);
  236. httpRequestMessage.Content = content;
  237. result.Msg += $"\r\n[PushNotification] --> [httpRequestMessage] --> Content --> jsonStr:{JsonConvert.SerializeObject(httpRequestMessage)}";
  238. try
  239. {
  240. //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13;
  241. //HttpClientHandler handler = new HttpClientHandler()
  242. //{
  243. // Proxy = new WebProxy("https://api.push.apple.com:443/3/device/"),
  244. // SslProtocols = System.Security.Authentication.SslProtocols.Tls12, // Enforce TLS 1.2
  245. // UseProxy = true
  246. //};
  247. //HttpClient client = new HttpClient(handler);
  248. //var httpResponseMessage = await client.SendAsync(httpRequestMessage);
  249. var httpResponseMessage = await _httpClientFactory.SendAsync(httpRequestMessage);
  250. if (httpResponseMessage.IsSuccessStatusCode)
  251. {
  252. responseData.Code = 200;
  253. result.Code = 0;
  254. result.Msg = "";
  255. result.Data = responseData;
  256. result.Msg += $"\r\n[PushNotification] End jsonStr[{JsonConvert.SerializeObject(result)}]";
  257. return result;
  258. }
  259. else
  260. {
  261. responseData.Data = httpResponseMessage.StatusCode;
  262. result.Code = -2;
  263. result.Msg = "";
  264. result.Data = responseData;
  265. result.Msg += $"\r\n[PushNotification] End jsonStr[{JsonConvert.SerializeObject(result)}]";
  266. return result;
  267. }
  268. }
  269. catch (Exception e)
  270. {
  271. responseData.Data = e.Message;
  272. result.Code = -3;
  273. result.Msg = "";
  274. result.Data = responseData;
  275. result.Msg += $"\r\n[PushNotification] --> [httpClientFactory] ExceptionMsg:{e.Message}";
  276. result.Msg += $"\r\n[PushNotification] --> [httpClientFactory] InnerExceptionData:{e.InnerException}";
  277. result.Msg += $"\r\n[PushNotification] --> [httpClientFactory] InnerExceptionMsg:{e.InnerException.Message}";
  278. return result;
  279. }
  280. }
  281. catch (Exception ex)
  282. {
  283. result.Msg += $"\r\n[PushNotification] InnerExceptionData:{JsonConvert.SerializeObject(ex.InnerException)}";
  284. result.Msg += $"\r\n[PushNotification] InnerExceptionMsg:{ex.InnerException.Message}";
  285. }
  286. return result;
  287. }
  288. public APNsReponseData FailedAPNsReponseData()
  289. {
  290. return new APNsReponseData() { Code = 400, Data = "" };
  291. }
  292. }
  293. public class APNsReponseData
  294. {
  295. public int Code { get; set; } = 0;
  296. public object Data { get; set; } = "";
  297. }
  298. }