APNsService.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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)
  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. var notContent = new
  159. {
  160. aps = new
  161. {
  162. alert = new
  163. {
  164. title = title,
  165. subtitle = subtitle,
  166. body = body
  167. }
  168. }
  169. };
  170. var headers = CurlNative.Slist.Append(SafeSlistHandle.Null, $"Authorization: Bearer {token}");
  171. CurlNative.Slist.Append(headers, $"apns-topic: {apnsTopic}");
  172. CurlNative.Slist.Append(headers, $"apns-expiration: 0");
  173. CurlNative.Easy.SetOpt(easy, CURLoption.HTTPHEADER, headers.DangerousGetHandle());
  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. //Your set of ciphers, full list is here https://curl.se/docs/ssl-ciphers.html
  177. CurlNative.Easy.SetOpt(easy, CURLoption.SSL_CIPHER_LIST, "ECDHE-RSA-AES256-GCM-SHA384");
  178. res.Msg += $"[PushNotification1] --> 发送请求";
  179. CurlNative.Easy.Perform(easy);
  180. content = Encoding.UTF8.GetString(dataCopier.Stream.ToArray());
  181. }
  182. catch (Exception ex)
  183. {
  184. res.Msg += $"[PushNotification1] ExMsg:{ex.Message}";
  185. if (ex.InnerException != null)
  186. {
  187. res.Msg += $"[PushNotification1] InnerException:{ex.InnerException.Message}";
  188. }
  189. }
  190. finally
  191. {
  192. easy.Dispose();
  193. if (global == CURLcode.OK)
  194. CurlNative.Cleanup();
  195. }
  196. res.Data = content;
  197. return res;
  198. }
  199. /// <summary>
  200. /// 发送推送通知
  201. /// </summary>
  202. /// <param name="apnsTopic">APP Id</param>
  203. /// <param name="deviceToken">设备标识</param>[文件:AuthKey_RMV7Y4KM9V.p8]
  204. /// <param name="type">通知类型</param>
  205. /// <param name="title">标题</param>
  206. /// <param name="subtitle">子标题</param>
  207. /// <param name="body">通知内容</param>
  208. /// <returns></returns>
  209. public async Task<Result> PushNotification(string apnsTopic, string deviceToken, NotificationType type, string title, string subtitle, string body)
  210. {
  211. Result result = new Result() { Code = -1, Msg = "[PushNotification] Start" };
  212. result.Msg += "\r\n[PushNotification] Start";
  213. _logger.LogInformation($"[PushNotification] Start");
  214. var responseData = FailedAPNsReponseData();
  215. var token = this.GetnerateAPNsJWTToken();
  216. try
  217. {
  218. var _httpClientFactory = new HttpClient { BaseAddress = new Uri("https://api.push.apple.com:443/3/device/") };
  219. result.Msg += $"\r\n[PushNotification] --> [HttpClient] --> Init --> jsonStr:{JsonConvert.SerializeObject(_httpClientFactory)}";
  220. var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, APNsService.baseUrl + deviceToken)
  221. {
  222. Headers =
  223. {
  224. { HeaderNames.Authorization, "bearer " + token },
  225. { "apns-topic", apnsTopic },
  226. { "apns-expiration", "0" }
  227. },
  228. Version = new Version(2, 0)
  229. };
  230. result.Msg += $"\r\n[PushNotification] --> [httpRequestMessage] --> Init --> jsonStr:{JsonConvert.SerializeObject(httpRequestMessage)}";
  231. var notContent = new
  232. {
  233. aps = new
  234. {
  235. alert = new
  236. {
  237. title = title,
  238. subtitle = subtitle,
  239. body = body
  240. }
  241. }
  242. };
  243. //var content = new StringContent(JsonSerializerTool.SerializeDefault(notContent), System.Text.Encoding.UTF8, Application.Json);
  244. var content = new StringContent(System.Text.Json.JsonSerializer.Serialize(notContent), System.Text.Encoding.UTF8, Application.Json);
  245. httpRequestMessage.Content = content;
  246. result.Msg += $"\r\n[PushNotification] --> [httpRequestMessage] --> Content --> jsonStr:{JsonConvert.SerializeObject(httpRequestMessage)}";
  247. try
  248. {
  249. //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13;
  250. //HttpClientHandler handler = new HttpClientHandler()
  251. //{
  252. // Proxy = new WebProxy("https://api.push.apple.com:443/3/device/"),
  253. // SslProtocols = System.Security.Authentication.SslProtocols.Tls12, // Enforce TLS 1.2
  254. // UseProxy = true
  255. //};
  256. //HttpClient client = new HttpClient(handler);
  257. //var httpResponseMessage = await client.SendAsync(httpRequestMessage);
  258. var httpResponseMessage = await _httpClientFactory.SendAsync(httpRequestMessage);
  259. if (httpResponseMessage.IsSuccessStatusCode)
  260. {
  261. responseData.Code = 200;
  262. result.Code = 0;
  263. result.Msg = "";
  264. result.Data = responseData;
  265. result.Msg += $"\r\n[PushNotification] End jsonStr[{JsonConvert.SerializeObject(result)}]";
  266. return result;
  267. }
  268. else
  269. {
  270. responseData.Data = httpResponseMessage.StatusCode;
  271. result.Code = -2;
  272. result.Msg = "";
  273. result.Data = responseData;
  274. result.Msg += $"\r\n[PushNotification] End jsonStr[{JsonConvert.SerializeObject(result)}]";
  275. return result;
  276. }
  277. }
  278. catch (Exception e)
  279. {
  280. responseData.Data = e.Message;
  281. result.Code = -3;
  282. result.Msg = "";
  283. result.Data = responseData;
  284. result.Msg += $"\r\n[PushNotification] --> [httpClientFactory] ExceptionMsg:{e.Message}";
  285. result.Msg += $"\r\n[PushNotification] --> [httpClientFactory] InnerExceptionData:{e.InnerException}";
  286. result.Msg += $"\r\n[PushNotification] --> [httpClientFactory] InnerExceptionMsg:{e.InnerException.Message}";
  287. return result;
  288. }
  289. }
  290. catch (Exception ex)
  291. {
  292. result.Msg += $"\r\n[PushNotification] InnerExceptionData:{JsonConvert.SerializeObject(ex.InnerException)}";
  293. result.Msg += $"\r\n[PushNotification] InnerExceptionMsg:{ex.InnerException.Message}";
  294. }
  295. return result;
  296. }
  297. public APNsReponseData FailedAPNsReponseData()
  298. {
  299. return new APNsReponseData() { Code = 400, Data = "" };
  300. }
  301. }
  302. public class APNsReponseData
  303. {
  304. public int Code { get; set; } = 0;
  305. public object Data { get; set; } = "";
  306. }
  307. }