forked from AcaMate/AcaMate_API
76 lines
2.4 KiB
C#
76 lines
2.4 KiB
C#
using System.Net.Http;
|
|
using System.Net.Http.Headers;
|
|
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));
|
|
this.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 certificate = new X509Certificate2(p12Path, p12Password,
|
|
X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable
|
|
);
|
|
|
|
var handler = new HttpClientHandler();
|
|
handler.ClientCertificates.Add(certificate);
|
|
|
|
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}");
|
|
}
|
|
}
|
|
} |