APNsService.cs 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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. namespace OASystem.API.OAMethodLib.APNs
  10. {
  11. public enum NotificationType : int
  12. {
  13. Alert = 0,
  14. Sound = 1,
  15. Badge = 2,
  16. Silent = 3
  17. }
  18. /// <summary>
  19. /// APNs 生成 JWT token,添加服务的时候,使用单利
  20. /// </summary>
  21. public class APNsService : IAPNsService
  22. {
  23. static string token = null;
  24. static string baseUrl = null;
  25. private readonly IConfiguration _configuration;
  26. private readonly IHttpClientFactory _httpClientFactory;
  27. public APNsService(IConfiguration configuration, IHttpClientFactory httpClientFactory)
  28. {
  29. this._configuration = configuration;
  30. this._httpClientFactory = httpClientFactory;
  31. //APNsService.baseUrl = this._configuration["apple:pushNotificationServer"];
  32. APNsService.baseUrl = this._configuration["apple:pushNotificationServer_Production"];
  33. }
  34. /// <summary>
  35. /// 生成 APNs JWT token
  36. /// </summary>
  37. /// <returns></returns>
  38. public string GetnerateAPNsJWTToken()
  39. {
  40. return this.GetnerateAPNsJWTToken(APNsService.token);
  41. }
  42. /// <summary>
  43. /// 生成 APNs JWT token
  44. /// </summary>
  45. /// <returns></returns>
  46. private string GetnerateAPNsJWTToken(string oldToken)
  47. {
  48. var tokenHandler = new JwtSecurityTokenHandler();
  49. var iat = ((DateTime.UtcNow.Ticks - new DateTime(1970, 1, 1).Ticks) / TimeSpan.TicksPerSecond);
  50. // 判断原 token 是否超过 50 分钟,如果未超过,直接返回
  51. if (string.IsNullOrWhiteSpace(oldToken) == false)
  52. {
  53. JwtPayload oldPayload = tokenHandler.ReadJwtToken(oldToken).Payload;
  54. var oldIat = oldPayload.Claims.FirstOrDefault(c => c.Type == "iat");
  55. if (oldIat != null)
  56. {
  57. if (long.TryParse(oldIat.Value, out long oldIatValue) == true)
  58. {
  59. // 两次间隔小于 50 分钟,使用原 token
  60. if ((iat - oldIatValue) < (50 * 60))
  61. {
  62. return oldToken;
  63. }
  64. }
  65. }
  66. }
  67. var kid = _configuration["apple:kid"];
  68. var securityKey = _configuration["apple:securityKey"].Replace("\n", "");
  69. var iss = _configuration["apple:iss"];
  70. var claims = new Claim[]
  71. {
  72. new Claim("iss", iss),
  73. new Claim("iat", iat.ToString())
  74. };
  75. var eCDsa = ECDsa.Create();
  76. eCDsa.ImportPkcs8PrivateKey(Convert.FromBase64String(securityKey), out _);
  77. var key = new ECDsaSecurityKey(eCDsa);
  78. key.KeyId = kid;
  79. var signingCredentials = new SigningCredentials(key, SecurityAlgorithms.EcdsaSha256);
  80. var jwtHeader = new JwtHeader(signingCredentials);
  81. var jwtPayload = new JwtPayload(claims);
  82. var jwtSecurityToken = new JwtSecurityToken(jwtHeader, jwtPayload);
  83. APNsService.token = tokenHandler.WriteToken(jwtSecurityToken);
  84. return APNsService.token;
  85. }
  86. /// <summary>
  87. /// 发送推送通知
  88. /// </summary>
  89. /// <param name="apnsTopic">APP Id</param>
  90. /// <param name="deviceToken">设备标识</param>
  91. /// <param name="type">通知类型</param>
  92. /// <param name="title">标题</param>
  93. /// <param name="subtitle">子标题</param>
  94. /// <param name="body">通知内容</param>
  95. /// <returns></returns>
  96. public async Task<Result> PushNotification(string apnsTopic, string deviceToken, NotificationType type, string title, string subtitle, string body)
  97. {
  98. Result result = new Result() { Code = -1, Msg = "未知错误" };
  99. var responseData = FailedAPNsReponseData();
  100. var token = this.GetnerateAPNsJWTToken();
  101. var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, APNsService.baseUrl + deviceToken)
  102. {
  103. Headers =
  104. {
  105. { HeaderNames.Authorization, "bearer " + token },
  106. { "apns-topic", apnsTopic },
  107. { "apns-expiration", "0" }
  108. },
  109. Version = new Version(2, 0)
  110. };
  111. var notContent = new
  112. {
  113. aps = new
  114. {
  115. alert = new
  116. {
  117. title = title,
  118. subtitle = subtitle,
  119. body = body
  120. }
  121. }
  122. };
  123. //var content = new StringContent(JsonSerializerTool.SerializeDefault(notContent), System.Text.Encoding.UTF8, Application.Json);
  124. var content = new StringContent(System.Text.Json.JsonSerializer.Serialize(notContent));
  125. httpRequestMessage.Content = content;
  126. var httpClient = _httpClientFactory.CreateClient();
  127. try
  128. {
  129. var httpResponseMessage = await httpClient.SendAsync(httpRequestMessage);
  130. if (httpResponseMessage.IsSuccessStatusCode)
  131. {
  132. responseData.Code = 200;
  133. result.Code = 0;
  134. result.Msg = "";
  135. result.Data = responseData;
  136. return result;
  137. }
  138. else
  139. {
  140. responseData.Data = httpResponseMessage.StatusCode;
  141. result.Code = -2;
  142. result.Msg = "";
  143. result.Data = responseData;
  144. return result;
  145. }
  146. }
  147. catch (Exception e)
  148. {
  149. responseData.Data = e.Message;
  150. result.Code = -3;
  151. result.Msg = "";
  152. result.Data = responseData;
  153. return result;
  154. }
  155. }
  156. public APNsReponseData FailedAPNsReponseData()
  157. {
  158. return new APNsReponseData() { Code = 400, Data = "" };
  159. }
  160. }
  161. public class APNsReponseData
  162. {
  163. public int Code { get; set; } = 0;
  164. public object Data { get; set; } = "";
  165. }
  166. }