feat: 订单余额优先+微信补差混合支付
新增 order_pay 支付单行与创建/回调入账,复用微信 status/close,未成功前不扣余额。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
b0fd3a30e1
commit
d0618509e5
27
db.sql
27
db.sql
@ -78,6 +78,7 @@ DROP TABLE IF EXISTS `t_country`;
|
||||
DROP TABLE IF EXISTS `t_invoice_apply_line`;
|
||||
DROP TABLE IF EXISTS `t_invoice_apply`;
|
||||
DROP TABLE IF EXISTS `t_customer_invoice_profile`;
|
||||
DROP TABLE IF EXISTS `t_payment_order_line`;
|
||||
DROP TABLE IF EXISTS `t_payment_order`;
|
||||
DROP TABLE IF EXISTS `t_recharge_record`;
|
||||
DROP TABLE IF EXISTS `t_customer`;
|
||||
@ -1153,10 +1154,11 @@ CREATE TABLE `t_recharge_record` (
|
||||
CREATE TABLE `t_payment_order` (
|
||||
`Id` INT NOT NULL AUTO_INCREMENT COMMENT '主键',
|
||||
`OutTradeNo` VARCHAR(64) NOT NULL COMMENT '商户订单号 out_trade_no',
|
||||
`BizType` VARCHAR(32) NOT NULL COMMENT '业务类型:recharge',
|
||||
`BizId` INT NOT NULL COMMENT '业务主键(充值记录 Id)',
|
||||
`BizType` VARCHAR(32) NOT NULL COMMENT '业务类型:recharge / order_pay',
|
||||
`BizId` INT NOT NULL COMMENT '业务主键(充值记录 Id / 首单 Id)',
|
||||
`CustomerId` INT NOT NULL COMMENT '客户 Id',
|
||||
`Amount` DECIMAL(18,2) NOT NULL COMMENT '支付金额(元)',
|
||||
`Amount` DECIMAL(18,2) NOT NULL COMMENT '微信支付金额(元);订单混合支付为补差',
|
||||
`BalanceAmount` DECIMAL(18,2) NOT NULL DEFAULT 0 COMMENT '本次拟扣账户余额(元)',
|
||||
`Currency` VARCHAR(8) NOT NULL DEFAULT 'CNY' COMMENT '币种',
|
||||
`Channel` VARCHAR(32) NOT NULL COMMENT 'WechatNative / WechatJsapi',
|
||||
`Status` TINYINT NOT NULL DEFAULT 1 COMMENT '1Created 2Paying 3Success 4Closed 5Failed',
|
||||
@ -1178,6 +1180,25 @@ CREATE TABLE `t_payment_order` (
|
||||
KEY `ix_pay_customer_status` (`CustomerId`, `Status`, `CreateTime`)
|
||||
) COMMENT='在线支付单';
|
||||
|
||||
CREATE TABLE `t_payment_order_line` (
|
||||
`Id` INT NOT NULL AUTO_INCREMENT COMMENT '主键',
|
||||
`PaymentOrderId` INT NOT NULL COMMENT '支付单 Id',
|
||||
`OrderId` INT NOT NULL COMMENT '运单 Id',
|
||||
`PayableAmount` DECIMAL(18,2) NOT NULL COMMENT '本单应付(元)',
|
||||
`BalanceAmount` DECIMAL(18,2) NOT NULL DEFAULT 0 COMMENT '本单用余额(元)',
|
||||
`WechatAmount` DECIMAL(18,2) NOT NULL DEFAULT 0 COMMENT '本单微信补差(元)',
|
||||
`CouponInstanceId` INT NULL COMMENT '优惠券实例 Id',
|
||||
`IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT '软删除:0-否,1-是',
|
||||
`ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT '并发戳',
|
||||
`CreateUserId` INT NOT NULL DEFAULT 0 COMMENT '创建人',
|
||||
`CreateTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`UpdateUserId` INT NULL COMMENT '更新人',
|
||||
`UpdateTime` DATETIME NULL COMMENT '更新时间',
|
||||
PRIMARY KEY (`Id`),
|
||||
KEY `ix_pay_line_payment` (`PaymentOrderId`),
|
||||
KEY `ix_pay_line_order` (`OrderId`)
|
||||
) COMMENT='在线支付单明细(订单混合支付)';
|
||||
|
||||
CREATE TABLE `t_customer_invoice_profile` (
|
||||
`Id` INT NOT NULL AUTO_INCREMENT COMMENT '主键',
|
||||
`CustomerId` INT NOT NULL COMMENT '客户 ID',
|
||||
|
||||
@ -34,7 +34,21 @@
|
||||
- [ ] 静态收款码 / 银行转账仍走截图 + 审批入账
|
||||
- [ ] 在线微信 **不走** ApprovalGate
|
||||
|
||||
## 订单混合支付(余额优先 + 微信补差)
|
||||
|
||||
- [ ] 已执行 `sql/migrate_payment_order_order_pay_20261201.sql`(`t_payment_order.BalanceAmount`、`t_payment_order_line`;`BizType=order_pay`)
|
||||
- [ ] 单客户、余额充足:PC/H5 仍走余额,create 返回 `paidImmediately=true`(不调微信)
|
||||
- [ ] 单客户、余额不足:创建时写入 PaymentOrder + lines,**未付成功前不扣余额**
|
||||
- [ ] PC Native:确认支付 → 二维码 → 轮询 Success → 订单已付、余额按 `BalanceAmount` 扣减、券/积分与 `/order/pay` 一致
|
||||
- [ ] H5 JSAPI:微信内调起 → 成功以 status 确认;取消/失败调 close;未确认不伪造成功(确认中文案)
|
||||
- [ ] 同客户多票:一笔微信补差覆盖多条 line;Finalize 时已付 line 跳过
|
||||
- [ ] 多客户批量:仅余额;前端禁用微信补差并提示按客户拆分
|
||||
- [ ] 关单 / 微信 CLOSED:只关支付单,订单仍待付、余额未动
|
||||
- [ ] 金额校验:微信实付仅比对补差 `Amount`(非应付总额)
|
||||
- [ ] 复用 `/recharge/pay/wechat/status|close|notify`;创建走 `POST /order/pay/wechat/create`
|
||||
|
||||
## 监控建议
|
||||
|
||||
- 日志关键字:`微信支付回调验签失败`、`入账失败`、`查单补偿失败`
|
||||
- 关注:Creating/Paying 堆积、Notify 5xx 比例、关单后仍 Success 的对账差异
|
||||
- 关注:Creating/Paying 堆积、Notify 5xx 比例、关单后仍 Success 的对账差异;订单混合支付另关注 `order_pay` Finalize 跳过已付 line
|
||||
|
||||
|
||||
46
sql/migrate_payment_order_order_pay_20261201.sql
Normal file
46
sql/migrate_payment_order_order_pay_20261201.sql
Normal file
@ -0,0 +1,46 @@
|
||||
-- 订单混合支付:支付单 BalanceAmount + 明细表 t_payment_order_line
|
||||
-- 可重复执行
|
||||
|
||||
SET @db := DATABASE();
|
||||
|
||||
-- t_payment_order.BalanceAmount
|
||||
SET @col := (
|
||||
SELECT COUNT(1) FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 't_payment_order' AND COLUMN_NAME = 'BalanceAmount'
|
||||
);
|
||||
SET @sql := IF(
|
||||
@col = 0,
|
||||
'ALTER TABLE `t_payment_order`
|
||||
ADD COLUMN `BalanceAmount` DECIMAL(18,2) NOT NULL DEFAULT 0 COMMENT ''本次拟扣账户余额(元)'' AFTER `Amount`',
|
||||
'SELECT 1'
|
||||
);
|
||||
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
|
||||
|
||||
-- t_payment_order_line
|
||||
SET @tbl := (
|
||||
SELECT COUNT(1) FROM information_schema.TABLES
|
||||
WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 't_payment_order_line'
|
||||
);
|
||||
SET @sql := IF(
|
||||
@tbl = 0,
|
||||
'CREATE TABLE `t_payment_order_line` (
|
||||
`Id` INT NOT NULL AUTO_INCREMENT COMMENT ''主键'',
|
||||
`PaymentOrderId` INT NOT NULL COMMENT ''支付单 Id'',
|
||||
`OrderId` INT NOT NULL COMMENT ''运单 Id'',
|
||||
`PayableAmount` DECIMAL(18,2) NOT NULL COMMENT ''本单应付(元)'',
|
||||
`BalanceAmount` DECIMAL(18,2) NOT NULL DEFAULT 0 COMMENT ''本单用余额(元)'',
|
||||
`WechatAmount` DECIMAL(18,2) NOT NULL DEFAULT 0 COMMENT ''本单微信补差(元)'',
|
||||
`CouponInstanceId` INT NULL COMMENT ''优惠券实例 Id'',
|
||||
`IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT ''软删除:0-否,1-是'',
|
||||
`ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT ''并发戳'',
|
||||
`CreateUserId` INT NOT NULL DEFAULT 0 COMMENT ''创建人'',
|
||||
`CreateTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''创建时间'',
|
||||
`UpdateUserId` INT NULL COMMENT ''更新人'',
|
||||
`UpdateTime` DATETIME NULL COMMENT ''更新时间'',
|
||||
PRIMARY KEY (`Id`),
|
||||
KEY `ix_pay_line_payment` (`PaymentOrderId`),
|
||||
KEY `ix_pay_line_order` (`OrderId`)
|
||||
) COMMENT=''在线支付单明细(订单混合支付)''',
|
||||
'SELECT 1'
|
||||
);
|
||||
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
|
||||
66
src/Oms.Application/Dtos/Orders/OrderWeChatPayDtos.cs
Normal file
66
src/Oms.Application/Dtos/Orders/OrderWeChatPayDtos.cs
Normal file
@ -0,0 +1,66 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using Oms.Application.Dtos.Payment;
|
||||
|
||||
namespace Oms.Application.Dtos.Orders;
|
||||
|
||||
/// <summary>创建订单微信混合支付(余额优先 + 微信补差)。</summary>
|
||||
public class CreateOrderWeChatPayInput
|
||||
{
|
||||
/// <summary>运单 Id 列表(须同一客户)。</summary>
|
||||
[Required]
|
||||
[MinLength(1)]
|
||||
public List<int> OrderIds { get; set; } = [];
|
||||
|
||||
/// <summary>每单选用的优惠券;key 为订单 Id,value 同支付预览(null 自动 / 0 不用 / >0 指定)。</summary>
|
||||
public Dictionary<int, int?>? CouponByOrderId { get; set; }
|
||||
|
||||
/// <summary>场景:native | jsapi。</summary>
|
||||
[Required]
|
||||
[StringLength(16)]
|
||||
public string Scene { get; set; } = "native";
|
||||
|
||||
/// <summary>JSAPI OAuth code(可选)。</summary>
|
||||
[StringLength(128)]
|
||||
public string? OauthCode { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>订单混合支付创建结果。</summary>
|
||||
public class CreateOrderWeChatPayOutput
|
||||
{
|
||||
/// <summary>应付合计。</summary>
|
||||
public decimal PayableTotal { get; set; }
|
||||
|
||||
/// <summary>本次用余额。</summary>
|
||||
public decimal BalanceAmount { get; set; }
|
||||
|
||||
/// <summary>微信补差。</summary>
|
||||
public decimal WechatAmount { get; set; }
|
||||
|
||||
/// <summary>账户当前余额(创建时快照)。</summary>
|
||||
public decimal CustomerBalance { get; set; }
|
||||
|
||||
/// <summary>无需微信、已全部用余额付清。</summary>
|
||||
public bool PaidImmediately { get; set; }
|
||||
|
||||
/// <summary>商户订单号(需微信支付时)。</summary>
|
||||
public string? OutTradeNo { get; set; }
|
||||
|
||||
public string? Channel { get; set; }
|
||||
public string? Status { get; set; }
|
||||
public string? CodeUrl { get; set; }
|
||||
public DateTime? ExpireTime { get; set; }
|
||||
public WeChatJsapiPayParams? Jsapi { get; set; }
|
||||
|
||||
public List<OrderWeChatPayLineOutput> Lines { get; set; } = [];
|
||||
}
|
||||
|
||||
/// <summary>混合支付分票明细。</summary>
|
||||
public class OrderWeChatPayLineOutput
|
||||
{
|
||||
public int OrderId { get; set; }
|
||||
public string? ServiceNo { get; set; }
|
||||
public decimal PayableAmount { get; set; }
|
||||
public decimal BalanceAmount { get; set; }
|
||||
public decimal WechatAmount { get; set; }
|
||||
public int? CouponInstanceId { get; set; }
|
||||
}
|
||||
@ -0,0 +1,94 @@
|
||||
using Fake.Application;
|
||||
using Fake.Domain.Exceptions;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Oms.Application.Dtos.Marketing;
|
||||
using Oms.Application.Dtos.Orders;
|
||||
using Oms.Application.Shared;
|
||||
using Oms.Domain.OrdersAggregate.Consts;
|
||||
using Oms.Domain.OrdersAggregate.Entities;
|
||||
using Oms.Domain.PaymentAggregate.Entities;
|
||||
using Oms.Domain.PaymentAggregate.Enums;
|
||||
using Oms.Domain.PaymentAggregate.Repositories;
|
||||
|
||||
namespace Oms.Application.Services.Orders;
|
||||
|
||||
public partial class OrderService
|
||||
{
|
||||
private IPaymentOrderLineRepository PaymentOrderLineRepository =>
|
||||
LazyServiceProvider.GetRequiredService<IPaymentOrderLineRepository>();
|
||||
|
||||
/// <summary>
|
||||
/// 微信订单混合支付成功后落账:扣余额(若有)并 Finalize 各运单。由支付回调/查单调用。
|
||||
/// </summary>
|
||||
public async Task SettleOrderOnlinePaymentAsync(int paymentOrderId, string? transactionId)
|
||||
{
|
||||
var paymentRepo = LazyServiceProvider.GetRequiredService<IPaymentOrderRepository>();
|
||||
var payment = await paymentRepo.FirstOrDefaultAsync(x => x.Id == paymentOrderId)
|
||||
?? throw new BusinessException("支付单不存在");
|
||||
if (payment.BizType != PaymentBizTypeCodes.OrderPay)
|
||||
{
|
||||
throw new BusinessException("非订单支付单");
|
||||
}
|
||||
|
||||
var lines = await PaymentOrderLineRepository.GetListByPaymentOrderIdAsync(payment.Id);
|
||||
if (lines.Count == 0)
|
||||
{
|
||||
throw new BusinessException("支付单无订单明细");
|
||||
}
|
||||
|
||||
var customer = await CustomerRepository.FirstOrDefaultAsync(x => x.Id == payment.CustomerId)
|
||||
?? throw new BusinessException("客户不存在");
|
||||
|
||||
if (payment.BalanceAmount > 0)
|
||||
{
|
||||
// 刷新余额实体,避免并发脏读后多扣
|
||||
customer = await CustomerRepository.FirstOrDefaultAsync(x => x.Id == payment.CustomerId)
|
||||
?? throw new BusinessException("客户不存在");
|
||||
var balanceMutator = LazyServiceProvider.GetRequiredService<CustomerBalanceMutator>();
|
||||
await balanceMutator.DebitOrderPayAsync(
|
||||
customer,
|
||||
payment.BalanceAmount,
|
||||
lines[0].OrderId,
|
||||
payment.OutTradeNo,
|
||||
$"订单混合支付余额部分 out_trade_no={payment.OutTradeNo}");
|
||||
}
|
||||
|
||||
foreach (var line in lines.OrderBy(x => x.Id))
|
||||
{
|
||||
var order = await GetOrderOrThrowAsync(line.OrderId);
|
||||
if (order.IsPaid > 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (order.OrderStatus is not OrderStatusCodes.PendingPayment)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (order.CustomerId != payment.CustomerId)
|
||||
{
|
||||
throw new BusinessException($"订单 {order.Id} 客户与支付单不一致");
|
||||
}
|
||||
|
||||
var fees = await OrderRepository.GetFeesByOrderIdsAsync([order.Id]);
|
||||
var breakdown = await BuildPayBreakdownAsync(order, fees, line.CouponInstanceId);
|
||||
if (Math.Abs(breakdown.PayableAmount - line.PayableAmount) > 0.01M)
|
||||
{
|
||||
throw new BusinessException(
|
||||
$"订单 {order.Id} 应付已变更为 {breakdown.PayableAmount},与支付锁定 {line.PayableAmount} 不一致,请人工处理 {payment.OutTradeNo}");
|
||||
}
|
||||
|
||||
var logSuffix = line.WechatAmount > 0
|
||||
? $"微信补差 {line.WechatAmount:0.####} transaction_id={transactionId}"
|
||||
: $"余额支付 transaction_id={transactionId}";
|
||||
await FinalizeOrderPaidCoreAsync(
|
||||
order,
|
||||
customer,
|
||||
fees as IList<OrderFee> ?? fees.ToList(),
|
||||
breakdown,
|
||||
line.PayableAmount,
|
||||
logSuffix);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -8,8 +8,10 @@ using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using MiniExcelLibs;
|
||||
using Oms.Application.Dtos.Marketing;
|
||||
using Oms.Application.Dtos.Orders;
|
||||
using Oms.Application.Dtos.Shared;
|
||||
using Oms.Domain.CustomersAggregate.Entities;
|
||||
using Oms.Application.DataPerm;
|
||||
using Oms.Application.Labeling;
|
||||
using Oms.Application.Shared;
|
||||
@ -180,7 +182,6 @@ public partial class OrderService : ApplicationService
|
||||
throw new BusinessException("订单未关联客户,无法支付");
|
||||
}
|
||||
|
||||
var beforeSnap = await CaptureOrderAuditSnapshotAsync(order);
|
||||
var fees = await OrderRepository.GetFeesByOrderIdsAsync([order.Id]);
|
||||
var breakdown = await BuildPayBreakdownAsync(order, fees, input.CouponInstanceId);
|
||||
if (breakdown.ReceivableSubtotal <= 0)
|
||||
@ -189,11 +190,8 @@ public partial class OrderService : ApplicationService
|
||||
}
|
||||
|
||||
var payAmount = breakdown.PayableAmount;
|
||||
var customer = await CustomerRepository.FirstOrDefaultAsync(x => x.Id == order.CustomerId.Value);
|
||||
if (customer == null)
|
||||
{
|
||||
throw new BusinessException("客户不存在");
|
||||
}
|
||||
var customer = await CustomerRepository.FirstOrDefaultAsync(x => x.Id == order.CustomerId.Value)
|
||||
?? throw new BusinessException("客户不存在");
|
||||
|
||||
if (payAmount > 0)
|
||||
{
|
||||
@ -206,6 +204,26 @@ public partial class OrderService : ApplicationService
|
||||
$"订单支付 {order.ServiceNo}");
|
||||
}
|
||||
|
||||
await FinalizeOrderPaidCoreAsync(order, customer, fees, breakdown, payAmount, null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 支付成功后的订单侧落账(券/折扣费/积分/已付状态/操作日志)。余额扣款由调用方完成。
|
||||
/// </summary>
|
||||
private async Task FinalizeOrderPaidCoreAsync(
|
||||
Order order,
|
||||
Customer customer,
|
||||
IList<OrderFee> fees,
|
||||
MarketingPriceBreakdown breakdown,
|
||||
decimal paidAmountForLog,
|
||||
string? logSuffix)
|
||||
{
|
||||
if (order.IsPaid > 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var beforeSnap = await CaptureOrderAuditSnapshotAsync(order);
|
||||
var couponManager = LazyServiceProvider.GetRequiredService<MarketingCouponManager>();
|
||||
if (order.CouponInstanceId is > 0 && order.CouponInstanceId != breakdown.CouponInstanceId)
|
||||
{
|
||||
@ -228,8 +246,8 @@ public partial class OrderService : ApplicationService
|
||||
var pointsManager = LazyServiceProvider.GetRequiredService<MarketingPointsManager>();
|
||||
var paidBaseFreight = MarketingFeeHelper.ResolvePaidBaseFreight(
|
||||
MarketingFeeHelper.SumReceivableBaseFreight(fees),
|
||||
order.LevelDiscountAmount,
|
||||
order.CouponDiscountAmount);
|
||||
breakdown.LevelDiscountAmount,
|
||||
breakdown.CouponDiscountAmount);
|
||||
await pointsManager.EarnOnOrderPaidAsync(mainCustomer.Id, order.Id, paidBaseFreight, order.ServiceNo);
|
||||
|
||||
order.PayTime = DateTime.Now;
|
||||
@ -239,16 +257,17 @@ public partial class OrderService : ApplicationService
|
||||
|
||||
order = await GetOrderOrThrowAsync(order.Id);
|
||||
var afterSnap = await CaptureOrderAuditSnapshotAsync(order);
|
||||
var amountText = payAmount.ToString("0.####", CultureInfo.InvariantCulture);
|
||||
var amountText = paidAmountForLog.ToString("0.####", CultureInfo.InvariantCulture);
|
||||
var couponText = breakdown.CouponDiscountAmount > 0
|
||||
? $",优惠券抵扣 {breakdown.CouponDiscountAmount.ToString("0.####", CultureInfo.InvariantCulture)}"
|
||||
: string.Empty;
|
||||
var suffix = string.IsNullOrWhiteSpace(logSuffix) ? string.Empty : $",{logSuffix.Trim()}";
|
||||
await OperationLogWriter.TryWriteAsync(
|
||||
order,
|
||||
OrderOperationActionCodes.Pay,
|
||||
beforeSnap,
|
||||
afterSnap,
|
||||
$"支付金额 {amountText}{couponText}");
|
||||
$"支付金额 {amountText}{couponText}{suffix}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@ -7,10 +7,14 @@ using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Oms.Application.Dtos.Orders;
|
||||
using Oms.Application.Dtos.Payment;
|
||||
using Oms.Application.Messaging;
|
||||
using Oms.Application.Services.Orders;
|
||||
using Oms.Application.Shared;
|
||||
using Oms.Domain.CustomersAggregate.Repositories;
|
||||
using Oms.Domain.OrdersAggregate.Consts;
|
||||
using Oms.Domain.OrdersAggregate.Repositories;
|
||||
using Oms.Domain.PaymentAggregate.Entities;
|
||||
using Oms.Domain.PaymentAggregate.Enums;
|
||||
using Oms.Domain.PaymentAggregate.Repositories;
|
||||
@ -36,10 +40,14 @@ public class WeChatPayService : ApplicationService
|
||||
|
||||
private IPaymentOrderRepository PaymentOrderRepository =>
|
||||
LazyServiceProvider.GetRequiredService<IPaymentOrderRepository>();
|
||||
private IPaymentOrderLineRepository PaymentOrderLineRepository =>
|
||||
LazyServiceProvider.GetRequiredService<IPaymentOrderLineRepository>();
|
||||
private IRechargeRecordRepository RechargeRecordRepository =>
|
||||
LazyServiceProvider.GetRequiredService<IRechargeRecordRepository>();
|
||||
private ICustomerRepository CustomerRepository =>
|
||||
LazyServiceProvider.GetRequiredService<ICustomerRepository>();
|
||||
private IOrderRepository OrderRepository =>
|
||||
LazyServiceProvider.GetRequiredService<IOrderRepository>();
|
||||
private ISystemOtherConfigRepository SystemOtherConfigRepository =>
|
||||
LazyServiceProvider.GetRequiredService<ISystemOtherConfigRepository>();
|
||||
private WeChatPayClientFactory ClientFactory =>
|
||||
@ -353,7 +361,10 @@ public class WeChatPayService : ApplicationService
|
||||
payment.Status = PaymentOrderStatus.Closed;
|
||||
payment.Remark = "用户关闭/超时关闭";
|
||||
await PaymentOrderRepository.UpdateAsync(payment);
|
||||
await RejectOnlineRechargeIfPendingAsync(payment.BizId, "支付关闭,未入账");
|
||||
if (payment.BizType == PaymentBizTypeCodes.Recharge)
|
||||
{
|
||||
await RejectOnlineRechargeIfPendingAsync(payment.BizId, "支付关闭,未入账");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -469,10 +480,13 @@ public class WeChatPayService : ApplicationService
|
||||
payment.Status = PaymentOrderStatus.Closed;
|
||||
payment.Remark = response.TradeStateDescription ?? response.TradeState;
|
||||
await PaymentOrderRepository.UpdateAsync(payment, cancellationToken: cancellationToken);
|
||||
await RejectOnlineRechargeIfPendingAsync(
|
||||
payment.BizId,
|
||||
$"微信{response.TradeState},未入账",
|
||||
cancellationToken);
|
||||
if (payment.BizType == PaymentBizTypeCodes.Recharge)
|
||||
{
|
||||
await RejectOnlineRechargeIfPendingAsync(
|
||||
payment.BizId,
|
||||
$"微信{response.TradeState},未入账",
|
||||
cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -526,9 +540,15 @@ public class WeChatPayService : ApplicationService
|
||||
return;
|
||||
}
|
||||
|
||||
if (payment.BizType == PaymentBizTypeCodes.OrderPay)
|
||||
{
|
||||
await CompleteOrderPaySuccessAsync(payment, transactionId, successTime);
|
||||
await uow.CompleteAsync();
|
||||
return;
|
||||
}
|
||||
|
||||
var recharge = await RechargeRecordRepository.FirstOrDefaultAsync(x => x.Id == payment.BizId)
|
||||
?? throw new BusinessException("充值记录不存在");
|
||||
|
||||
if (recharge.RechargeStatus == RechargeStatus.Approved)
|
||||
{
|
||||
var paidAt = successTime?.LocalDateTime ?? DateTime.Now;
|
||||
@ -608,6 +628,312 @@ public class WeChatPayService : ApplicationService
|
||||
await uow.CompleteAsync();
|
||||
}
|
||||
|
||||
private async Task CompleteOrderPaySuccessAsync(
|
||||
PaymentOrder payment,
|
||||
string? transactionId,
|
||||
DateTimeOffset? successTime)
|
||||
{
|
||||
var paidTime = successTime?.LocalDateTime ?? DateTime.Now;
|
||||
var claimed = await PaymentOrderRepository.TryClaimSuccessAsync(
|
||||
payment.OutTradeNo,
|
||||
transactionId,
|
||||
paidTime,
|
||||
"订单混合支付成功");
|
||||
if (!claimed)
|
||||
{
|
||||
var latest = await PaymentOrderRepository.GetByOutTradeNoAsync(payment.OutTradeNo);
|
||||
if (latest?.Status == PaymentOrderStatus.Success)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
throw new BusinessException($"支付单状态不可入账:{latest?.Status}");
|
||||
}
|
||||
|
||||
var orderService = LazyServiceProvider.GetRequiredService<OrderService>();
|
||||
await orderService.SettleOrderOnlinePaymentAsync(payment.Id, transactionId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建订单混合支付:余额优先,差额微信 Native/JSAPI;差额为 0 则立即余额付清。
|
||||
/// </summary>
|
||||
[HttpPost("/order/pay/wechat/create")]
|
||||
public async Task<CreateOrderWeChatPayOutput> CreateOrderPayAsync(CreateOrderWeChatPayInput input)
|
||||
{
|
||||
var scene = (input.Scene ?? "native").Trim().ToLowerInvariant();
|
||||
if (scene is not ("native" or "jsapi"))
|
||||
{
|
||||
throw new BusinessException("场景仅支持 native 或 jsapi");
|
||||
}
|
||||
|
||||
var orderIds = (input.OrderIds ?? [])
|
||||
.Where(x => x > 0)
|
||||
.Distinct()
|
||||
.ToList();
|
||||
if (orderIds.Count == 0)
|
||||
{
|
||||
throw new BusinessException("请选择待支付订单");
|
||||
}
|
||||
|
||||
var orderService = LazyServiceProvider.GetRequiredService<OrderService>();
|
||||
var orders = new List<Domain.OrdersAggregate.Entities.Order>();
|
||||
foreach (var id in orderIds)
|
||||
{
|
||||
var order = await OrderRepository.FirstOrDefaultAsync(x => x.Id == id)
|
||||
?? throw new BusinessException($"订单不存在:{id}");
|
||||
if (order.IsPaid > 0)
|
||||
{
|
||||
throw new BusinessException($"订单已支付:{order.ServiceNo}");
|
||||
}
|
||||
|
||||
if (order.OrderStatus is not OrderStatusCodes.PendingPayment)
|
||||
{
|
||||
throw new BusinessException($"订单状态不可支付:{order.ServiceNo}");
|
||||
}
|
||||
|
||||
if (!order.CustomerId.HasValue)
|
||||
{
|
||||
throw new BusinessException($"订单未关联客户:{order.ServiceNo}");
|
||||
}
|
||||
|
||||
orders.Add(order);
|
||||
}
|
||||
|
||||
var customerIds = orders.Select(x => x.CustomerId!.Value).Distinct().ToList();
|
||||
if (customerIds.Count > 1)
|
||||
{
|
||||
throw new BusinessException("批量在线支付仅支持同一客户的订单,请拆分后支付");
|
||||
}
|
||||
|
||||
var customerId = customerIds[0];
|
||||
var customer = await CustomerRepository.FirstOrDefaultAsync(x => x.Id == customerId)
|
||||
?? throw new BusinessException("客户不存在");
|
||||
|
||||
var lines = new List<(Domain.OrdersAggregate.Entities.Order Order, decimal Payable, int? CouponId, decimal Bal, decimal Wx)>();
|
||||
decimal payableTotal = 0;
|
||||
foreach (var order in orders)
|
||||
{
|
||||
int? couponArg = null;
|
||||
if (input.CouponByOrderId != null && input.CouponByOrderId.TryGetValue(order.Id, out var c))
|
||||
{
|
||||
couponArg = c;
|
||||
}
|
||||
|
||||
// 通过 OrderService 支付预览口径:委托 Build 需用公共 API
|
||||
var preview = await orderService.GetPayPreviewAsync(new OrderPayPreviewInput
|
||||
{
|
||||
Id = order.Id,
|
||||
CouponInstanceId = couponArg
|
||||
});
|
||||
if (preview.PayableAmount <= 0 || preview.ReceivableSubtotal <= 0)
|
||||
{
|
||||
throw new BusinessException($"订单应付无效:{order.ServiceNo}");
|
||||
}
|
||||
|
||||
payableTotal += preview.PayableAmount;
|
||||
lines.Add((order, preview.PayableAmount, preview.AppliedCouponInstanceId, 0M, 0M));
|
||||
}
|
||||
|
||||
var balanceUse = Math.Min(customer.Balance, payableTotal);
|
||||
var wechatAmount = payableTotal - balanceUse;
|
||||
// 贪心拆分余额到各票
|
||||
var remainBal = balanceUse;
|
||||
var allocated = new List<(Domain.OrdersAggregate.Entities.Order Order, decimal Payable, int? CouponId, decimal Bal, decimal Wx)>();
|
||||
foreach (var row in lines)
|
||||
{
|
||||
var bal = Math.Min(remainBal, row.Payable);
|
||||
remainBal -= bal;
|
||||
var wx = row.Payable - bal;
|
||||
allocated.Add((row.Order, row.Payable, row.CouponId, bal, wx));
|
||||
}
|
||||
|
||||
var outputLines = allocated.Select(x => new OrderWeChatPayLineOutput
|
||||
{
|
||||
OrderId = x.Order.Id,
|
||||
ServiceNo = x.Order.ServiceNo,
|
||||
PayableAmount = x.Payable,
|
||||
BalanceAmount = x.Bal,
|
||||
WechatAmount = x.Wx,
|
||||
CouponInstanceId = x.CouponId
|
||||
}).ToList();
|
||||
|
||||
if (wechatAmount <= 0)
|
||||
{
|
||||
foreach (var row in allocated)
|
||||
{
|
||||
await orderService.PayAsync(new OrderPayInput
|
||||
{
|
||||
Id = row.Order.Id,
|
||||
CouponInstanceId = row.CouponId ?? 0
|
||||
});
|
||||
}
|
||||
|
||||
return new CreateOrderWeChatPayOutput
|
||||
{
|
||||
PayableTotal = payableTotal,
|
||||
BalanceAmount = balanceUse,
|
||||
WechatAmount = 0,
|
||||
CustomerBalance = customer.Balance,
|
||||
PaidImmediately = true,
|
||||
Lines = outputLines
|
||||
};
|
||||
}
|
||||
|
||||
WechatTenpayClient client;
|
||||
WeChatPayMerchantSettings settings;
|
||||
try
|
||||
{
|
||||
(client, settings) = await ClientFactory.CreateAsync();
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
throw new BusinessException(ex.Message);
|
||||
}
|
||||
|
||||
var outTradeNo = await GenerateOutTradeNoAsync();
|
||||
var expire = DateTimeOffset.Now.Add(PayExpire);
|
||||
var channel = scene == "jsapi" ? PaymentChannelCodes.WechatJsapi : PaymentChannelCodes.WechatNative;
|
||||
var amountFen = ToFen(wechatAmount);
|
||||
|
||||
var payment = new PaymentOrder
|
||||
{
|
||||
OutTradeNo = outTradeNo,
|
||||
BizType = PaymentBizTypeCodes.OrderPay,
|
||||
BizId = allocated[0].Order.Id,
|
||||
CustomerId = customerId,
|
||||
Amount = wechatAmount,
|
||||
BalanceAmount = balanceUse,
|
||||
Currency = "CNY",
|
||||
Channel = channel,
|
||||
Status = PaymentOrderStatus.Created,
|
||||
ExpireTime = expire.DateTime,
|
||||
Remark = "订单混合支付待向微信下单"
|
||||
};
|
||||
payment = await PaymentOrderRepository.InsertAsync(payment);
|
||||
|
||||
foreach (var row in allocated)
|
||||
{
|
||||
await PaymentOrderLineRepository.InsertAsync(new PaymentOrderLine
|
||||
{
|
||||
PaymentOrderId = payment.Id,
|
||||
OrderId = row.Order.Id,
|
||||
PayableAmount = row.Payable,
|
||||
BalanceAmount = row.Bal,
|
||||
WechatAmount = row.Wx,
|
||||
CouponInstanceId = row.CouponId
|
||||
});
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
CreateOrderWeChatPayOutput output;
|
||||
if (scene == "jsapi")
|
||||
{
|
||||
var openId = await ResolveOpenIdAsync(customer.Id, customer.WechatOpenid, input.OauthCode);
|
||||
var request = new CreatePayTransactionJsapiRequest
|
||||
{
|
||||
OutTradeNumber = outTradeNo,
|
||||
AppId = settings.AppId,
|
||||
Description = $"运单支付-{customer.CustomerCode}",
|
||||
ExpireTime = expire,
|
||||
NotifyUrl = settings.NotifyUrl,
|
||||
Amount = new CreatePayTransactionJsapiRequest.Types.Amount { Total = amountFen, Currency = "CNY" },
|
||||
Payer = new CreatePayTransactionJsapiRequest.Types.Payer { OpenId = openId },
|
||||
Attachment = $"order_pay:{payment.Id}"
|
||||
};
|
||||
var response = await client.ExecuteCreatePayTransactionJsapiAsync(request);
|
||||
if (!response.IsSuccessful() || string.IsNullOrWhiteSpace(response.PrepayId))
|
||||
{
|
||||
throw new BusinessException($"微信 JSAPI 下单失败:{response.ErrorCode} {response.ErrorMessage}");
|
||||
}
|
||||
|
||||
payment.PrepayId = response.PrepayId;
|
||||
payment.Status = PaymentOrderStatus.Paying;
|
||||
payment.Remark = "订单混合支付 Paying";
|
||||
await PaymentOrderRepository.UpdateAsync(payment);
|
||||
|
||||
var paramMap = client.GenerateParametersForJsapiPayRequest(settings.AppId, response.PrepayId);
|
||||
output = new CreateOrderWeChatPayOutput
|
||||
{
|
||||
PayableTotal = payableTotal,
|
||||
BalanceAmount = balanceUse,
|
||||
WechatAmount = wechatAmount,
|
||||
CustomerBalance = customer.Balance,
|
||||
PaidImmediately = false,
|
||||
OutTradeNo = outTradeNo,
|
||||
Channel = channel,
|
||||
Status = nameof(PaymentOrderStatus.Paying),
|
||||
ExpireTime = payment.ExpireTime,
|
||||
Jsapi = new WeChatJsapiPayParams
|
||||
{
|
||||
AppId = DictGet(paramMap, "appId") ?? settings.AppId,
|
||||
TimeStamp = DictGet(paramMap, "timeStamp") ?? string.Empty,
|
||||
NonceStr = DictGet(paramMap, "nonceStr") ?? string.Empty,
|
||||
Package = DictGet(paramMap, "package") ?? $"prepay_id={response.PrepayId}",
|
||||
SignType = DictGet(paramMap, "signType") ?? "RSA",
|
||||
PaySign = DictGet(paramMap, "paySign") ?? string.Empty
|
||||
},
|
||||
Lines = outputLines
|
||||
};
|
||||
}
|
||||
else
|
||||
{
|
||||
var request = new CreatePayTransactionNativeRequest
|
||||
{
|
||||
OutTradeNumber = outTradeNo,
|
||||
AppId = settings.AppId,
|
||||
Description = $"运单支付-{customer.CustomerCode}",
|
||||
ExpireTime = expire,
|
||||
NotifyUrl = settings.NotifyUrl,
|
||||
Amount = new CreatePayTransactionNativeRequest.Types.Amount { Total = amountFen, Currency = "CNY" },
|
||||
Attachment = $"order_pay:{payment.Id}"
|
||||
};
|
||||
var response = await client.ExecuteCreatePayTransactionNativeAsync(request);
|
||||
if (!response.IsSuccessful() || string.IsNullOrWhiteSpace(response.QrcodeUrl))
|
||||
{
|
||||
throw new BusinessException($"微信 Native 下单失败:{response.ErrorCode} {response.ErrorMessage}");
|
||||
}
|
||||
|
||||
payment.CodeUrl = response.QrcodeUrl;
|
||||
payment.Status = PaymentOrderStatus.Paying;
|
||||
payment.Remark = "订单混合支付 Paying";
|
||||
await PaymentOrderRepository.UpdateAsync(payment);
|
||||
|
||||
output = new CreateOrderWeChatPayOutput
|
||||
{
|
||||
PayableTotal = payableTotal,
|
||||
BalanceAmount = balanceUse,
|
||||
WechatAmount = wechatAmount,
|
||||
CustomerBalance = customer.Balance,
|
||||
PaidImmediately = false,
|
||||
OutTradeNo = outTradeNo,
|
||||
Channel = channel,
|
||||
Status = nameof(PaymentOrderStatus.Paying),
|
||||
ExpireTime = payment.ExpireTime,
|
||||
CodeUrl = response.QrcodeUrl,
|
||||
Lines = outputLines
|
||||
};
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
try
|
||||
{
|
||||
payment.Status = PaymentOrderStatus.Failed;
|
||||
payment.Remark = TruncateRemark($"微信下单失败:{ex.Message}");
|
||||
await PaymentOrderRepository.UpdateAsync(payment);
|
||||
}
|
||||
catch (Exception cleanupEx)
|
||||
{
|
||||
PayLogger.LogError(cleanupEx, "订单支付微信下单失败后清理异常 OutTradeNo={OutTradeNo}", outTradeNo);
|
||||
}
|
||||
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task FailCreateCleanupAsync(PaymentOrder payment, RechargeRecord recharge, string? reason)
|
||||
{
|
||||
try
|
||||
|
||||
@ -24,9 +24,12 @@ public class PaymentOrder : OmsAuditedAggregateRoot
|
||||
/// <summary>客户 Id。</summary>
|
||||
public int CustomerId { get; set; }
|
||||
|
||||
/// <summary>支付金额(元)。</summary>
|
||||
/// <summary>微信支付金额(元);订单混合支付时为补差部分。</summary>
|
||||
public decimal Amount { get; set; }
|
||||
|
||||
/// <summary>本次拟扣账户余额(元);订单混合支付用,成功前不实扣。</summary>
|
||||
public decimal BalanceAmount { get; set; }
|
||||
|
||||
/// <summary>币种。</summary>
|
||||
[SugarColumn(Length = 8)]
|
||||
public string Currency { get; set; } = "CNY";
|
||||
|
||||
30
src/Oms.Domain/PaymentAggregate/Entities/PaymentOrderLine.cs
Normal file
30
src/Oms.Domain/PaymentAggregate/Entities/PaymentOrderLine.cs
Normal file
@ -0,0 +1,30 @@
|
||||
using Oms.Domain.Shared;
|
||||
using SqlSugar;
|
||||
|
||||
namespace Oms.Domain.PaymentAggregate.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// 在线支付单明细(订单混合支付:一笔补差对应多票)。
|
||||
/// </summary>
|
||||
[SugarTable("t_payment_order_line")]
|
||||
public class PaymentOrderLine : OmsAuditedAggregateRoot
|
||||
{
|
||||
/// <summary>支付单 Id。</summary>
|
||||
public int PaymentOrderId { get; set; }
|
||||
|
||||
/// <summary>运单 Id。</summary>
|
||||
public int OrderId { get; set; }
|
||||
|
||||
/// <summary>本单应付(元)。</summary>
|
||||
public decimal PayableAmount { get; set; }
|
||||
|
||||
/// <summary>本单用余额(元)。</summary>
|
||||
public decimal BalanceAmount { get; set; }
|
||||
|
||||
/// <summary>本单微信补差(元)。</summary>
|
||||
public decimal WechatAmount { get; set; }
|
||||
|
||||
/// <summary>优惠券实例 Id。</summary>
|
||||
[SugarColumn(IsNullable = true)]
|
||||
public int? CouponInstanceId { get; set; }
|
||||
}
|
||||
@ -7,4 +7,7 @@ public static class PaymentBizTypeCodes
|
||||
{
|
||||
/// <summary>客户充值。</summary>
|
||||
public const string Recharge = "recharge";
|
||||
|
||||
/// <summary>订单支付(余额+微信补差)。</summary>
|
||||
public const string OrderPay = "order_pay";
|
||||
}
|
||||
|
||||
@ -0,0 +1,11 @@
|
||||
using Fake.Domain.Repositories;
|
||||
using Oms.Domain.PaymentAggregate.Entities;
|
||||
|
||||
namespace Oms.Domain.PaymentAggregate.Repositories;
|
||||
|
||||
public interface IPaymentOrderLineRepository : IRepository<PaymentOrderLine>
|
||||
{
|
||||
Task<List<PaymentOrderLine>> GetListByPaymentOrderIdAsync(
|
||||
int paymentOrderId,
|
||||
CancellationToken cancellationToken = default);
|
||||
}
|
||||
22
src/Oms.SqlSugarCore/Payment/PaymentOrderLineRepository.cs
Normal file
22
src/Oms.SqlSugarCore/Payment/PaymentOrderLineRepository.cs
Normal file
@ -0,0 +1,22 @@
|
||||
using Fake.DependencyInjection;
|
||||
using Oms.Domain.PaymentAggregate.Entities;
|
||||
using Oms.Domain.PaymentAggregate.Repositories;
|
||||
using Oms.SqlSugarCore.Repositories;
|
||||
|
||||
namespace Oms.SqlSugarCore.Payment;
|
||||
|
||||
public class PaymentOrderLineRepository
|
||||
: OmsSqlSugarRepository<PaymentOrderLine>, IPaymentOrderLineRepository, IScopedDependency
|
||||
{
|
||||
public async Task<List<PaymentOrderLine>> GetListByPaymentOrderIdAsync(
|
||||
int paymentOrderId,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (paymentOrderId <= 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
return await GetListAsync(x => x.PaymentOrderId == paymentOrderId, cancellationToken);
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user