DanalPayService.cs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. using System.Text;
  2. using System.Text.Json;
  3. using Application.Abstractions.Data;
  4. using Application.Abstractions.Payment;
  5. using Microsoft.EntityFrameworkCore;
  6. using Microsoft.Extensions.Logging;
  7. namespace Infrastructure.Payment;
  8. internal sealed class DanalPayService(
  9. HttpClient httpClient,
  10. IAppDbContext db,
  11. ILogger<DanalPayService> logger
  12. ) : IDanalPayService
  13. {
  14. private const string ConfirmUrl = "https://one-api.danalpay.com/payments/confirm";
  15. private const string CancelUrl = "https://one-api.danalpay.com/payments/cancel";
  16. public async Task<DanalClientConfig> GetClientConfigAsync(CancellationToken ct)
  17. {
  18. var (cpid, clientKey, _) = await GetKeysAsync(ct);
  19. return new DanalClientConfig(clientKey, cpid);
  20. }
  21. public async Task<DanalConfirmResult> ConfirmAsync(string method, string transactionID, string orderID, int amount, CancellationToken ct)
  22. {
  23. try
  24. {
  25. var (cpid, _, secretKey) = await GetKeysAsync(ct);
  26. var authHeader = BuildBasicAuth(secretKey);
  27. var request = new HttpRequestMessage(HttpMethod.Post, ConfirmUrl);
  28. request.Headers.Add("Authorization", authHeader);
  29. var body = new
  30. {
  31. method,
  32. transactionId = transactionID,
  33. orderId = orderID,
  34. amount = amount.ToString(),
  35. merchantId = cpid
  36. };
  37. request.Content = new StringContent(JsonSerializer.Serialize(body), Encoding.UTF8, "application/json");
  38. var response = await httpClient.SendAsync(request, ct);
  39. var json = await response.Content.ReadAsStringAsync(ct);
  40. logger.LogInformation("[DanalPay] Confirm response: {StatusCode} {Body}", response.StatusCode, json);
  41. var doc = JsonSerializer.Deserialize<JsonElement>(json);
  42. var code = doc.TryGetProperty("code", out var codeProp) ? codeProp.GetString() : null;
  43. var message = doc.TryGetProperty("message", out var msgProp) ? msgProp.GetString() : null;
  44. string? Get(string key) => doc.TryGetProperty(key, out var p) ? p.GetString() : null;
  45. int? GetInt(string key) => int.TryParse(Get(key), out var v) ? v : null;
  46. byte? GetByte(string key) => byte.TryParse(Get(key), out var v) ? v : null;
  47. return new DanalConfirmResult(
  48. code == "SUCCESS", code, message,
  49. Get("transactionId") ?? transactionID,
  50. Get("orderName"),
  51. GetInt("totalAmount"),
  52. GetInt("discountAmount"),
  53. Get("userName"),
  54. Get("transDate"), Get("transTime"),
  55. Get("cardCode"), Get("cardName"), Get("cardNo"),
  56. GetByte("installmentMonths"), Get("approveNo"),
  57. Get("approvalDateTime"), Get("authKey"),
  58. Get("accountNumber"), Get("bankCode"), Get("userId"), Get("userEmail"),
  59. Get("bankName"), Get("expireDate"), Get("expireTime"),
  60. Get("virtualAccountNumber"), Get("useCashReceipt")
  61. );
  62. }
  63. catch (Exception ex)
  64. {
  65. logger.LogError(ex, "[DanalPay] Confirm error for orderID={OrderID}", orderID);
  66. return new DanalConfirmResult(false, "ERROR", ex.Message, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null);
  67. }
  68. }
  69. public async Task<DanalCancelResult> CancelAsync(string method, string transactionID, int amount, string cancelType, CancellationToken ct)
  70. {
  71. try
  72. {
  73. var (cpid, _, secretKey) = await GetKeysAsync(ct);
  74. var authHeader = BuildBasicAuth(secretKey);
  75. var request = new HttpRequestMessage(HttpMethod.Post, CancelUrl);
  76. request.Headers.Add("Authorization", authHeader);
  77. var body = new
  78. {
  79. method,
  80. transactionId = transactionID,
  81. amount = amount.ToString(),
  82. merchantId = cpid,
  83. cancelType
  84. };
  85. request.Content = new StringContent(JsonSerializer.Serialize(body), Encoding.UTF8, "application/json");
  86. var response = await httpClient.SendAsync(request, ct);
  87. var json = await response.Content.ReadAsStringAsync(ct);
  88. logger.LogInformation("[DanalPay] Cancel response: {StatusCode} {Body}", response.StatusCode, json);
  89. var doc = JsonSerializer.Deserialize<JsonElement>(json);
  90. var code = doc.TryGetProperty("code", out var codeProp) ? codeProp.GetString() : null;
  91. var message = doc.TryGetProperty("message", out var msgProp) ? msgProp.GetString() : null;
  92. string? Get(string key) => doc.TryGetProperty(key, out var p) ? p.GetString() : null;
  93. int? GetInt(string key) => int.TryParse(Get(key), out var v) ? v : null;
  94. return new DanalCancelResult(
  95. code == "SUCCESS", code, message,
  96. Get("originalTransactionId"),
  97. GetInt("cancelledAmount"),
  98. Get("transDate"), Get("transTime"),
  99. Get("balance"), Get("remainedAmount"),
  100. Get("approvalDateTime")
  101. );
  102. }
  103. catch (Exception ex)
  104. {
  105. logger.LogError(ex, "[DanalPay] Cancel error for transactionID={TransactionID}", transactionID);
  106. return new DanalCancelResult(false, "ERROR", ex.Message, null, null, null, null, null, null, null);
  107. }
  108. }
  109. // ── Private ──────────────────────────────────────────────────────
  110. private async Task<(string Cpid, string ClientKey, string SecretKey)> GetKeysAsync(CancellationToken ct)
  111. {
  112. var config = await db.Config.FirstOrDefaultAsync(ct);
  113. if (config?.External is null)
  114. {
  115. throw new InvalidOperationException("다날 결제 설정이 없습니다. 관리자 페이지에서 설정해주세요.");
  116. }
  117. var ext = config.External;
  118. var isLive = string.Equals(ext.DanalPayMode, "live", StringComparison.OrdinalIgnoreCase);
  119. var cpid = isLive ? ext.DanalLiveCpid : ext.DanalTestCpid;
  120. var clientKey = isLive ? ext.DanalLiveClientKeyEnc : ext.DanalTestClientKeyEnc;
  121. var secretKey = isLive ? ext.DanalLiveSecretKeyEnc : ext.DanalTestSecretKeyEnc;
  122. if (string.IsNullOrEmpty(cpid) || string.IsNullOrEmpty(clientKey) || string.IsNullOrEmpty(secretKey))
  123. {
  124. throw new InvalidOperationException($"다날 {(isLive ? "라이브" : "테스트")} 설정이 불완전합니다.");
  125. }
  126. return (cpid, clientKey, secretKey);
  127. }
  128. private static string BuildBasicAuth(string secretKey)
  129. {
  130. // SecretKey + ":" → Base64
  131. var raw = $"{secretKey}:";
  132. var base64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(raw));
  133. return $"Basic {base64}";
  134. }
  135. }