using System.Net.Http; using System.Net.Http.Headers; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Text.Json; namespace AcaMate.V1.Services; using AcaMate.V1.Models; public class PushServiceWithP12 { private readonly string p12Path; private readonly string p12Password; private readonly string apnsTopic; public PushServiceWithP12(string keysFilePath, string p12Path, string apnsTopic) { // 존재 안하면 예외 던져 버리는거 if (!File.Exists(keysFilePath)) { Console.WriteLine($"File not found: {keysFilePath}"); throw new FileNotFoundException("The specified file was not found", keysFilePath); } var keys = JsonSerializer.Deserialize>(File.ReadAllText(keysFilePath)); // TEST Console.WriteLine("Keys content:"); foreach (var key in keys) { Console.WriteLine($"{key.Key}: {key.Value}"); } p12Password = keys["Password"]; this.p12Path = p12Path; this.apnsTopic = apnsTopic; } public async Task SendPushAsync(string uri,string deviceToken, string title, string body, int badge) { var payload = new Payload() { aps = new Aps() { alert = new Alert() { title = title, body = body }, badge = badge } }; var jsonPayload = JsonSerializer.Serialize(payload); var handler = new HttpClientHandler(); try { var certificate = new X509Certificate2(p12Path, p12Password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable ); handler.ClientCertificates.Add(certificate); Console.WriteLine("Certificate successfully loaded."); } catch (CryptographicException ex) { Console.WriteLine($"CryptographicException: {ex.Message}"); } catch (Exception ex) { Console.WriteLine($"Unexpected error: {ex.Message}"); } using var client = new HttpClient(handler) { BaseAddress = new Uri($"{uri}") }; client.DefaultRequestHeaders.Add("apns-topic", apnsTopic); client.DefaultRequestHeaders.Add("apns-priority", "10"); var content = new StringContent(jsonPayload, Encoding.UTF8, "application/json"); try { var response = await client.PostAsync($"/3/device/{deviceToken}", content); if (response.IsSuccessStatusCode) { Console.WriteLine("Push notification sent successfully."); } else { var errorContent = await response.Content.ReadAsStringAsync(); Console.WriteLine($"Failed to send push notification. Status Code: {response.StatusCode}, Error: {errorContent}"); } } catch (Exception ex) { Console.WriteLine($"An error occurred while sending the push notification: {ex.Message}"); } } }