AcaMate_API/Program/V1/Services/PushService.cs
seonkyu.kim f4efd70507 [🐛] 10차 푸시 확인
Signed-off-by: seonkyu.kim <sean.kk@daum.net>
2024-11-30 16:11:08 +09:00

132 lines
4.3 KiB
C#

using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Security;
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<Dictionary<string, string>>(File.ReadAllText(keysFilePath));
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 SocketsHttpHandler
{
SslOptions = new SslClientAuthenticationOptions
{
EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls12 // TLS 1.2 활성화
}
};
try
{
// .p12 인증서 로드
var certificate = new X509Certificate2(p12Path, p12Password,
X509KeyStorageFlags.MachineKeySet |
X509KeyStorageFlags.PersistKeySet |
X509KeyStorageFlags.Exportable);
handler.SslOptions.ClientCertificates = new X509CertificateCollection { certificate };
Console.WriteLine("Certificate successfully loaded and attached to handler.");
}
catch (CryptographicException ex)
{
Console.WriteLine($"[Error] CryptographicException: {ex.Message}");
throw;
}
catch (Exception ex)
{
Console.WriteLine($"[Error] Unexpected error: {ex.Message}");
throw;
}
using var client = new HttpClient(handler)
{
BaseAddress = new Uri($"{uri}")
};
client.DefaultRequestHeaders.ExpectContinue = false;
client.DefaultRequestHeaders.Add("apns-topic", "me.myds.ipstein.acamate.AcaMate");
client.DefaultRequestHeaders.Add("apns-priority", "10");
var content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
try
{
Console.WriteLine($"Payload: {jsonPayload}");
Console.WriteLine($"Request URI: {client.BaseAddress}3/device/{deviceToken}");
var response = await client.PostAsync($"3/device/{deviceToken}", content);
Console.WriteLine("이건 넘음?");
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 (HttpRequestException httpEx)
{
Console.WriteLine($"HttpRequestException: {httpEx.Message}");
if (httpEx.InnerException != null)
{
Console.WriteLine($"Inner Exception: {httpEx.InnerException.Message}");
}
}
catch (Exception ex)
{
Console.WriteLine($"General Exception: {ex.Message}");
}
}
}