完成支付失败商户轮换禁用
Some checks failed
构建并部署到测试环境(无 SSH) / build-and-deploy (push) Failing after 5h7m21s

This commit is contained in:
2026-09-22 15:58:03 +08:00
parent 622e99b543
commit 9959168e22
16 changed files with 579 additions and 70 deletions

View File

@@ -112,6 +112,11 @@ func (s *OnlineCreationService) Execute(ctx context.Context, command CreateOnlin
ExpireAt: *result.Payment.ExpireAt, PayerClientIP: command.PayerClientIP, Config: config,
})
if err != nil {
if merchantpayment.ShouldDisableMerchant(err) {
if disableErr := merchantpayment.DisableMerchantAfterExplicitFailure(ctx, s.db, result.Payment, "payment_precreate_failed", time.Now()); disableErr != nil {
return nil, disableErr
}
}
if !isUnknownPaymentResult(err) {
if closeErr := s.closeFailedCreation(ctx, result); closeErr != nil {
return nil, apperrors.Wrap(apperrors.CodeDatabaseError, closeErr, "支付链接生成失败且关闭本地订单失败")
@@ -286,10 +291,13 @@ func (s *OnlineCreationService) createLocalFacts(
if err := tx.Create(payment).Error; err != nil {
return err
}
return s.audit.WriteAgentRechargePayment(ctx, tx, PaymentAudit{
if err := s.audit.WriteAgentRechargePayment(ctx, tx, PaymentAudit{
ActionCode: constants.AuditActionPaymentCreated, Summary: "创建代理充值支付记录",
Payment: payment, Recharge: record, AfterData: map[string]any{"status": payment.Status},
})
}); err != nil {
return err
}
return merchantpayment.RecordRoutingAttempt(ctx, tx, payment)
})
if err != nil {
var appErr *apperrors.AppError

View File

@@ -650,7 +650,7 @@ func merchantResponse(m *model.PaymentMerchant) *dto.PaymentMerchantResponse {
// poolResponse 组装商户池响应,成员、成员计数与命中成员由只读投影提供。
func poolResponse(p *model.PaymentMerchantPool, projection poolProjection) *dto.PaymentMerchantPoolResponse {
response := &dto.PaymentMerchantPoolResponse{ID: p.ID, Name: p.Name, PaymentMethod: p.PaymentMethod, Enabled: p.Status == model.PaymentMerchantStatusEnabled, Strategy: p.Strategy, ThresholdAmount: p.ThresholdAmount, ThresholdCount: p.ThresholdCount, StatisticCycle: p.StatisticCycle, TimePeriodValue: p.TimePeriodValue, TimePeriodUnit: p.TimePeriodUnit, TimePeriodStartedAt: p.TimePeriodStartedAt, RoutingEpoch: p.RoutingEpoch, MemberIDs: projection.MemberIDs, EnabledMemberCount: projection.EnabledMembers, MemberCount: len(projection.MemberIDs), UpdatedAt: p.UpdatedAt, Remark: p.Remark}
response := &dto.PaymentMerchantPoolResponse{ID: p.ID, Name: p.Name, PaymentMethod: p.PaymentMethod, Enabled: p.Status == model.PaymentMerchantStatusEnabled, Strategy: p.Strategy, ThresholdAmount: p.ThresholdAmount, ThresholdCount: p.ThresholdCount, StatisticCycle: p.StatisticCycle, TimePeriodValue: p.TimePeriodValue, TimePeriodUnit: p.TimePeriodUnit, TimePeriodStartedAt: p.TimePeriodStartedAt, RoutingEpoch: p.RoutingEpoch, MemberIDs: projection.MemberIDs, EnabledMemberCount: projection.EnabledMembers, MemberCount: len(projection.MemberIDs), UpdatedAt: p.UpdatedAt, Remark: p.Remark, LastFailureMerchantID: projection.LastFailureMerchantID, LastFailurePaymentID: projection.LastFailurePaymentID, LastFailurePaymentNo: projection.LastFailurePaymentNo, LastFailureReason: projection.LastFailureReason, LastFailureAt: projection.LastFailureAt}
if projection.CurrentMerchant != nil {
merchantID := projection.CurrentMerchant.ID
response.CurrentMerchantID = &merchantID

View File

@@ -2,7 +2,9 @@ package merchantpayment
import (
"context"
stderrors "errors"
"fmt"
"net"
"strings"
"time"
@@ -257,19 +259,19 @@ type routingOutcome struct {
OpenNewRound bool
}
// routeStats 是已按统计世代隔离的商户成功累计。
// routeStats 是已按统计世代隔离的商户路由尝试累计。
type routeStats struct {
amounts map[uint]int64
counts map[uint]int64
}
// newRouteStats 创建空的成功累计聚合。
// newRouteStats 创建空的路由尝试累计聚合。
func newRouteStats() routeStats {
return routeStats{amounts: map[uint]int64{}, counts: map[uint]int64{}}
}
// add 累加一条成功事实。
func (s routeStats) add(row *model.PaymentMerchantRoutingSuccess) {
// add 累加一条路由尝试事实。
func (s routeStats) add(row *model.PaymentMerchantRoutingAttempt) {
s.amounts[row.MerchantID] += row.Amount
s.counts[row.MerchantID]++
}
@@ -368,8 +370,8 @@ func chooseMerchant(ctx context.Context, tx *gorm.DB, pool *model.PaymentMerchan
return outcome.Merchant, nil
}
// loadPoolRouteStats 读取单个商户池当前统计世代的成功累计。
// 自然日与自然月周期只统计支付时间不早于当期窗口起点的成功事实。
// loadPoolRouteStats 读取单个商户池当前统计世代的路由尝试累计。
// 自然日与自然月周期只统计支付创建时间不早于当期窗口起点的尝试事实。
func loadPoolRouteStats(ctx context.Context, tx *gorm.DB, pool *model.PaymentMerchantPool, now time.Time) (routeStats, error) {
cycle, err := statisticCycle(pool)
if err != nil {
@@ -377,9 +379,9 @@ func loadPoolRouteStats(ctx context.Context, tx *gorm.DB, pool *model.PaymentMer
}
query := tx.WithContext(ctx).Where("pool_id = ? AND routing_epoch = ?", pool.ID, pool.RoutingEpoch)
if start, limited := routingWindowStart(cycle, now); limited {
query = query.Where("paid_at >= ?", start)
query = query.Where("created_at >= ?", start)
}
var rows []model.PaymentMerchantRoutingSuccess
var rows []model.PaymentMerchantRoutingAttempt
if err := query.Find(&rows).Error; err != nil {
return routeStats{}, err
}
@@ -440,14 +442,16 @@ func advanceRoutingEpoch(ctx context.Context, tx *gorm.DB, pool *model.PaymentMe
return nil
}
// poolProjection 是商户池列表投影的只读计算结果。
// poolProjection 是商户池列表的只读计算结果。
type poolProjection struct {
// MemberIDs 是按顺序排列的成员商户ID。
MemberIDs []uint
// EnabledMembers 是成员中当前启用且支付方式与池一致的商户数量。
EnabledMembers int
// CurrentMerchant 是当前命中成员;池停用或无可用成员时为空。
CurrentMerchant *model.PaymentMerchant
MemberIDs []uint
EnabledMembers int
CurrentMerchant *model.PaymentMerchant
LastFailureMerchantID *uint
LastFailurePaymentID *uint
LastFailurePaymentNo string
LastFailureReason string
LastFailureAt *time.Time
}
// loadPoolProjections 按页批量计算成员计数与当前命中成员,供列表与详情投影复用。
@@ -484,8 +488,7 @@ func loadPoolProjections(ctx context.Context, db *gorm.DB, pools []*model.Paymen
merchants[merchant.ID] = merchant
}
}
// 金额与笔数启用池当前世代的成功累计一次查出:按池拼出「池 + 世代(+ 当期窗口起点)」
// 条件,既避免逐池查询,也避免把其他世代与上一周期的成功事实读进内存。
// 金额与笔数启用池当前世代的路由尝试累计一次查出:按池拼出「池 + 世代(+ 当期窗口起点)」条件,避免逐池查询。
terms := make([]string, 0, len(pools))
args := make([]any, 0, len(pools)*3)
for _, pool := range pools {
@@ -500,7 +503,7 @@ func loadPoolProjections(ctx context.Context, db *gorm.DB, pools []*model.Paymen
continue
}
if start, limited := routingWindowStart(cycle, now); limited {
terms = append(terms, "(pool_id = ? AND routing_epoch = ? AND paid_at >= ?)")
terms = append(terms, "(pool_id = ? AND routing_epoch = ? AND created_at >= ?)")
args = append(args, pool.ID, pool.RoutingEpoch, start)
continue
}
@@ -509,7 +512,7 @@ func loadPoolProjections(ctx context.Context, db *gorm.DB, pools []*model.Paymen
}
statsByPool := make(map[uint]routeStats, len(pools))
if len(terms) > 0 {
var rows []model.PaymentMerchantRoutingSuccess
var rows []model.PaymentMerchantRoutingAttempt
if err := db.WithContext(ctx).Where(strings.Join(terms, " OR "), args...).Find(&rows).Error; err != nil {
return nil, err
}
@@ -523,9 +526,29 @@ func loadPoolProjections(ctx context.Context, db *gorm.DB, pools []*model.Paymen
stats.add(row)
}
}
var failures []model.PaymentMerchantFailure
if err := db.WithContext(ctx).Where("pool_id IN ? AND result_class = ?", poolIDs, "explicit_failed").Order("occurred_at DESC, id DESC").Find(&failures).Error; err != nil {
return nil, err
}
failureByPool := make(map[uint]model.PaymentMerchantFailure, len(failures))
for index := range failures {
failure := failures[index]
if _, exists := failureByPool[failure.PoolID]; !exists {
failureByPool[failure.PoolID] = failure
}
}
for _, pool := range pools {
ordered := orderedEnabledMembers(pool, membersByPool[pool.ID], merchants)
projection := poolProjection{MemberIDs: membersByPool[pool.ID], EnabledMembers: len(ordered)}
if failure, ok := failureByPool[pool.ID]; ok {
merchantID, paymentID := failure.MerchantID, failure.PaymentID
projection.LastFailureMerchantID = &merchantID
projection.LastFailurePaymentID = &paymentID
projection.LastFailurePaymentNo = failure.PaymentNo
projection.LastFailureReason = failure.FailureReason
occurredAt := failure.OccurredAt
projection.LastFailureAt = &occurredAt
}
if pool.Status == model.PaymentMerchantStatusEnabled {
if outcome, err := selectRouteMember(pool, ordered, statsByPool[pool.ID], now); err == nil {
projection.CurrentMerchant = outcome.Merchant
@@ -580,3 +603,115 @@ func RecordFirstSuccess(ctx context.Context, tx *gorm.DB, payment *model.Payment
}
return nil
}
// RecordRoutingAttempt 在支付单与冻结路由同一事务中写入一次路由尝试事实。
// 唯一支付约束使并发重放和重复建账不会增加第二次统计。
func RecordRoutingAttempt(ctx context.Context, tx *gorm.DB, payment *model.Payment) error {
if payment == nil || payment.ID == 0 || payment.MerchantID == nil || payment.MerchantPoolID == nil || payment.RoutingEpoch == nil || payment.Amount <= 0 {
return nil
}
attempt := &model.PaymentMerchantRoutingAttempt{
PaymentID: payment.ID, MerchantID: *payment.MerchantID, PoolID: *payment.MerchantPoolID,
RoutingEpoch: *payment.RoutingEpoch, Amount: payment.Amount, ResultClass: "pending",
}
if err := tx.WithContext(ctx).Create(attempt).Error; err != nil {
if strings.Contains(err.Error(), "duplicate key") {
return nil
}
return errors.Wrap(errors.CodeDatabaseError, err, "写入商户池路由尝试失败")
}
return nil
}
// DisableMerchantAfterExplicitFailure 条件禁用冻结商户,并写入脱敏失败调查事实。
func DisableMerchantAfterExplicitFailure(ctx context.Context, db *gorm.DB, payment *model.Payment, reason string, now time.Time) error {
if payment == nil || payment.ID == 0 || payment.MerchantID == nil || payment.MerchantPoolID == nil || db == nil {
return nil
}
return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
var merchant model.PaymentMerchant
if err := tx.WithContext(ctx).First(&merchant, *payment.MerchantID).Error; err != nil {
return errors.Wrap(errors.CodeDatabaseError, err, "读取失败支付商户状态失败")
}
result := tx.WithContext(ctx).Model(&model.PaymentMerchant{}).
Where("id = ? AND status = ?", merchant.ID, model.PaymentMerchantStatusEnabled).
Update("status", model.PaymentMerchantStatusDisabled)
if result.Error != nil {
return errors.Wrap(errors.CodeDatabaseError, result.Error, "自动禁用失败支付商户失败")
}
after := merchant.Status
if result.RowsAffected == 1 {
after = model.PaymentMerchantStatusDisabled
}
failure := &model.PaymentMerchantFailure{
PaymentID: payment.ID, PaymentNo: payment.PaymentNo, MerchantID: merchant.ID,
PoolID: *payment.MerchantPoolID, ResultClass: "explicit_failed", FailureReason: safeFailureReason(reason),
StatusBefore: merchant.Status, StatusAfter: after, OccurredAt: now,
}
if err := tx.WithContext(ctx).Create(failure).Error; err != nil {
return errors.Wrap(errors.CodeDatabaseError, err, "写入支付商户失败留痕失败")
}
return nil
})
}
func safeFailureReason(reason string) string {
reason = strings.TrimSpace(reason)
if len(reason) > 128 {
return reason[:128]
}
return reason
}
// PreCreateResultClass 是渠道预下单结果的稳定分类。
type PreCreateResultClass string
const (
PreCreateResultSuccess PreCreateResultClass = "success"
PreCreateResultExplicitFailed PreCreateResultClass = "explicit_failed"
PreCreateResultUnknown PreCreateResultClass = "unknown"
PreCreateResultNotSent PreCreateResultClass = "not_sent"
)
// ClassifyPreCreateResult 统一判断预下单结果及自动禁用资格。
func ClassifyPreCreateResult(err error, sent bool) PreCreateResultClass {
if err == nil {
return PreCreateResultSuccess
}
if !sent {
return PreCreateResultNotSent
}
if !ShouldDisableMerchant(err) {
return PreCreateResultUnknown
}
return PreCreateResultExplicitFailed
}
// ShouldDisableMerchant 仅在没有结果未知信号且错误代表渠道明确拒绝时返回 true。
// 上下文取消、超时、连接中断、网络传输错误和响应无法确认均不得禁用商户。
func ShouldDisableMerchant(err error) bool {
if err == nil {
return false
}
if stderrors.Is(err, context.Canceled) || stderrors.Is(err, context.DeadlineExceeded) {
return false
}
var networkErr net.Error
if stderrors.As(err, &networkErr) {
return false
}
var appErr *errors.AppError
if !stderrors.As(err, &appErr) || appErr == nil {
return false
}
if appErr.Code == errors.CodeTimeout || appErr.Code == errors.CodeServiceUnavailable || appErr.Code == errors.CodeNoPaymentConfig {
return false
}
message := strings.ToLower(appErr.Error())
for _, marker := range []string{"timeout", "deadline", "context canceled", "connection", "transport", "network", "unknown", "结果未知", "无法确认", "连接中断"} {
if strings.Contains(message, marker) {
return false
}
}
return appErr.Code == errors.CodeWechatPayFailed || appErr.Code == errors.CodeFuiouPayFailed
}