Merge pull request #9258 from zriyox/fix/payment-expired-order-recovery

fix(payment): 过期订单收到支付成功回调后照常入账;过期前查单失败不再直接置为过期
This commit is contained in:
Wesley Liddick authored and GitHub committed 2026-12-04 23:42:23 +08:00
commit eb413d9b39
5 files changed
+130 -25

No files matched your search

@@ -178,17 +178,13 @@ func expectedNotificationProviderKey(registry *payment.Registry, orderPaymentTyp
func (s *PaymentService) toPaid(ctx context.Context, o *dbent.PaymentOrder, tradeNo string, paid float64, pk string) error {
previousStatus := o.Status
now := time.Now()
grace := now.Add(-paymentGraceMinutes * time.Minute)
// A verified success notification means the money has already moved, so
// an expired order is recovered no matter how long ago it expired, the
// same as a cancelled one. Gateways such as EasyPay keep the hosted
// cashier open after our local expiry, so late payments are normal.
c, err := s.entClient.PaymentOrder.Update().Where(
paymentorder.IDEQ(o.ID),
paymentorder.Or(
paymentorder.StatusEQ(OrderStatusPending),
paymentorder.StatusEQ(OrderStatusCancelled),
paymentorder.And(
paymentorder.StatusEQ(OrderStatusExpired),
paymentorder.UpdatedAtGTE(grace),
),
),
paymentorder.StatusIn(OrderStatusPending, OrderStatusCancelled, OrderStatusExpired),
).SetStatus(OrderStatusPaid).SetPayAmount(paid).SetPaymentTradeNo(tradeNo).SetPaidAt(now).ClearFailedAt().ClearFailedReason().Save(ctx)
if err != nil {
return fmt.Errorf("update to PAID: %w", err)
@@ -224,18 +220,6 @@ func (s *PaymentService) alreadyProcessed(ctx context.Context, o *dbent.PaymentO
return nil
case OrderStatusFailed, OrderStatusPaid, OrderStatusRecharging:
return s.executeFulfillment(ctx, o.ID)
case OrderStatusExpired:
slog.Warn("webhook payment success for expired order beyond grace period",
"orderID", o.ID,
"status", cur.Status,
"updatedAt", cur.UpdatedAt,
)
s.writeAuditLog(ctx, o.ID, "PAYMENT_AFTER_EXPIRY", "system", map[string]any{
"status": cur.Status,
"updatedAt": cur.UpdatedAt,
"reason": "payment arrived after expiry grace period",
})
return nil
default:
return nil
}
@@ -1293,3 +1293,46 @@ func TestExecuteSubscriptionFulfillmentDoesNotDuplicateWorkAfterLegacySuccessAud
var _ AffiliateRepository = (*paymentFulfillmentAffiliateRepoStub)(nil)
var _ SettingRepository = (*paymentFulfillmentSettingRepoStub)(nil)
// Reproduces a production incident: the order expired locally, the user then
// paid on EasyPay's still-open cashier, and the verified success callback
// arrived six minutes after expiry. It was dropped and never credited.
func TestPaymentNotificationRecoversOrderPaidLongAfterExpiry(t *testing.T) {
ctx := context.Background()
client := newPaymentConfigServiceTestClient(t)
ensurePaymentAuditOrderActionUniqueIndex(t, ctx, client)
expiredAt := time.Now().Add(-6 * time.Minute)
order := createPaymentFulfillmentSubscriptionOrder(t, ctx, client, OrderStatusExpired, expiredAt)
order, err := client.PaymentOrder.UpdateOneID(order.ID).
SetOrderType(payment.OrderTypeBalance).
ClearPlanID().
ClearSubscriptionGroupID().
ClearSubscriptionDays().
ClearPaidAt().
SetUpdatedAt(expiredAt).
Save(ctx)
require.NoError(t, err)
credited := 0.0
userRepo := &mockUserRepo{getByIDUser: &User{ID: order.UserID, Balance: 0}}
userRepo.updateBalanceFn = func(_ context.Context, _ int64, amount float64) error {
credited += amount
return nil
}
redeemService := NewRedeemService(&paymentFulfillmentRedeemRepo{}, userRepo, nil, &paymentFulfillmentRedeemCacheStub{}, nil, client, nil, nil)
svc := &PaymentService{entClient: client, redeemService: redeemService, userRepo: userRepo}
err = svc.HandlePaymentNotification(ctx, &payment.PaymentNotification{
TradeNo: "easypay-late-trade",
OrderID: order.OutTradeNo,
Amount: order.PayAmount,
Status: payment.NotificationStatusSuccess,
}, payment.TypeAlipay)
require.NoError(t, err)
require.InDelta(t, order.Amount, credited, 1e-8, "a verified payment must be credited however late it arrives")
reloaded, err := client.PaymentOrder.Get(ctx, order.ID)
require.NoError(t, err)
require.Equal(t, OrderStatusCompleted, reloaded.Status)
require.Equal(t, "easypay-late-trade", reloaded.PaymentTradeNo)
}
@@ -26,8 +26,17 @@ const (
rateLimitModeFixed = "fixed"
checkPaidResultAlreadyPaid = "already_paid"
checkPaidResultCancelled = "cancelled"
// checkPaidResultQueryFailed means the upstream status is unknown: the
// order may already be paid, so expiry must not close it yet.
checkPaidResultQueryFailed = "query_failed"
pendingPaymentReconcileLimit = 20
// paymentExpiryQueryRetryWindow bounds how long the expiry job keeps a
// timed-out order pending while the upstream status query keeps failing.
// After it the order expires anyway; a late success webhook still
// recovers it.
paymentExpiryQueryRetryWindow = time.Hour
)
type checkPaidOptions struct {
@@ -123,8 +132,13 @@ func (s *PaymentService) AdminCancelOrder(ctx context.Context, orderID int64) (s
func (s *PaymentService) cancelCore(ctx context.Context, o *dbent.PaymentOrder, fs, op, ad string) (string, error) {
if o.PaymentTradeNo != "" || o.PaymentType != "" {
if s.checkPaid(ctx, o) == checkPaidResultAlreadyPaid {
switch s.checkPaid(ctx, o) {
case checkPaidResultAlreadyPaid:
return checkPaidResultAlreadyPaid, nil
case checkPaidResultQueryFailed:
if fs == OrderStatusExpired && time.Since(o.ExpiresAt) < paymentExpiryQueryRetryWindow {
return checkPaidResultQueryFailed, nil
}
}
}
c, err := s.entClient.PaymentOrder.Update().Where(paymentorder.IDEQ(o.ID), paymentorder.StatusEQ(OrderStatusPending)).SetStatus(fs).Save(ctx)
@@ -163,7 +177,7 @@ func (s *PaymentService) checkPaidWithOptions(ctx context.Context, o *dbent.Paym
finishProviderCall()
if err != nil {
slog.Warn("query upstream failed", "orderID", o.ID, "error", err)
return ""
return checkPaidResultQueryFailed
}
if resp.Status == payment.ProviderStatusPaid {
if !isValidProviderAmount(resp.Amount) {
@@ -391,6 +405,10 @@ func (s *PaymentService) ExpireTimedOutOrders(ctx context.Context) (int, error)
slog.Info("order was paid during expiry", "orderID", o.ID)
continue
}
if outcome == checkPaidResultQueryFailed {
slog.Warn("upstream query failed, keeping order pending for the next expiry run", "orderID", o.ID)
continue
}
if outcome != "" {
n++
}
@@ -5,6 +5,7 @@ package service
import (
"context"
"database/sql"
"errors"
"testing"
"time"
@@ -27,6 +28,7 @@ type paymentOrderLifecycleQueryProvider struct {
cancelCalls int
responses []*payment.QueryOrderResponse
resp *payment.QueryOrderResponse
queryErr error
}
type paymentOrderLifecycleRedeemRepo struct {
@@ -59,6 +61,9 @@ func (p *paymentOrderLifecycleQueryProvider) CreatePayment(context.Context, paym
func (p *paymentOrderLifecycleQueryProvider) QueryOrder(_ context.Context, tradeNo string) (*payment.QueryOrderResponse, error) {
p.lastQueryTradeNo = tradeNo
p.queryCalls++
if p.queryErr != nil {
return nil, p.queryErr
}
if len(p.responses) > 0 {
resp := p.responses[0]
if len(p.responses) > 1 {
@@ -864,3 +869,60 @@ func newPaymentOrderLifecycleTestClient(t *testing.T) *dbent.Client {
t.Cleanup(func() { _ = client.Close() })
return client
}
// Reproduces a production incident: the upstream status query failed with
// "connection reset by peer" right at expiry, and the order was expired
// without knowing whether it had been paid.
func TestExpireTimedOutOrdersKeepsOrderPendingWhenUpstreamQueryFails(t *testing.T) {
ctx := context.Background()
client := newPaymentOrderLifecycleTestClient(t)
user, err := client.User.Create().
SetEmail("expire-query-failed@example.com").
SetPasswordHash("hash").
SetUsername("expire-query-failed-user").
Save(ctx)
require.NoError(t, err)
createOrder := func(outTradeNo string, expiresAt time.Time) *dbent.PaymentOrder {
order, err := client.PaymentOrder.Create().
SetUserID(user.ID).
SetUserEmail(user.Email).
SetUserName(user.Username).
SetAmount(100).
SetPayAmount(100).
SetFeeRate(0).
SetRechargeCode("RC-" + outTradeNo).
SetOutTradeNo(outTradeNo).
SetPaymentType(payment.TypeAlipay).
SetPaymentTradeNo("").
SetOrderType(payment.OrderTypeBalance).
SetStatus(OrderStatusPending).
SetExpiresAt(expiresAt).
SetClientIP("127.0.0.1").
SetSrcHost("api.example.com").
Save(ctx)
require.NoError(t, err)
return order
}
justTimedOut := createOrder("sub2_expire_query_failed_recent", time.Now().Add(-time.Minute))
longTimedOut := createOrder("sub2_expire_query_failed_old", time.Now().Add(-paymentExpiryQueryRetryWindow-time.Minute))
registry := payment.NewRegistry()
provider := &paymentOrderLifecycleQueryProvider{queryErr: errors.New("read: connection reset by peer")}
registry.Register(provider)
svc := &PaymentService{entClient: client, registry: registry, providersLoaded: true}
expired, err := svc.ExpireTimedOutOrders(ctx)
require.NoError(t, err)
require.Equal(t, 1, expired)
require.Zero(t, provider.cancelCalls, "an order whose upstream status is unknown must not be closed upstream")
reloaded, err := client.PaymentOrder.Get(ctx, justTimedOut.ID)
require.NoError(t, err)
require.Equal(t, OrderStatusPending, reloaded.Status, "a failed upstream query must not expire the order")
reloaded, err = client.PaymentOrder.Get(ctx, longTimedOut.ID)
require.NoError(t, err)
require.Equal(t, OrderStatusExpired, reloaded.Status, "after the retry window the order expires anyway")
}
@@ -39,8 +39,6 @@ const (
const (
// defaultMaxPendingOrders and defaultOrderTimeoutMin are defined in
// payment_config_service.go alongside other payment configuration defaults.
paymentGraceMinutes = 5
defaultPageSize = 20
maxPageSize = 100
topUsersLimit = 10