APNsService.cs 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  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<string> PushNotification(string apnsTopic, string deviceToken, NotificationType type, string title, string subtitle, string body)
  97. {
  98. var responseData = FailedAPNsReponseData();
  99. var token = this.GetnerateAPNsJWTToken();
  100. var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, APNsService.baseUrl + deviceToken)
  101. {
  102. Headers =
  103. {
  104. { HeaderNames.Authorization, "bearer " + token },
  105. { "apns-topic", apnsTopic },
  106. { "apns-expiration", "0" }
  107. },
  108. Version = new Version(2, 0)
  109. };
  110. var notContent = new
  111. {
  112. aps = new
  113. {
  114. alert = new
  115. {
  116. title = title,
  117. subtitle = subtitle,
  118. body = body
  119. }
  120. }
  121. };
  122. //var content = new StringContent(JsonSerializerTool.SerializeDefault(notContent), System.Text.Encoding.UTF8, Application.Json);
  123. var content = new StringContent(System.Text.Json.JsonSerializer.Serialize(notContent));
  124. httpRequestMessage.Content = content;
  125. var httpClient = _httpClientFactory.CreateClient();
  126. try
  127. {
  128. var httpResponseMessage = await httpClient.SendAsync(httpRequestMessage);
  129. if (httpResponseMessage.IsSuccessStatusCode)
  130. {
  131. responseData.Code = 200;
  132. return System.Text.Json.JsonSerializer.Serialize(responseData);
  133. }
  134. else
  135. {
  136. responseData.Data = httpResponseMessage.StatusCode;
  137. return System.Text.Json.JsonSerializer.Serialize(responseData);
  138. }
  139. }
  140. catch (Exception e)
  141. {
  142. responseData.Data = e.Message;
  143. return System.Text.Json.JsonSerializer.Serialize(responseData);
  144. }
  145. }
  146. public APNsReponseData FailedAPNsReponseData()
  147. {
  148. return new APNsReponseData() { Code = 400, Data = "" };
  149. }
  150. }
  151. public class APNsReponseData
  152. {
  153. public int Code { get; set; } = 0;
  154. public object Data { get; set; } = "";
  155. }
  156. }