Browse Source

ios 推送

LEIYI 4 months ago
parent
commit
300faf986e

+ 6 - 2
OASystem/OASystem.Api/Controllers/GroupsController.cs

@@ -11061,9 +11061,13 @@ ORDER by  gctggrc.id DESC
 
                 try
                 {
+
                     Logs($"【iOS推送通知PostHotelReservationsAddOrEdit】Start");
-                    var iosRes = await APNsTools.iOS_PushNotifications("051", title, "", content);
-                    Logs($"【iOS推送通知PostHotelReservationsAddOrEdit】End Response:[{JsonConvert.SerializeObject(iosRes)}]");
+                    var iosRes1 = await APNsTools.iOS_PushNotifications1("051", title, "", content);
+                    Logs($"【iOS推送通知PostHotelReservationsAddOrEdit】End Response:[{JsonConvert.SerializeObject(iosRes1)}]");
+                    //Logs($"【iOS推送通知PostHotelReservationsAddOrEdit】Start");
+                    //var iosRes = await APNsTools.iOS_PushNotifications("051", title, "", content);
+                    //Logs($"【iOS推送通知PostHotelReservationsAddOrEdit】End Response:[{JsonConvert.SerializeObject(iosRes)}]");
                 }
                 catch (Exception ex )
                 {

+ 6 - 0
OASystem/OASystem.Api/File/AuthKey_RMV7Y4KM9V.p8

@@ -0,0 +1,6 @@
+-----BEGIN PRIVATE KEY-----
+MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQglyUl7hjI75YJUVMb
+ZLN6TpkiFzuTXUN+UIjuJA7+y8ugCgYIKoZIzj0DAQehRANCAAS8GR7lKNst4KEN
+Cp45OXCMyiytvzK0qdRBrx0l+bMaHjiU+Upfox82G+Xy4wd8hI+0wMDh341aNelq
+EdYUUx3O
+-----END PRIVATE KEY-----

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

@@ -10,6 +10,13 @@ using System.Net.Http;
 using Flurl.Http.Configuration;
 using System.Net;
 using QuzrtzJob.Factory;
+using Org.BouncyCastle.Crypto.Parameters;
+using System.IO;
+using CurlThin;
+using CurlThin.Enums;
+using CurlThin.Helpers;
+using CurlThin.Native;
+using CurlThin.SafeHandles;
 
 namespace OASystem.API.OAMethodLib.APNs
 {
@@ -53,6 +60,18 @@ namespace OASystem.API.OAMethodLib.APNs
             return this.GetnerateAPNsJWTToken(APNsService.token);
         }
 
+        //private static CngKey GetPrivateKey()
+        //{
+        //    using (var reader = System.IO.File.OpenText("File/AuthKey_RMV7Y4KM9V.p8"))
+        //    {
+        //        var ecPrivateKeyParameters = (ECPrivateKeyParameters)new PemReader(reader).ReadObject();
+        //        var x = ecPrivateKeyParameters.Parameters.G.AffineXCoord.GetEncoded();
+        //        var y = ecPrivateKeyParameters.Parameters.G.AffineYCoord.GetEncoded();
+        //        var d = ecPrivateKeyParameters.D.ToByteArrayUnsigned();
+        //        return EccKey.New(x, y, d);
+        //    }
+        //}
+
         /// <summary>
         /// 生成 APNs JWT token
         /// </summary>
@@ -115,11 +134,101 @@ namespace OASystem.API.OAMethodLib.APNs
             return APNsService.token;
         }
 
+        public async Task<Result>  PushNotification1(string apnsTopic, string deviceToken, NotificationType type, string title, string subtitle, string body)
+        {
+
+            var res = new Result() { Code = 0, Msg = "", Data = "" };
+
+            res.Msg += $"[PushNotification1] --> Start\t\t\t\t\t";
+            //This string is for extracting libcurl and ssl libs to the bin directory.
+            CurlResources.Init();
+            var global = CurlNative.Init();
+            var easy = CurlNative.Easy.Init();
+            string content=string.Empty;
+            try
+            {
+                var token = GetnerateAPNsJWTToken(); ;
+
+                res.Msg += $"[PushNotification1] --> Token:[{token}]\t\t\t\t\t";
+                var dataCopier = new DataCallbackCopier();
+
+                CurlNative.Easy.SetOpt(easy, CURLoption.URL, $"https://api.push.apple.com:443/3/device/{deviceToken}");
+                CurlNative.Easy.SetOpt(easy, CURLoption.WRITEFUNCTION, dataCopier.DataHandler);
+                //This string is needed when you call a https endpoint.
+                CurlNative.Easy.SetOpt(easy, CURLoption.CAINFO, CurlResources.CaBundlePath);
+
+
+                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)
+                };
+
+                res.Msg += $"[PushNotification1] --> httpRequestMessage:baseUrl[{APNsService.baseUrl + deviceToken}]\t\t\t\t\t";
+                var notContent = new
+                {
+                    aps = new
+                    {
+                        alert = new
+                        {
+                            title = title,
+                            subtitle = subtitle,
+                            body = body
+                        }
+                    }
+                };
+
+                var headers = CurlNative.Slist.Append(SafeSlistHandle.Null, $"Authorization: Bearer {token}");
+                CurlNative.Slist.Append(headers, $"apns-topic: {apnsTopic}");
+                CurlNative.Slist.Append(headers, $"apns-expiration: 0");
+
+                CurlNative.Easy.SetOpt(easy, CURLoption.HTTPHEADER, headers.DangerousGetHandle());
+
+                var contentJson = new StringContent(System.Text.Json.JsonSerializer.Serialize(notContent), System.Text.Encoding.UTF8, Application.Json);
+                CurlNative.Easy.SetOpt(easy, CURLoption.POSTFIELDS, System.Text.Json.JsonSerializer.Serialize(notContent));
+
+
+
+                //Your set of ciphers, full list is here https://curl.se/docs/ssl-ciphers.html
+                CurlNative.Easy.SetOpt(easy, CURLoption.SSL_CIPHER_LIST, "ECDHE-RSA-AES256-GCM-SHA384");
+
+
+
+                res.Msg += $"[PushNotification1] --> 发送请求\t\t\t\t\t";
+                CurlNative.Easy.Perform(easy);
+
+                content = Encoding.UTF8.GetString(dataCopier.Stream.ToArray());
+            }
+            catch (Exception ex)
+            {
+                res.Msg += $"[PushNotification1] ExMsg:{ex.Message}";
+                if (ex.InnerException != null)
+                {
+                    res.Msg += $"[PushNotification1] InnerException:{ex.InnerException.Message}";
+                }
+            }
+            finally
+            {
+                easy.Dispose();
+
+                if (global == CURLcode.OK)
+                    CurlNative.Cleanup();
+            }
+            res.Data = content;
+            return res;
+        }
+
+
         /// <summary>
         /// 发送推送通知
         /// </summary>
         /// <param name="apnsTopic">APP Id</param>
-        /// <param name="deviceToken">设备标识</param>
+        /// <param name="deviceToken">设备标识</param>[文件:AuthKey_RMV7Y4KM9V.p8]
         /// <param name="type">通知类型</param>
         /// <param name="title">标题</param>
         /// <param name="subtitle">子标题</param>

+ 27 - 0
OASystem/OASystem.Api/OAMethodLib/APNs/APNsTools.cs

@@ -36,5 +36,32 @@ namespace OASystem.API.OAMethodLib.APNs
             }
             return rst2;
         }
+
+        public static async Task<Result> iOS_PushNotifications1(string Numbers, string title, string subtitle, string body)
+        {
+
+            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.PushNotification1("com.panamerican.oa2024", rst.DeviceToken, NotificationType.Alert, title, subtitle, body);
+                }
+
+            }
+            catch (Exception ex)
+            {
+                rst2.Msg = $"[iOS_PushNotifications1] --> MSG:{ex.Message}";
+                rst2.Msg = $"[iOS_PushNotifications1] --> InnerException:{ex.InnerException .Message}";
+
+            }
+            return rst2;
+        }
+
     }
 }

+ 13 - 0
OASystem/OASystem.Api/OAMethodLib/APNs/IAPNsService.cs

@@ -19,5 +19,18 @@
         /// <param name="body">通知内容</param>
         /// <returns></returns>
         Task<Result> PushNotification(string apnsTopic, string deviceToken, NotificationType type, string title, string subtitle, string body);
+
+        /// <summary>
+        /// 发送推送通知
+        /// </summary>
+        /// <param name="apnsTopic">APP Id</param>
+        /// <param name="deviceToken">设备标识</param>
+        /// <param name="type">通知类型</param>
+        /// <param name="title">标题</param>
+        /// <param name="subtitle">子标题</param>
+        /// <param name="body">通知内容</param>
+        /// <returns></returns>
+        Task<Result> PushNotification1(string apnsTopic, string deviceToken, NotificationType type, string title, string subtitle, string body);
+
     }
 }

+ 8 - 0
OASystem/OASystem.Api/OASystem.API.csproj

@@ -32,6 +32,8 @@
     <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="12.0.0" />
     <PackageReference Include="Betalgo.OpenAI.GPT3" Version="6.8.3" />
     <PackageReference Include="BouncyCastle.NetCore" Version="1.8.8" />
+    <PackageReference Include="CurlThin" Version="0.0.7" />
+    <PackageReference Include="CurlThin.Native" Version="0.0.8" />
     <PackageReference Include="EPPlus" Version="7.4.1" />
     <PackageReference Include="Flurl.Http" Version="3.2.4" />
     <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.11" />
@@ -65,6 +67,12 @@
   <ItemGroup>
     <Resource Include="Images\VoucherHeader.png" />
   </ItemGroup>
+	
+  <ItemGroup>
+    <None Update="File\AuthKey_RMV7Y4KM9V.p8">
+      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
+    </None>
+  </ItemGroup>
 
   <ProjectExtensions><VisualStudio><UserProperties properties_4launchsettings_1json__JsonSchema="" /></VisualStudio></ProjectExtensions>
 

+ 2 - 0
OASystem/OASystem.Api/Program.cs

@@ -15,6 +15,7 @@ using Quartz.Impl;
 using Quartz.Spi;
 using QuzrtzJob.Factory;
 
+Console.Title = $"FMGJ OASystem Server";
 var builder = WebApplication.CreateBuilder(args);
 var basePath = AppContext.BaseDirectory;
 
@@ -424,6 +425,7 @@ app.MapHub<ChatHub>("/ChatHub", options =>
 
 #endregion
 
+
 app.MapControllerRoute(
     name: "default",
     pattern: "{controller=Home}/{action=Index}/{id?}");