using Apimanager_backend.Dtos; using Apimanager_backend.Exceptions; using Apimanager_backend.Models; using Apimanager_backend.Services; using Apimanager_backend.Tools; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace Apimanager_backend.Controllers { [Route("api/[controller]/[action]")] [ApiController] public class PayController : ControllerBase { private ILogger _logger; private IOrderService _orderService; private IPaymentConfigService _paymentService; private IPayService _payService; public PayController(ILogger logger,IOrderService order,IPaymentConfigService paymentConfigService,IPayService payService) { _logger = logger; _orderService = order; _paymentService = paymentConfigService; _payService = payService; } [HttpPost] [Authorize(Roles = "User")] public async Task CreatePayment([FromBody]CreatePaymentDto dto) { var userId = User.Claims.First(x => x.Type == "userId").Value; //获取支付接口信息 var paymentConfig = await _paymentService.GetPaymentConfigInfoByTypeAsync(dto.PaymentType.ToString()); //创建订单 OrderDto order = new OrderDto(); order.Amount = dto.Amount; order.OrderType = OrderType.Purchase; order.UserId = int.Parse(userId); order.PaymentType = dto.PaymentType; Order orderRes = await _orderService.CreateOrderAsync(order); switch (paymentConfig.PayType) { case PayType.None: throw new BaseException(4001,"当前支付方式未配置"); case PayType.Epay: var epayRes = await _payService.CreateEpay(orderRes, paymentConfig,dto.ReturnUrl); return Ok(epayRes); default: throw new BaseException(4001, "不支持的支付方式"); } } [HttpGet] public async Task Notice( int pid, string trade_no,string out_trade_no , string type, string name, decimal money , string trade_status, string sign, string sign_type ) { Dictionary param = new Dictionary(); param["pid"] = pid.ToString(); param["trade_no"] = trade_no; param["out_trade_no"] = out_trade_no; param["type"] = type; param["name"] = name; param["money"] = money.ToString(); param["trade_status"] = trade_status; param["sign"] = sign; param["sign_type"] = sign_type; PaymentConfig paymentConfig = await _paymentService.GetPaymentConfigInfoByTypeAsync(type); bool verifyRes = EpayHelper.VerifySign(param,paymentConfig.SecretKey); if (!verifyRes) { throw new BaseException(4001, "签名校验失败"); } OrderDto orderDto = new OrderDto(); orderDto.ThirdPartyOrderId = trade_no; if (trade_status == "TRADE_SUCCESS") orderDto.Status = OrderStatus.Completed; else orderDto.Status = OrderStatus.Failed; await _orderService.UpdateOrderAsync(orderDto); return Ok("Success"); } } }