[🐛] 10차 푸시 확인

Signed-off-by: seonkyu.kim <sean.kk@daum.net>
This commit is contained in:
김선규 2024-11-30 16:11:08 +09:00
parent 8f7f1c4894
commit f4efd70507
4 changed files with 76 additions and 46 deletions

View File

@ -11,6 +11,7 @@
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.10" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.8"/>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.10" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="8.0.2" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="7.1.0" />
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="7.1.0" />

View File

@ -15,6 +15,9 @@ using AcaMate.V1.Controllers;
var builder = WebApplication.CreateBuilder(args);
// DB 설정부 시작
builder.Configuration.AddJsonFile("private/dbSetting.json", optional: true, reloadOnChange: true);
// var connectionString = builder.Configuration.GetConnectionString("MariaDbConnection");
@ -67,7 +70,6 @@ builder.Services.AddControllers();
// builder.Services.AddScoped<UserService>(); //
// builder.Services.AddScoped<UserController>();
builder.Services.AddEndpointsApiExplorer();
// 스웨거 설정 추가 부분
@ -82,6 +84,7 @@ if (app.Environment.IsDevelopment())
// app.UseSwaggerUI();
app.UseCustomSwaggerUI();
app.UseDeveloperExceptionPage(); // 좀더 자세한 예외 정보 제공
}
else
{

View File

@ -1,4 +1,3 @@
using Microsoft.AspNetCore.Mvc;
using AcaMate.V1.Services;
@ -31,35 +30,36 @@ public class PushController : ControllerBase
[CustomOperation("푸시전송", "저장된 양식으로, 사용자에게 푸시를 전송한다.", "푸시")]
public async Task<IActionResult> SendPush(string deviceToken, string title, string body, int badge)
{
var keysFilePath = "/src/private/appleKeys.json";
var uri = "";
var p12FilePath = "";
var keysFilePath = "/src/private/appleKeys.json";
// var keysFilePath = "private/appleKeys.json";
var uri = "";
var p12FilePath = "";
if (_env.IsDevelopment())
{
// TEST
Console.WriteLine($"Current Directory: {Environment.CurrentDirectory}");
if (_env.IsDevelopment())
{
// TEST
Console.WriteLine($"Current Directory: {Environment.CurrentDirectory}");
Console.WriteLine($"Keys File Path: /src/private/appleKeys.json");
uri = "https://api.sandbox.push.apple.com";
p12FilePath = "/src/private/AM_Push_Sandbox.p12";
// p12FilePath = "private/AM_Push_Sandbox.p12";
}
else
{
uri = "https://api.push.apple.com";
p12FilePath = "/src/private/AM_Push.p12";
// p12FilePath = "private/AM_Push.p12";
}
var apnsTopic = "me.myds.ipstien.acamate.AcaMate";
uri = "https://api.sandbox.push.apple.com";
p12FilePath = "/src/private/AM_Push_Sandbox.p12";
// p12FilePath = "private/AM_Push_Sandbox.p12";
}
else
{
uri = "https://api.push.apple.com";
p12FilePath = "/src/private/AM_Push.p12";
// p12FilePath = "private/AM_Push.p12";
}
var apnsTopic = "me.myds.ipstein.acamate.AcaMate";
Console.WriteLine($"{uri} || {p12FilePath}");
var pushService = new PushServiceWithP12(keysFilePath, p12FilePath, apnsTopic);
Console.WriteLine($"{uri} || {p12FilePath}");
var pushService = new PushServiceWithP12(keysFilePath, p12FilePath, apnsTopic);
// 푸시 알림 전송
await pushService.SendPushAsync(uri, deviceToken, title, body, badge);
// 푸시 알림 전송
await pushService.SendPushAsync(uri, deviceToken, title, body, badge);
return Ok("Push notification sent.");
return Ok("Push notification sent.");
}
}
}

View File

@ -1,5 +1,7 @@
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;
@ -24,7 +26,7 @@ public class PushServiceWithP12
}
var keys = JsonSerializer.Deserialize<Dictionary<string, string>>(File.ReadAllText(keysFilePath));
// TEST
Console.WriteLine("Keys content:");
foreach (var key in keys)
{
@ -52,41 +54,55 @@ public class PushServiceWithP12
};
var jsonPayload = JsonSerializer.Serialize(payload);
var handler = new HttpClientHandler();
var handler = new SocketsHttpHandler
{
SslOptions = new SslClientAuthenticationOptions
{
EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls12 // TLS 1.2 활성화
}
};
try
{
var certificate = new X509Certificate2(p12Path, p12Password,
X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable
);
handler.ClientCertificates.Add(certificate);
Console.WriteLine("Certificate successfully loaded.");
// .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($"CryptographicException: {ex.Message}");
Console.WriteLine($"[Error] CryptographicException: {ex.Message}");
throw;
}
catch (Exception ex)
{
Console.WriteLine($"Unexpected error: {ex.Message}");
Console.WriteLine($"[Error] Unexpected error: {ex.Message}");
throw;
}
using var client = new HttpClient(handler)
{
BaseAddress = new Uri($"{uri}")
};
client.DefaultRequestHeaders.Add("apns-topic", apnsTopic);
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
{
var response = await client.PostAsync($"/3/device/{deviceToken}", content);
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)
{
@ -96,11 +112,21 @@ public class PushServiceWithP12
{
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($"An error occurred while sending the push notification: {ex.Message}");
Console.WriteLine($"General Exception: {ex.Message}");
}
}
}