[🐛] 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.Authentication.JwtBearer" Version="8.0.10" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.8"/> <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.8"/>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.10" /> <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="Pomelo.EntityFrameworkCore.MySql" Version="8.0.2" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="7.1.0" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="7.1.0" />
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" 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); var builder = WebApplication.CreateBuilder(args);
// DB 설정부 시작 // DB 설정부 시작
builder.Configuration.AddJsonFile("private/dbSetting.json", optional: true, reloadOnChange: true); builder.Configuration.AddJsonFile("private/dbSetting.json", optional: true, reloadOnChange: true);
// var connectionString = builder.Configuration.GetConnectionString("MariaDbConnection"); // var connectionString = builder.Configuration.GetConnectionString("MariaDbConnection");
@ -67,7 +70,6 @@ builder.Services.AddControllers();
// builder.Services.AddScoped<UserService>(); // // builder.Services.AddScoped<UserService>(); //
// builder.Services.AddScoped<UserController>(); // builder.Services.AddScoped<UserController>();
builder.Services.AddEndpointsApiExplorer(); builder.Services.AddEndpointsApiExplorer();
// 스웨거 설정 추가 부분 // 스웨거 설정 추가 부분
@ -82,6 +84,7 @@ if (app.Environment.IsDevelopment())
// app.UseSwaggerUI(); // app.UseSwaggerUI();
app.UseCustomSwaggerUI(); app.UseCustomSwaggerUI();
app.UseDeveloperExceptionPage(); // 좀더 자세한 예외 정보 제공 app.UseDeveloperExceptionPage(); // 좀더 자세한 예외 정보 제공
} }
else else
{ {

View File

@ -1,4 +1,3 @@
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using AcaMate.V1.Services; using AcaMate.V1.Services;
@ -31,35 +30,36 @@ public class PushController : ControllerBase
[CustomOperation("푸시전송", "저장된 양식으로, 사용자에게 푸시를 전송한다.", "푸시")] [CustomOperation("푸시전송", "저장된 양식으로, 사용자에게 푸시를 전송한다.", "푸시")]
public async Task<IActionResult> SendPush(string deviceToken, string title, string body, int badge) public async Task<IActionResult> SendPush(string deviceToken, string title, string body, int badge)
{ {
var keysFilePath = "/src/private/appleKeys.json"; var keysFilePath = "/src/private/appleKeys.json";
var uri = ""; // var keysFilePath = "private/appleKeys.json";
var p12FilePath = ""; 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"; uri = "https://api.sandbox.push.apple.com";
p12FilePath = "/src/private/AM_Push_Sandbox.p12"; p12FilePath = "/src/private/AM_Push_Sandbox.p12";
// p12FilePath = "private/AM_Push_Sandbox.p12"; // p12FilePath = "private/AM_Push_Sandbox.p12";
} }
else else
{ {
uri = "https://api.push.apple.com"; uri = "https://api.push.apple.com";
p12FilePath = "/src/private/AM_Push.p12"; p12FilePath = "/src/private/AM_Push.p12";
// p12FilePath = "private/AM_Push.p12"; // p12FilePath = "private/AM_Push.p12";
} }
var apnsTopic = "me.myds.ipstien.acamate.AcaMate"; var apnsTopic = "me.myds.ipstein.acamate.AcaMate";
Console.WriteLine($"{uri} || {p12FilePath}"); Console.WriteLine($"{uri} || {p12FilePath}");
var pushService = new PushServiceWithP12(keysFilePath, p12FilePath, apnsTopic); 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;
using System.Net.Http.Headers; using System.Net.Http.Headers;
using System.Net.Security;
using System.Security.Cryptography; using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography.X509Certificates;
using System.Text; using System.Text;
@ -24,7 +26,7 @@ public class PushServiceWithP12
} }
var keys = JsonSerializer.Deserialize<Dictionary<string, string>>(File.ReadAllText(keysFilePath)); var keys = JsonSerializer.Deserialize<Dictionary<string, string>>(File.ReadAllText(keysFilePath));
// TEST
Console.WriteLine("Keys content:"); Console.WriteLine("Keys content:");
foreach (var key in keys) foreach (var key in keys)
{ {
@ -52,41 +54,55 @@ public class PushServiceWithP12
}; };
var jsonPayload = JsonSerializer.Serialize(payload); var jsonPayload = JsonSerializer.Serialize(payload);
var handler = new SocketsHttpHandler
var handler = new HttpClientHandler(); {
SslOptions = new SslClientAuthenticationOptions
{
EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls12 // TLS 1.2 활성화
}
};
try try
{ {
var certificate = new X509Certificate2(p12Path, p12Password, // .p12 인증서 로드
X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable var certificate = new X509Certificate2(p12Path, p12Password,
); X509KeyStorageFlags.MachineKeySet |
handler.ClientCertificates.Add(certificate); X509KeyStorageFlags.PersistKeySet |
Console.WriteLine("Certificate successfully loaded."); X509KeyStorageFlags.Exportable);
handler.SslOptions.ClientCertificates = new X509CertificateCollection { certificate };
Console.WriteLine("Certificate successfully loaded and attached to handler.");
} }
catch (CryptographicException ex) catch (CryptographicException ex)
{ {
Console.WriteLine($"CryptographicException: {ex.Message}"); Console.WriteLine($"[Error] CryptographicException: {ex.Message}");
throw;
} }
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine($"Unexpected error: {ex.Message}"); Console.WriteLine($"[Error] Unexpected error: {ex.Message}");
throw;
} }
using var client = new HttpClient(handler) using var client = new HttpClient(handler)
{ {
BaseAddress = new Uri($"{uri}") 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"); client.DefaultRequestHeaders.Add("apns-priority", "10");
var content = new StringContent(jsonPayload, Encoding.UTF8, "application/json"); var content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
try 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) if (response.IsSuccessStatusCode)
{ {
@ -96,11 +112,21 @@ public class PushServiceWithP12
{ {
var errorContent = await response.Content.ReadAsStringAsync(); var errorContent = await response.Content.ReadAsStringAsync();
Console.WriteLine($"Failed to send push notification. Status Code: {response.StatusCode}, Error: {errorContent}"); 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) catch (Exception ex)
{ {
Console.WriteLine($"An error occurred while sending the push notification: {ex.Message}"); Console.WriteLine($"General Exception: {ex.Message}");
} }
} }
} }