74 lines
2.7 KiB
Go
74 lines
2.7 KiB
Go
package payment
|
|
|
|
import (
|
|
"context"
|
|
"hfb_sys/backend/internal/model"
|
|
"time"
|
|
)
|
|
|
|
func (r *Repository) applyChannelStatus(ctx context.Context, payment *model.PaymentOrder, status string, payTime string, raw map[string]string, source string) error {
|
|
switch status {
|
|
case "paid":
|
|
paidAt := parseChannelTime(payTime)
|
|
if paidAt == nil {
|
|
now := time.Now()
|
|
paidAt = &now
|
|
}
|
|
return r.confirmPaid(ctx, payment, status, *paidAt, raw, source)
|
|
case "closed":
|
|
return r.updateChannelStatus(ctx, payment.ID, "closed", raw, source)
|
|
case "failed":
|
|
return r.updateChannelStatus(ctx, payment.ID, "failed", raw, source)
|
|
default:
|
|
return r.updateChannelStatus(ctx, payment.ID, "paying", raw, source)
|
|
}
|
|
}
|
|
func (r *Repository) updateChannelStatus(ctx context.Context, paymentID uint64, status string, raw map[string]string, source string) error {
|
|
updates := map[string]any{
|
|
"status": status,
|
|
"raw_response": jsonMap(withRawSource(raw, source)),
|
|
}
|
|
if source == channelSourceNotify {
|
|
updates["notified_at"] = time.Now()
|
|
}
|
|
return r.db.WithContext(ctx).Model(&model.PaymentOrder{}).Where("id = ?", paymentID).Updates(updates).Error
|
|
}
|
|
func (r *Repository) confirmPaid(ctx context.Context, payment *model.PaymentOrder, status string, paidAt time.Time, raw map[string]string, source string) error {
|
|
if payment.Status != "paid" {
|
|
if payment.OrderID == 0 {
|
|
if r.walletRepo == nil {
|
|
return ErrDependencyUnavailable
|
|
}
|
|
if err := r.walletRepo.ConfirmRechargeFromChannel(ctx, payment.UserID, firstNonEmpty(payment.ProviderOrderID, payment.PaymentNo), payment.AmountCent); err != nil {
|
|
return err
|
|
}
|
|
} else {
|
|
if r.orderRepo == nil {
|
|
return ErrDependencyUnavailable
|
|
}
|
|
if err := r.orderRepo.ConfirmPaidFromChannel(ctx, payment.OrderID, firstNonEmpty(payment.ProviderOrderID, payment.PaymentNo)); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
updates := map[string]any{
|
|
"status": "paid",
|
|
"provider_order_id": firstNonEmpty(raw["provider_order_id"], raw["leshua_order_id"], raw["pay_order_no"], raw["trade_no"], payment.ProviderOrderID),
|
|
"raw_response": jsonMap(withRawSource(raw, source)),
|
|
"paid_at": paidAt,
|
|
}
|
|
if source == channelSourceNotify {
|
|
updates["notified_at"] = time.Now()
|
|
}
|
|
return r.db.WithContext(ctx).Model(&model.PaymentOrder{}).Where("id = ?", payment.ID).Updates(updates).Error
|
|
}
|
|
func (r *Repository) markPaymentFailed(ctx context.Context, paymentID uint64, raw map[string]string, message string) error {
|
|
if raw == nil {
|
|
raw = map[string]string{"error": message}
|
|
}
|
|
return r.db.WithContext(ctx).Model(&model.PaymentOrder{}).Where("id = ?", paymentID).Updates(map[string]any{
|
|
"status": "failed",
|
|
"raw_response": jsonMap(raw),
|
|
}).Error
|
|
}
|