58 lines
1.9 KiB
C#
58 lines
1.9 KiB
C#
using Microsoft.AspNetCore.Mvc;
|
|
using PetWash.Api.Services;
|
|
|
|
namespace PetWash.Api.Controllers;
|
|
|
|
[ApiController]
|
|
[Route("api/payments/wechat")]
|
|
public class PaymentsController : ControllerBase
|
|
{
|
|
private readonly OrderService _orderService;
|
|
private readonly WeChatPayService _weChatPayService;
|
|
private readonly ILogger<PaymentsController> _logger;
|
|
|
|
public PaymentsController(
|
|
OrderService orderService,
|
|
WeChatPayService weChatPayService,
|
|
ILogger<PaymentsController> logger)
|
|
{
|
|
_orderService = orderService;
|
|
_weChatPayService = weChatPayService;
|
|
_logger = logger;
|
|
}
|
|
|
|
[HttpPost("notify")]
|
|
public async Task<IActionResult> Notify(CancellationToken cancellationToken)
|
|
{
|
|
using var reader = new StreamReader(Request.Body);
|
|
var body = await reader.ReadToEndAsync(cancellationToken);
|
|
|
|
try
|
|
{
|
|
var notification = await _weChatPayService.ParsePaymentNotificationAsync(
|
|
body,
|
|
Request.Headers,
|
|
cancellationToken);
|
|
|
|
if (string.Equals(notification.TradeState, "SUCCESS", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
var order = await _orderService.ConfirmPaymentAsync(notification.OrderId);
|
|
if (order == null)
|
|
{
|
|
_logger.LogWarning(
|
|
"WeChat payment notification references a missing order. OrderId={OrderId}, OutTradeNo={OutTradeNo}",
|
|
notification.OrderId,
|
|
notification.OutTradeNo);
|
|
}
|
|
}
|
|
|
|
return Ok(new { code = "SUCCESS", message = "成功" });
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, "Failed to process WeChat payment notification.");
|
|
return BadRequest(new { code = "FAIL", message = ex.Message });
|
|
}
|
|
}
|
|
}
|