APNsService.cs 6.7 KB

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