APNsService.cs 6.7 KB

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