From a3f4c1829d79141b68fe447449a4c5dc218236f7 Mon Sep 17 00:00:00 2001 From: Yared Yemane Date: Tue, 4 Aug 2026 15:09:24 +0300 Subject: [PATCH] Verify stale Chapa payments before expiring them. Recover SUCCESS/FAILED outcomes from Chapa when webhooks were missed, then expire any rows still pending. Co-authored-by: Cursor --- internal/domain/chapa.go | 14 ++++++ internal/domain/chapa_direct_test.go | 19 ++++++++ internal/services/chapa/service.go | 72 +++++++++++++++++++++++++--- internal/web_server/app.go | 9 ++-- 4 files changed, 104 insertions(+), 10 deletions(-) diff --git a/internal/domain/chapa.go b/internal/domain/chapa.go index b92290c3..6b84a547 100644 --- a/internal/domain/chapa.go +++ b/internal/domain/chapa.go @@ -168,6 +168,20 @@ func IsChapaPaymentMethod(method string) bool { return strings.HasPrefix(m, "CHAPA_DIRECT:") } +// ShouldAttemptChapaVerify reports whether a payment row should be checked against Chapa +// before expiry (hosted CHAPA, direct charges, and common wallet method labels). +func ShouldAttemptChapaVerify(method string) bool { + if IsChapaPaymentMethod(method) { + return true + } + switch strings.ToLower(strings.TrimSpace(method)) { + case "", "chapa", "telebirr", "cbebirr", "mpesa", "ebirr", "amole", "awashbirr", "enat_bank", "card": + return true + default: + return strings.HasPrefix(strings.ToUpper(strings.TrimSpace(method)), "CHAPA") + } +} + type InitiateChapaDirectChargeRequest struct { PlanID int64 `json:"plan_id" validate:"required"` Phone string `json:"phone" validate:"required"` diff --git a/internal/domain/chapa_direct_test.go b/internal/domain/chapa_direct_test.go index e42eafe8..e601dd82 100644 --- a/internal/domain/chapa_direct_test.go +++ b/internal/domain/chapa_direct_test.go @@ -21,6 +21,25 @@ func TestIsChapaPaymentMethod(t *testing.T) { } } +func TestShouldAttemptChapaVerify(t *testing.T) { + cases := []struct { + method string + want bool + }{ + {"CHAPA", true}, + {"CHAPA_DIRECT:telebirr", true}, + {"telebirr", true}, + {"", true}, + {"ARIFPAY", false}, + {"ADMIN_GRANT", false}, + } + for _, tc := range cases { + if got := ShouldAttemptChapaVerify(tc.method); got != tc.want { + t.Fatalf("method=%q got %v want %v", tc.method, got, tc.want) + } + } +} + func TestChapaDirectChargePaymentMethod(t *testing.T) { if got := ChapaDirectChargePaymentMethod(ChapaDirectChargeTelebirr); got != "CHAPA_DIRECT:telebirr" { t.Fatalf("got %q", got) diff --git a/internal/services/chapa/service.go b/internal/services/chapa/service.go index 07278bb5..18cb519b 100644 --- a/internal/services/chapa/service.go +++ b/internal/services/chapa/service.go @@ -424,17 +424,75 @@ func (s *Service) GetPaymentByID(ctx context.Context, id int64) (*domain.Payment return s.paymentStore.GetPaymentByID(ctx, id) } -// ExpireStalePendingPayments marks PENDING payments past expires_at as EXPIRED -// and cancels any linked PENDING subscriptions. -func (s *Service) ExpireStalePendingPayments(ctx context.Context) (int64, error) { - expired, err := s.paymentStore.ExpireStalePendingPayments(ctx) +// ExpireStalePendingPayments verifies stale Chapa PENDING payments with Chapa first, +// then marks any still-pending rows past expires_at as EXPIRED and cancels linked +// PENDING subscriptions. +func (s *Service) ExpireStalePendingPayments(ctx context.Context) (verifiedCount, expiredCount int64, err error) { + stale, err := s.paymentStore.GetExpiredPendingPayments(ctx) if err != nil { - return 0, err + return 0, 0, err + } + + if len(stale) > 0 && s.configured() == nil { + for i := range stale { + payment := &stale[i] + method := "" + if payment.PaymentMethod != nil { + method = *payment.PaymentMethod + } + if !domain.ShouldAttemptChapaVerify(method) { + continue + } + + txRef := strings.TrimSpace(payment.Nonce) + if txRef == "" && payment.SessionID != nil { + txRef = strings.TrimSpace(*payment.SessionID) + } + if txRef == "" { + continue + } + + recovered, verifyErr := s.verifyStalePendingBeforeExpire(ctx, txRef) + if verifyErr != nil { + continue + } + if recovered { + verifiedCount++ + } + } + } + + expiredCount, err = s.paymentStore.ExpireStalePendingPayments(ctx) + if err != nil { + return verifiedCount, 0, err } if _, cancelErr := s.subscriptionStore.CancelPendingSubscriptionsForTerminalPayments(ctx); cancelErr != nil { - return expired, cancelErr + return verifiedCount, expiredCount, cancelErr + } + return verifiedCount, expiredCount, nil +} + +// verifyStalePendingBeforeExpire calls Chapa verify and applies only terminal outcomes +// (success / failed / cancelled). Non-terminal Chapa statuses are left PENDING so the +// expire step can mark them EXPIRED. +func (s *Service) verifyStalePendingBeforeExpire(ctx context.Context, txRef string) (recovered bool, err error) { + verifyData, err := s.fetchVerifiedTransaction(ctx, txRef) + if err != nil { + return false, err + } + + status := mapChapaStatus(verifyData.Status) + switch status { + case string(domain.PaymentStatusSuccess), + string(domain.PaymentStatusFailed), + string(domain.PaymentStatusCancelled): + if applyErr := s.applyVerifiedTransaction(ctx, verifyData); applyErr != nil && !errors.Is(applyErr, ErrPaymentAlreadyPaid) { + return false, applyErr + } + return status == string(domain.PaymentStatusSuccess), nil + default: + return false, nil } - return expired, nil } func (s *Service) CancelPayment(ctx context.Context, paymentID int64, userID int64) error { diff --git a/internal/web_server/app.go b/internal/web_server/app.go index 073f0366..be884ea9 100644 --- a/internal/web_server/app.go +++ b/internal/web_server/app.go @@ -327,14 +327,17 @@ func (a *App) stopPaymentExpiryWorkerFunc() { } func (a *App) runPaymentExpiryOnce(ctx context.Context) { - expiredCount, err := a.chapaSvc.ExpireStalePendingPayments(ctx) + verifiedCount, expiredCount, err := a.chapaSvc.ExpireStalePendingPayments(ctx) if err != nil { a.logger.Error("payment expiry run failed", "error", err) return } - if expiredCount > 0 { - a.logger.Info("payment expiry run completed", "expired_count", expiredCount) + if verifiedCount > 0 || expiredCount > 0 { + a.logger.Info("payment expiry run completed", + "verified_count", verifiedCount, + "expired_count", expiredCount, + ) } }