LEIYI před 4 měsíci
rodič
revize
e7ab72654b

+ 4 - 4
OASystem/OASystem.Api/Controllers/GroupsController.cs

@@ -11057,18 +11057,18 @@ ORDER by  gctggrc.id DESC
                 if (_dto.Id == 0) content = $"[新增-酒店费用录入({groupInfo?.TeamName ?? "-"})]一项费用:{(ccpInfo.PayMoney * ccpInfo.DayRate).ToString("#0.00")} CNY;";
                 else if (_dto.Id > 0) content = $"[更新-酒店费用录入({groupInfo?.TeamName ?? "-"})]一项费用:{(ccpInfo.PayMoney * ccpInfo.DayRate).ToString("#0.00")} CNY;";
 
-                Logs($"【iOS推送通知Exceptio1】Start");
+               
 
                 try
                 {
-
+                    Logs($"【iOS推送通知PostHotelReservationsAddOrEdit】Start");
                     var iosRes = await APNsTools.iOS_PushNotifications("051", title, "", content);
-                    Logs($"【iOS推送通知Exception2】End Response:[{JsonConvert.SerializeObject(iosRes)}]");
+                    Logs($"【iOS推送通知PostHotelReservationsAddOrEdit】End Response:[{JsonConvert.SerializeObject(iosRes)}]");
                 }
                 catch (Exception ex )
                 {
 
-                    Logs($"【iOS推送通知Exception2-1】[{ex.Message}]");
+                    Logs($"【iOS推送通知-PostHotelReservationsAddOrEdit-Exception】[{ex.Message}]");
                 }
 
             }

+ 110 - 62
OASystem/OASystem.Api/OAMethodLib/APNs/APNsService.cs

@@ -6,6 +6,10 @@ using static System.Net.Mime.MediaTypeNames;
 using Microsoft.Net.Http.Headers;
 using Microsoft.Extensions.Configuration;
 using NPOI.SS.Formula.Functions;
+using System.Net.Http;
+using Flurl.Http.Configuration;
+using System.Net;
+using QuzrtzJob.Factory;
 
 namespace OASystem.API.OAMethodLib.APNs
 {
@@ -25,16 +29,19 @@ namespace OASystem.API.OAMethodLib.APNs
         static string token = null;
         static string baseUrl = null;
 
+        private readonly ILogger<APNsService> _logger;
+        //private static readonly HttpClient _httpClientFactory = new HttpClient { BaseAddress = new Uri("https://api.push.apple.com:443/3/device/") };
         private readonly IConfiguration _configuration;
-        private readonly IHttpClientFactory _httpClientFactory;
-        private readonly Serilog.ILogger _logger;
-        public APNsService(IConfiguration configuration, IHttpClientFactory httpClientFactory)
+        //private readonly IHttpClientFactory _httpClientFactory;
+        public APNsService(ILogger<APNsService> logger,IConfiguration configuration)
         {
             this._configuration = configuration;
-            this._httpClientFactory = httpClientFactory;
-
+            //this._httpClientFactory = httpClientFactory;
             //APNsService.baseUrl = this._configuration["apple:pushNotificationServer"];
-            APNsService.baseUrl = this._configuration["apple:pushNotificationServer_Production"];
+            //APNsService.baseUrl = this._configuration["apple:pushNotificationServer_Production"];
+            //
+            //APNsService.baseUrl = string.Format("https://api.push.apple.com:443/3/device/");
+            _logger = logger;
         }
 
         /// <summary>
@@ -76,29 +83,35 @@ namespace OASystem.API.OAMethodLib.APNs
             var kid = _configuration["apple:kid"];
             var securityKey = _configuration["apple:securityKey"].Replace("\n", "");
             var iss = _configuration["apple:iss"];
-
             var claims = new Claim[]
             {
-            new Claim("iss", iss),
-            new Claim("iat", iat.ToString())
+                new Claim("iss", iss),
+                new Claim("iat", iat.ToString())
             };
 
-            var eCDsa = ECDsa.Create();
-
-            eCDsa.ImportPkcs8PrivateKey(Convert.FromBase64String(securityKey), out _);
+            try
+            {
+                var eCDsa = ECDsa.Create();
 
-            var key = new ECDsaSecurityKey(eCDsa);
+                eCDsa.ImportPkcs8PrivateKey(Convert.FromBase64String(securityKey), out _);
 
-            key.KeyId = kid;
+                var key = new ECDsaSecurityKey(eCDsa);
 
-            var signingCredentials = new SigningCredentials(key, SecurityAlgorithms.EcdsaSha256);
-            var jwtHeader = new JwtHeader(signingCredentials);
-            var jwtPayload = new JwtPayload(claims);
+                key.KeyId = kid;
 
-            var jwtSecurityToken = new JwtSecurityToken(jwtHeader, jwtPayload);
+                var signingCredentials = new SigningCredentials(key, SecurityAlgorithms.EcdsaSha256);
+                var jwtHeader = new JwtHeader(signingCredentials);
+                var jwtPayload = new JwtPayload(claims);
 
-            APNsService.token = tokenHandler.WriteToken(jwtSecurityToken);
+                var jwtSecurityToken = new JwtSecurityToken(jwtHeader, jwtPayload);
 
+                APNsService.token = tokenHandler.WriteToken(jwtSecurityToken);
+            }
+            catch (Exception ex)
+            {
+                return $"[ECDsa] ExMsg:[{ex.Message}]";
+            }
+            
             return APNsService.token;
         }
 
@@ -114,69 +127,104 @@ namespace OASystem.API.OAMethodLib.APNs
         /// <returns></returns>
         public async Task<Result> PushNotification(string apnsTopic, string deviceToken, NotificationType type, string title, string subtitle, string body)
         {
-            Result result = new Result() { Code = -1, Msg = "未知错误" };
+            Result result = new Result() { Code = -1, Msg = "[PushNotification] Start" };
+
+            result.Msg += "\r\n[PushNotification] Start";
+            _logger.LogInformation($"[PushNotification] Start");
             var responseData = FailedAPNsReponseData();
             var token = this.GetnerateAPNsJWTToken();
-            var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, APNsService.baseUrl + deviceToken)
-            {
-                Headers =
-            {
-                { HeaderNames.Authorization, "bearer " +  token },
-                { "apns-topic", apnsTopic },
-                { "apns-expiration", "0" }
-            },
-                Version = new Version(2, 0)
-            };
 
-            var notContent = new
+            try
             {
-                aps = new
+                var _httpClientFactory = new HttpClient { BaseAddress = new Uri("https://api.push.apple.com:443/3/device/") };
+                result.Msg += $"\r\n[PushNotification] --> [HttpClient] --> Init --> jsonStr:{JsonConvert.SerializeObject(_httpClientFactory)}";
+
+                var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, APNsService.baseUrl + deviceToken)
                 {
-                    alert = new
+                    Headers =
                     {
-                        title = title,
-                        subtitle = subtitle,
-                        body = body
+                        { HeaderNames.Authorization, "bearer " +  token },
+                        { "apns-topic", apnsTopic },
+                        { "apns-expiration", "0" }
+                    },
+                    Version = new Version(2, 0)
+                };
+                result.Msg += $"\r\n[PushNotification] --> [httpRequestMessage] --> Init --> jsonStr:{JsonConvert.SerializeObject(httpRequestMessage)}";
+                var notContent = new
+                {
+                    aps = new
+                    {
+                        alert = new
+                        {
+                            title = title,
+                            subtitle = subtitle,
+                            body = body
+                        }
                     }
-                }
-            };
-            //var content = new StringContent(JsonSerializerTool.SerializeDefault(notContent), System.Text.Encoding.UTF8, Application.Json);
+                };
+                //var content = new StringContent(JsonSerializerTool.SerializeDefault(notContent), System.Text.Encoding.UTF8, Application.Json);
 
-            var content = new StringContent(System.Text.Json.JsonSerializer.Serialize(notContent));
+                var content = new StringContent(System.Text.Json.JsonSerializer.Serialize(notContent));
 
-            httpRequestMessage.Content = content;
+                httpRequestMessage.Content = content;
 
-            var httpClient = _httpClientFactory.CreateClient();
-            try
-            {
-                var httpResponseMessage = await httpClient.SendAsync(httpRequestMessage);
-
-                if (httpResponseMessage.IsSuccessStatusCode)
+                result.Msg += $"\r\n[PushNotification] --> [httpRequestMessage] --> Content --> jsonStr:{JsonConvert.SerializeObject(httpRequestMessage)}";
+                try
                 {
-                    responseData.Code = 200;
-                    result.Code = 0;
-                    result.Msg = "";
-                    result.Data = responseData;
-                    return result;
+                    //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13;
+
+                    //HttpClientHandler handler = new HttpClientHandler()
+                    //{
+                    //    Proxy = new WebProxy("https://api.push.apple.com:443/3/device/"),
+                    //    SslProtocols = System.Security.Authentication.SslProtocols.Tls12, // Enforce TLS 1.2
+                    //    UseProxy = true
+                    //};
+                    //HttpClient client = new HttpClient(handler);
+
+                    //var httpResponseMessage = await client.SendAsync(httpRequestMessage);
+                    var httpResponseMessage = await _httpClientFactory.SendAsync(httpRequestMessage);
+
+                    if (httpResponseMessage.IsSuccessStatusCode)
+                    {
+                        responseData.Code = 200;
+                        result.Code = 0;
+                        result.Msg = "";
+                        result.Data = responseData;
+                        result.Msg += $"\r\n[PushNotification] End jsonStr[{JsonConvert.SerializeObject(result)}]";
+                        return result;
+                    }
+                    else
+                    {
+                        responseData.Data = httpResponseMessage.StatusCode;
+                        result.Code = -2;
+                        result.Msg = "";
+                        result.Data = responseData;
+                        result.Msg += $"\r\n[PushNotification] End jsonStr[{JsonConvert.SerializeObject(result)}]";
+
+                        return result;
+                    }
                 }
-                else
+                catch (Exception e)
                 {
-                    responseData.Data = httpResponseMessage.StatusCode;
-                    result.Code = -2;
+                    responseData.Data = e.Message;
+                    result.Code = -3;
                     result.Msg = "";
                     result.Data = responseData;
+
+                    result.Msg += $"\r\n[PushNotification] --> [httpClientFactory] ExceptionMsg:{e.Message}";
+                    result.Msg += $"\r\n[PushNotification] --> [httpClientFactory] InnerExceptionData:{e.InnerException}";
+                    result.Msg += $"\r\n[PushNotification] --> [httpClientFactory] InnerExceptionMsg:{e.InnerException.Message}";
                     return result;
                 }
             }
-            catch (Exception e)
+            catch (Exception ex)
             {
-                responseData.Data = e.Message;
-                result.Code = -3;
-                result.Msg = "";
-                result.Data = responseData;
-                _logger.Information(string.Format(@" APNs : {0}", e.Message));
-                return result;
+                result.Msg += $"\r\n[PushNotification] InnerExceptionData:{JsonConvert.SerializeObject(ex.InnerException)}";
+                result.Msg += $"\r\n[PushNotification] InnerExceptionMsg:{ex.InnerException.Message}";
             }
+
+
+            return result;
         }
 
         public APNsReponseData FailedAPNsReponseData()

+ 18 - 3
OASystem/OASystem.Api/OAMethodLib/APNs/APNsTools.cs

@@ -1,4 +1,6 @@
 using EyeSoft.Runtime.InteropServices;
+using OASystem.API.Controllers;
+using OASystem.API.OAMethodLib.Hub.Hubs;
 using OASystem.Domain.Entities.Groups;
 using OASystem.Infrastructure.Repositories.Login;
 
@@ -7,17 +9,30 @@ namespace OASystem.API.OAMethodLib.APNs
     public static class APNsTools
     {
         private static readonly DeviceTokenRepository _deviceTokenRep = AutofacIocManager.Instance.GetService<DeviceTokenRepository>();
+        
         //private static readonly IAPNsService _APNsService = AutofacIocManager.Instance.GetService<IAPNsService>();
 
         public static async Task<Result> iOS_PushNotifications(string Numbers, string title, string subtitle, string body)
         {
-            var _APNsService = AutofacIocManager.Instance.GetService<IAPNsService>();
-            var rst = await _deviceTokenRep.Query(s => s.Number == Numbers).FirstAsync();
-            //var rst = new Sys_DeviceToken() { DeviceToken = "08be7ba1ee42ecf36f695fd6b795b5e203295eaed0ba3857276141dbeee025ff" };
+            
             Result rst2 = new Result() { Code = -1, Msg = "" };
+            try
+            {
+
+
+                var _APNsService = AutofacIocManager.Instance.GetService<IAPNsService>();
+            var rst = await _deviceTokenRep.Query(s => s.Number == Numbers).FirstAsync();
+            //var rst = new Sys_DeviceToken() { DeviceToken = "08be7ba1ee42ecf36f695fd6b795b5e203295eaed0ba3857276141dbeee025ff" }
             if (rst != null)
             {
                 rst2 = await _APNsService.PushNotification("com.panamerican.oa2024", rst.DeviceToken, NotificationType.Alert, title, subtitle, body);
+            }
+
+            }
+            catch (Exception ex)
+            {
+
+
             }
             return rst2;
         }