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

94 lines
2.8 KiB
C#

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)
{
var keys = JsonSerializer.Deserialize<Dictionary<string, string>>(File.ReadAllText(keysFilePath));
// TEST
Console.WriteLine($"File Exists: {keys}");
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);
}
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}");
}
}
}