diff --git a/backend/internal/integrations/payment/lakala/client.go b/backend/internal/integrations/payment/lakala/client.go index 8ef3dfd1..3940cc59 100644 --- a/backend/internal/integrations/payment/lakala/client.go +++ b/backend/internal/integrations/payment/lakala/client.go @@ -100,6 +100,7 @@ type QueryPaymentResponse struct { PayWay string PayTime string Raw map[string]string + RawRequest map[string]string } type CreateRefundRequest struct { @@ -250,6 +251,7 @@ func (c *Client) QueryPayment(ctx context.Context, thirdOrderID, providerOrderID PayWay: firstNonEmpty(raw["pay_mode"], raw["account_type"]), PayTime: firstNonEmpty(raw["pay_time"], raw["trade_time"], raw["finish_time"]), Raw: raw, + RawRequest: stringifyMap(reqData), }, nil } diff --git a/backend/internal/integrations/payment/leshua/client.go b/backend/internal/integrations/payment/leshua/client.go index 55e49c94..1301a743 100644 --- a/backend/internal/integrations/payment/leshua/client.go +++ b/backend/internal/integrations/payment/leshua/client.go @@ -80,6 +80,7 @@ type QueryPaymentResponse struct { PayWay string PayTime string Raw map[string]string + RawRequest map[string]string } type CreateRefundRequest struct { @@ -236,6 +237,7 @@ func (c *Client) QueryPayment(ctx context.Context, thirdOrderID, providerOrderID PayWay: raw["pay_way"], PayTime: raw["pay_time"], Raw: raw, + RawRequest: params, }, nil } diff --git a/backend/internal/integrations/payment/saobei/client.go b/backend/internal/integrations/payment/saobei/client.go index cf115ac4..d102ed83 100644 --- a/backend/internal/integrations/payment/saobei/client.go +++ b/backend/internal/integrations/payment/saobei/client.go @@ -91,6 +91,7 @@ type QueryPaymentResponse struct { Amount string PayTime string Raw map[string]string + RawRequest map[string]string } type CreateRefundRequest struct { @@ -237,6 +238,7 @@ func (c *Client) QueryPayment(ctx context.Context, req QueryPaymentRequest) (*Qu Amount: raw["total_fee"], PayTime: firstNonEmpty(raw["end_time"], raw["terminal_time"]), Raw: raw, + RawRequest: copyMap(params), }, nil } diff --git a/backend/internal/integrations/payment/shuncheng/client.go b/backend/internal/integrations/payment/shuncheng/client.go index 0abf54fd..62be34be 100644 --- a/backend/internal/integrations/payment/shuncheng/client.go +++ b/backend/internal/integrations/payment/shuncheng/client.go @@ -99,6 +99,7 @@ type QueryPaymentResponse struct { PayWay string PayTime string Raw map[string]string + RawRequest map[string]string } type CreateRefundRequest struct { @@ -266,6 +267,7 @@ func (c *Client) QueryPayment(ctx context.Context, thirdOrderID, providerOrderID PayWay: raw["pay_way"], PayTime: firstNonEmpty(raw["pay_time"], raw["channel_datetime"]), Raw: raw, + RawRequest: copyStringMap(params), }, nil } diff --git a/backend/internal/model/payment_config_test_order.go b/backend/internal/model/payment_config_test_order.go new file mode 100644 index 00000000..931e0963 --- /dev/null +++ b/backend/internal/model/payment_config_test_order.go @@ -0,0 +1,50 @@ +package model + +import ( + "time" + + "gorm.io/datatypes" +) + +// PaymentConfigTestOrder 支付配置真实通道测试单,与业务支付流水完全隔离。 +type PaymentConfigTestOrder struct { + ID uint64 `gorm:"primaryKey" json:"id"` + TenantID uint64 `gorm:"not null;default:0;index:idx_payment_config_test_tenant_created" json:"tenant_id"` + PaymentConfigID uint64 `gorm:"not null;index:idx_payment_config_test_config" json:"payment_config_id"` + ConfigName string `gorm:"size:128;not null" json:"config_name"` + Provider string `gorm:"size:32;not null" json:"provider"` + MerchantID string `gorm:"size:128;not null" json:"merchant_id"` + PayWay string `gorm:"size:16;not null;default:''" json:"pay_way"` + Environment string `gorm:"size:16;not null;default:''" json:"environment"` + ConfigStatus string `gorm:"size:32;not null;default:''" json:"config_status"` + TestNo string `gorm:"size:64;not null;uniqueIndex" json:"test_no"` + ThirdOrderID string `gorm:"size:64;not null;uniqueIndex" json:"third_order_id"` + NotifyToken string `gorm:"size:64;not null;uniqueIndex" json:"-"` + ProviderOrderID string `gorm:"size:64;not null;default:''" json:"provider_order_id"` + AmountCent int64 `gorm:"not null;default:0" json:"amount_cent"` + Status string `gorm:"size:32;not null;default:'created';index:idx_payment_config_test_status" json:"status"` + TDCode string `gorm:"size:512;not null;default:''" json:"td_code"` + JSPayURL string `gorm:"column:jspay_url;size:512;not null;default:''" json:"jspay_url"` + JSPayInfo string `gorm:"column:jspay_info;type:text" json:"jspay_info"` + ErrorMessage string `gorm:"size:512;not null;default:''" json:"error_message"` + RawRequest datatypes.JSON `json:"raw_request"` + RawResponse datatypes.JSON `json:"raw_response"` + CreateRequest datatypes.JSON `json:"create_request"` + CreateResponse datatypes.JSON `json:"create_response"` + QueryRequest datatypes.JSON `json:"query_request"` + QueryResponse datatypes.JSON `json:"query_response"` + NotifyRequest datatypes.JSON `json:"notify_request"` + NotifyResult datatypes.JSON `json:"notify_result"` + NotifyAck string `gorm:"size:512;not null;default:''" json:"notify_ack"` + QueryCount int `gorm:"not null;default:0" json:"query_count"` + LastQueriedAt *time.Time `json:"last_queried_at,omitempty"` + PaidAt *time.Time `json:"paid_at,omitempty"` + NotifiedAt *time.Time `json:"notified_at,omitempty"` + CreatedBy *uint64 `json:"created_by"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` +} + +func (PaymentConfigTestOrder) TableName() string { + return "payment_config_test_orders" +} diff --git a/backend/internal/modules/payment/channel_adapter.go b/backend/internal/modules/payment/channel_adapter.go index b2dd2802..f4907c55 100644 --- a/backend/internal/modules/payment/channel_adapter.go +++ b/backend/internal/modules/payment/channel_adapter.go @@ -57,6 +57,7 @@ type channelQueryPaymentResponse struct { PayWay string PayTime string Raw map[string]string + RawRequest map[string]string } type channelQueryPaymentRequest struct { @@ -167,6 +168,7 @@ func (c leshuaChannel) QueryPayment(ctx context.Context, req channelQueryPayment PayWay: resp.PayWay, PayTime: resp.PayTime, Raw: resp.Raw, + RawRequest: resp.RawRequest, }, nil } @@ -287,6 +289,7 @@ func (c lakalaChannel) QueryPayment(ctx context.Context, req channelQueryPayment PayWay: resp.PayWay, PayTime: resp.PayTime, Raw: resp.Raw, + RawRequest: resp.RawRequest, }, nil } @@ -415,6 +418,7 @@ func (c shunchengChannel) QueryPayment(ctx context.Context, req channelQueryPaym PayWay: resp.PayWay, PayTime: resp.PayTime, Raw: resp.Raw, + RawRequest: resp.RawRequest, }, nil } @@ -535,6 +539,7 @@ func (c saobeiChannel) QueryPayment(ctx context.Context, req channelQueryPayment Amount: resp.Amount, PayTime: resp.PayTime, Raw: resp.Raw, + RawRequest: resp.RawRequest, }, nil } @@ -599,9 +604,18 @@ func (c saobeiChannel) VerifyNotify(params map[string]string, rawPayload string, } func buildChannelClient(dto *paymentconfig.ConfigDTO) (channelClient, error) { + return buildChannelClientWithBreaker(dto, true) +} + +// buildConfigTestChannelClient 为后台支付配置测试构建独立通道客户端,不进入生产支付熔断器。 +func buildConfigTestChannelClient(dto *paymentconfig.ConfigDTO) (channelClient, error) { + return buildChannelClientWithBreaker(dto, false) +} + +func buildChannelClientWithBreaker(dto *paymentconfig.ConfigDTO, useBreaker bool) (channelClient, error) { switch strings.ToLower(strings.TrimSpace(dto.Provider)) { case "leshua": - return withChannelBreaker("leshua", newLeshuaChannel(leshua.Config{ + return channelClientWithOptionalBreaker(useBreaker, "leshua", newLeshuaChannel(leshua.Config{ GatewayURL: dto.GatewayURL, MerchantID: dto.MerchantID, SignKey: dto.SignKey, @@ -613,7 +627,7 @@ func buildChannelClient(dto *paymentconfig.ConfigDTO) (channelClient, error) { SignType: firstNonEmpty(dto.SignType, "MD5"), })), nil case "lakala": - return withChannelBreaker("lakala", newLakalaChannel(lakala.Config{ + return channelClientWithOptionalBreaker(useBreaker, "lakala", newLakalaChannel(lakala.Config{ GatewayURL: dto.GatewayURL, AppID: extraString(dto.ExtraConfig, "app_id"), SerialNo: extraString(dto.ExtraConfig, "serial_no"), @@ -630,7 +644,7 @@ func buildChannelClient(dto *paymentconfig.ConfigDTO) (channelClient, error) { OrderExpireMinutes: extraInt(dto.ExtraConfig, "order_expire_minutes"), })), nil case "shuncheng": - return withChannelBreaker("shuncheng", newShunchengChannel(shuncheng.Config{ + return channelClientWithOptionalBreaker(useBreaker, "shuncheng", newShunchengChannel(shuncheng.Config{ GatewayURL: dto.GatewayURL, MerchantID: dto.MerchantID, SecretID: extraString(dto.ExtraConfig, "secret_id"), @@ -646,7 +660,7 @@ func buildChannelClient(dto *paymentconfig.ConfigDTO) (channelClient, error) { TokenMargin: time.Duration(extraInt(dto.ExtraConfig, "token_refresh_margin_seconds")) * time.Second, })), nil case "saobei": - return withChannelBreaker("saobei", newSaobeiChannel(saobei.Config{ + return channelClientWithOptionalBreaker(useBreaker, "saobei", newSaobeiChannel(saobei.Config{ GatewayURL: dto.GatewayURL, MerchantID: dto.MerchantID, TerminalID: extraString(dto.ExtraConfig, "terminal_id"), @@ -734,3 +748,10 @@ func extraInt(config map[string]any, key string) int { n, _ := strconv.Atoi(value) return n } + +func channelClientWithOptionalBreaker(useBreaker bool, name string, next channelClient) channelClient { + if !useBreaker { + return next + } + return withChannelBreaker(name, next) +} diff --git a/backend/internal/modules/payment/config_test_dto.go b/backend/internal/modules/payment/config_test_dto.go new file mode 100644 index 00000000..334696b9 --- /dev/null +++ b/backend/internal/modules/payment/config_test_dto.go @@ -0,0 +1,110 @@ +package payment + +import ( + "errors" + "time" + + "hfb_sys/backend/internal/model" + + "gorm.io/datatypes" +) + +var ErrConfigTestPaymentInvalid = errors.New("invalid config test payment") + +type StartConfigTestPaymentRequest struct { + AmountCent int64 `json:"amount_cent" binding:"required,min=1"` +} + +type ConfigTestPaymentQuery struct { + PaymentConfigID uint64 + Provider string + PayWay string + Status string + TestNo string + Page int + PageSize int +} + +type ConfigTestPaymentDTO struct { + ID uint64 `json:"id"` + TenantID uint64 `json:"tenant_id"` + PaymentConfigID uint64 `json:"payment_config_id"` + ConfigName string `json:"config_name"` + Provider string `json:"provider"` + MerchantID string `json:"merchant_id"` + PayWay string `json:"pay_way"` + Environment string `json:"environment"` + ConfigStatus string `json:"config_status"` + TestNo string `json:"test_no"` + ThirdOrderID string `json:"third_order_id"` + ProviderOrderID string `json:"provider_order_id"` + AmountCent int64 `json:"amount_cent"` + Status string `json:"status"` + TDCode string `json:"td_code,omitempty"` + JSPayURL string `json:"jspay_url,omitempty"` + JSPayInfo string `json:"jspay_info,omitempty"` + ErrorMessage string `json:"error_message"` + RawRequest datatypes.JSON `json:"raw_request,omitempty"` + RawResponse datatypes.JSON `json:"raw_response,omitempty"` + CreateRequest datatypes.JSON `json:"create_request,omitempty"` + CreateResponse datatypes.JSON `json:"create_response,omitempty"` + QueryRequest datatypes.JSON `json:"query_request,omitempty"` + QueryResponse datatypes.JSON `json:"query_response,omitempty"` + NotifyRequest datatypes.JSON `json:"notify_request,omitempty"` + NotifyResult datatypes.JSON `json:"notify_result,omitempty"` + NotifyAck string `json:"notify_ack,omitempty"` + QueryCount int `json:"query_count"` + LastQueriedAt *time.Time `json:"last_queried_at,omitempty"` + PaidAt *time.Time `json:"paid_at,omitempty"` + NotifiedAt *time.Time `json:"notified_at,omitempty"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` +} + +type ConfigTestPaymentListResponse struct { + Items []ConfigTestPaymentDTO `json:"items"` + Total int64 `json:"total"` + Page int `json:"page"` + PageSize int `json:"page_size"` +} + +func toConfigTestPaymentDTO(row model.PaymentConfigTestOrder, includeRaw bool) ConfigTestPaymentDTO { + dto := ConfigTestPaymentDTO{ + ID: row.ID, + TenantID: row.TenantID, + PaymentConfigID: row.PaymentConfigID, + ConfigName: row.ConfigName, + Provider: row.Provider, + MerchantID: row.MerchantID, + PayWay: row.PayWay, + Environment: row.Environment, + ConfigStatus: row.ConfigStatus, + TestNo: row.TestNo, + ThirdOrderID: row.ThirdOrderID, + ProviderOrderID: row.ProviderOrderID, + AmountCent: row.AmountCent, + Status: row.Status, + TDCode: row.TDCode, + JSPayURL: row.JSPayURL, + JSPayInfo: row.JSPayInfo, + ErrorMessage: row.ErrorMessage, + QueryCount: row.QueryCount, + LastQueriedAt: row.LastQueriedAt, + PaidAt: row.PaidAt, + NotifiedAt: row.NotifiedAt, + CreatedAt: row.CreatedAt, + UpdatedAt: row.UpdatedAt, + } + if includeRaw { + dto.RawRequest = row.RawRequest + dto.RawResponse = row.RawResponse + dto.CreateRequest = row.CreateRequest + dto.CreateResponse = row.CreateResponse + dto.QueryRequest = row.QueryRequest + dto.QueryResponse = row.QueryResponse + dto.NotifyRequest = row.NotifyRequest + dto.NotifyResult = row.NotifyResult + dto.NotifyAck = row.NotifyAck + } + return dto +} diff --git a/backend/internal/modules/payment/config_test_handler.go b/backend/internal/modules/payment/config_test_handler.go new file mode 100644 index 00000000..1aca8aaa --- /dev/null +++ b/backend/internal/modules/payment/config_test_handler.go @@ -0,0 +1,186 @@ +package payment + +import ( + "errors" + "io" + "net/http" + "strconv" + "strings" + + "hfb_sys/backend/internal/integrations/payment/lakala" + "hfb_sys/backend/internal/integrations/payment/leshua" + "hfb_sys/backend/internal/integrations/payment/saobei" + "hfb_sys/backend/internal/integrations/payment/shuncheng" + "hfb_sys/backend/internal/middleware" + "hfb_sys/backend/internal/modules/paymentconfig" + "hfb_sys/backend/pkg/response" + + "github.com/gin-gonic/gin" + "go.uber.org/zap" +) + +func (h *Handler) StartConfigTestPayment(c *gin.Context) { + configID, ok := parseID(c) + if !ok { + return + } + var req StartConfigTestPaymentRequest + if err := c.ShouldBindJSON(&req); err != nil { + response.BadRequest(c, "测试金额必须大于0") + return + } + adminID, _ := configTestAdminID(c) + item, err := h.service.StartConfigTestPayment(c.Request.Context(), configID, req, adminID, c.ClientIP()) + if err != nil { + writeConfigTestError(c, err) + return + } + response.OK(c, item) +} + +func (h *Handler) AdminListConfigTestPayments(c *gin.Context) { + query := ConfigTestPaymentQuery{ + Provider: strings.TrimSpace(c.Query("provider")), + PayWay: strings.TrimSpace(c.Query("pay_way")), + Status: strings.TrimSpace(c.Query("status")), + TestNo: strings.TrimSpace(c.Query("test_no")), + } + if raw := strings.TrimSpace(c.Query("payment_config_id")); raw != "" { + value, err := strconv.ParseUint(raw, 10, 64) + if err != nil || value == 0 { + response.BadRequest(c, "支付配置ID不正确") + return + } + query.PaymentConfigID = value + } + query.Page, _ = strconv.Atoi(c.DefaultQuery("page", "1")) + query.PageSize, _ = strconv.Atoi(c.DefaultQuery("page_size", "20")) + result, err := h.service.ListConfigTestPayments(c.Request.Context(), query) + if err != nil { + writeConfigTestError(c, err) + return + } + response.OK(c, result) +} + +func (h *Handler) AdminGetConfigTestPayment(c *gin.Context) { + id, ok := parseID(c) + if !ok { + return + } + item, err := h.service.GetConfigTestPayment(c.Request.Context(), id) + if err != nil { + writeConfigTestError(c, err) + return + } + response.OK(c, item) +} + +func (h *Handler) AdminRefreshConfigTestPayment(c *gin.Context) { + id, ok := parseID(c) + if !ok { + return + } + item, err := h.service.RefreshConfigTestPayment(c.Request.Context(), id) + if err != nil { + writeConfigTestError(c, err) + return + } + response.OK(c, item) +} + +// ConfigTestNotify 是独立测试单回调,不读取或更新 payment_orders / rental_orders。 +func (h *Handler) ConfigTestNotify(c *gin.Context) { + provider := strings.ToLower(strings.TrimSpace(c.Param("provider"))) + notifyToken := strings.TrimSpace(c.Param("token")) + body, err := io.ReadAll(io.LimitReader(c.Request.Body, 1<<20)) + if err != nil { + h.recordConfigTestNotifyAck(c, provider, notifyToken, false) + writeConfigTestNotifyFailure(c, provider) + return + } + var params map[string]string + switch provider { + case "leshua": + params, err = leshua.ParsePayload(body) + case "lakala": + params, err = lakala.ParsePayload(body) + case "shuncheng": + params, err = shuncheng.ParsePayload(body) + case "saobei": + params, err = saobei.ParsePayload(body) + default: + err = ErrPaymentNotFound + } + if err != nil { + h.recordConfigTestNotifyAck(c, provider, notifyToken, false) + writeConfigTestNotifyFailure(c, provider) + return + } + rawPayload := string(body) + contentType := c.GetHeader("Content-Type") + authorization := c.GetHeader("Authorization") + result, err := h.service.HandleConfigTestNotify(c.Request.Context(), provider, notifyToken, params, rawPayload, contentType, authorization) + if err != nil || result == nil || !result.OK { + h.log().Warn("支付配置测试回调处理失败", notifyLogFields(c.Request.Context(), provider, params, contentType, len(body), zap.Error(err))...) + h.recordConfigTestNotifyAck(c, provider, notifyToken, false) + writeConfigTestNotifyFailure(c, provider) + return + } + h.recordConfigTestNotifyAck(c, provider, notifyToken, true) + h.log().Info("支付配置测试回调处理完成", notifyLogFields(c.Request.Context(), provider, params, contentType, len(body))...) + switch provider { + case "lakala": + c.JSON(http.StatusOK, gin.H{"code": "SUCCESS", "message": "执行成功"}) + case "saobei": + c.JSON(http.StatusOK, gin.H{"return_code": "01", "return_msg": "success"}) + default: + c.String(http.StatusOK, result.Message) + } +} + +func (h *Handler) recordConfigTestNotifyAck(c *gin.Context, provider string, notifyToken string, success bool) { + ack := configTestNotifyAck(provider, success) + if err := h.service.RecordConfigTestNotifyAck(c.Request.Context(), provider, notifyToken, ack); err != nil { + h.log().Warn("支付配置测试回调应答保存失败", + notifyLogFields(c.Request.Context(), provider, nil, "", 0, zap.Error(err))...) + } +} + +func writeConfigTestNotifyFailure(c *gin.Context, provider string) { + switch provider { + case "lakala": + c.JSON(http.StatusOK, gin.H{"code": "FAIL", "message": "失败"}) + case "saobei": + c.JSON(http.StatusOK, gin.H{"return_code": "02", "return_msg": "失败"}) + default: + c.String(http.StatusOK, "FAIL") + } +} + +func writeConfigTestError(c *gin.Context, err error) { + response.RecordError(c, err) + switch { + case errors.Is(err, ErrConfigTestPaymentInvalid): + response.BadRequest(c, "测试金额必须大于0") + case errors.Is(err, ErrDependencyUnavailable): + response.ServiceUnavailable(c, "数据库未连接") + case errors.Is(err, ErrPaymentNotFound), errors.Is(err, paymentconfig.ErrConfigNotFound): + response.NotFound(c, "测试支付记录或支付配置不存在") + case errors.Is(err, ErrPaymentVerifyFailed): + response.Error(c, http.StatusForbidden, "payment_verify_failed", "支付回调验签失败") + case errors.Is(err, ErrPaymentUnavailable): + response.Error(c, http.StatusBadGateway, "payment_unavailable", "支付渠道暂不可用") + default: + response.Error(c, http.StatusBadGateway, "config_test_payment_failed", "测试支付处理失败,请查看测试记录") + } +} + +func configTestAdminID(c *gin.Context) (uint64, bool) { + value, ok := c.Get(middleware.ContextAdminID) + if !ok { + return 0, false + } + id, ok := value.(uint64) + return id, ok && id > 0 +} diff --git a/backend/internal/modules/payment/config_test_redact.go b/backend/internal/modules/payment/config_test_redact.go new file mode 100644 index 00000000..70dd5766 --- /dev/null +++ b/backend/internal/modules/payment/config_test_redact.go @@ -0,0 +1,89 @@ +package payment + +import ( + "strconv" + "strings" + + "hfb_sys/backend/internal/model" +) + +// sanitizeConfigTestPayload 对测试报文中的签名、用户标识和凭证类字段打码。 +func sanitizeConfigTestPayload(raw map[string]string) map[string]string { + if raw == nil { + return nil + } + out := make(map[string]string, len(raw)) + for key, value := range raw { + if configTestSensitiveKey(key) { + out[key] = "***" + continue + } + out[key] = value + } + return out +} + +func configTestSensitiveKey(key string) bool { + lower := strings.ToLower(strings.TrimSpace(key)) + if lower == "sign" || strings.HasSuffix(lower, "_sign") || strings.Contains(lower, "signature") { + return true + } + for _, token := range []string{"openid", "auth_code", "access_token", "secret", "private_key", "cert", "token"} { + if strings.Contains(lower, token) { + return true + } + } + return false +} + +func configTestQueryRequest(row model.PaymentConfigTestOrder) map[string]string { + return map[string]string{ + "provider": row.Provider, + "merchant_id": row.MerchantID, + "pay_way": row.PayWay, + "third_order_id": row.ThirdOrderID, + "provider_order_id": row.ProviderOrderID, + } +} + +func configTestNotifyRequest(params map[string]string, contentType string) map[string]string { + out := sanitizeConfigTestPayload(params) + if out == nil { + out = map[string]string{} + } + out["_content_type"] = contentType + return out +} + +func configTestNotifyResult(verified bool, status string, row model.PaymentConfigTestOrder, message string) map[string]string { + out := map[string]string{ + "verified": strconv.FormatBool(verified), + "status": status, + "amount_cent": strconv.FormatInt(row.AmountCent, 10), + "provider_order_id": row.ProviderOrderID, + } + if message != "" { + out["message"] = message + } + return out +} + +func configTestNotifyAck(provider string, success bool) string { + switch provider { + case "lakala": + if success { + return `{"code":"SUCCESS","message":"执行成功"}` + } + return `{"code":"FAIL","message":"失败"}` + case "saobei": + if success { + return `{"return_code":"01","return_msg":"success"}` + } + return `{"return_code":"02","return_msg":"失败"}` + default: + if success { + return "000000" + } + return "FAIL" + } +} diff --git a/backend/internal/modules/payment/config_test_repository.go b/backend/internal/modules/payment/config_test_repository.go new file mode 100644 index 00000000..c76380c2 --- /dev/null +++ b/backend/internal/modules/payment/config_test_repository.go @@ -0,0 +1,490 @@ +package payment + +import ( + "context" + "crypto/rand" + "encoding/hex" + "fmt" + "net/url" + "strings" + "time" + + "hfb_sys/backend/internal/integrations/payment/saobei" + "hfb_sys/backend/internal/model" + "hfb_sys/backend/internal/tenancy" + + "gorm.io/gorm" + "gorm.io/gorm/clause" +) + +const configTestSource = "config_test" + +// StartConfigTestPayment 使用指定支付配置创建一笔真实渠道测试单。 +// 测试单与业务订单、钱包、结算完全隔离,只用于验证商户配置和二维码支付能力。 +func (r *Repository) StartConfigTestPayment(ctx context.Context, configID uint64, req StartConfigTestPaymentRequest, adminID uint64, clientIP string) (*ConfigTestPaymentDTO, error) { + if r == nil || r.db == nil || r.configRepo == nil { + return nil, ErrDependencyUnavailable + } + if configID == 0 || req.AmountCent <= 0 { + return nil, ErrConfigTestPaymentInvalid + } + dto, err := r.configRepo.FindRuntimeByID(ctx, configID, true) + if err != nil { + return nil, err + } + runtimeConfig := runtimeConfigFromDTO(dto) + channel, err := buildConfigTestChannelClient(dto) + if err != nil { + return nil, ErrPaymentUnavailable + } + runtimeConfig.Channel = channel + + testNo, err := newConfigTestNo("PCT") + if err != nil { + return nil, err + } + notifyToken, err := randomToken(16) + if err != nil { + return nil, err + } + tenantID := tenancy.IDFromContext(ctx) + if tenantID == 0 { + tenantID = dto.OwnerTenantID + } + row := model.PaymentConfigTestOrder{ + TenantID: tenantID, + PaymentConfigID: dto.ID, + ConfigName: dto.Name, + Provider: firstNonEmpty(dto.Provider, "mock"), + MerchantID: dto.MerchantID, + PayWay: normalizePayWay(dto.PayWay), + Environment: dto.Environment, + ConfigStatus: dto.Status, + TestNo: testNo, + ThirdOrderID: testNo, + NotifyToken: notifyToken, + AmountCent: req.AmountCent, + Status: "created", + CreatedBy: &adminID, + } + if err := r.db.WithContext(ctx).Create(&row).Error; err != nil { + return nil, err + } + + if runtimeConfig.isMockMode() { + now := time.Now() + mockResponse := map[string]string{"_source": channelSourceMock, "mock": "true"} + if err := r.db.WithContext(ctx).Model(&model.PaymentConfigTestOrder{}).Where("id = ?", row.ID).Updates(map[string]any{ + "status": "paid", + "paid_at": now, + "raw_response": jsonMap(mockResponse), + "create_response": jsonMap(mockResponse), + }).Error; err != nil { + return nil, err + } + return r.GetConfigTestPayment(ctx, row.ID) + } + if runtimeConfig.Channel == nil { + _ = r.failConfigTestPayment(ctx, row.ID, "支付渠道不可用", nil, nil) + return r.GetConfigTestPayment(ctx, row.ID) + } + + notifyURL := buildConfigTestNotifyURL(dto.NotifyURL, dto.Provider, notifyToken) + resp, err := runtimeConfig.Channel.CreatePayment(ctx, channelCreatePaymentRequest{ + ThirdOrderID: row.ThirdOrderID, + AmountCent: row.AmountCent, + PayWay: row.PayWay, + JSPayFlag: firstNonEmpty(dto.JSPayFlag, "2"), + NotifyURL: notifyURL, + JumpURL: dto.JumpURL, + ClientIP: clientIP, + Body: "支付配置测试 " + dto.Name, + Attach: "payment_config_test:" + row.TestNo, + }) + if err != nil { + _ = r.failConfigTestPayment(ctx, row.ID, err.Error(), nil, nil) + return r.GetConfigTestPayment(ctx, row.ID) + } + if resp == nil { + _ = r.failConfigTestPayment(ctx, row.ID, "支付渠道未返回结果", nil, nil) + return r.GetConfigTestPayment(ctx, row.ID) + } + if !resp.OK { + message := firstNonEmpty(resp.ErrorMessage, "支付渠道拒绝下单") + _ = r.failConfigTestPayment(ctx, row.ID, message, resp.Raw, resp.RawRequest) + return r.GetConfigTestPayment(ctx, row.ID) + } + + status := configTestChannelStatus(resp.Status) + updates := map[string]any{ + "status": status, + "provider_order_id": resp.ProviderOrderID, + "pay_way": firstNonEmpty(resp.PayWay, row.PayWay), + "td_code": resp.TDCode, + "jspay_url": resp.JSPayURL, + "jspay_info": resp.JSPayInfo, + "raw_request": jsonMap(sanitizeConfigTestPayload(resp.RawRequest)), + "raw_response": jsonMap(withRawSource(sanitizeConfigTestPayload(resp.Raw), channelSourceCreate)), + "create_request": jsonMap(sanitizeConfigTestPayload(resp.RawRequest)), + "create_response": jsonMap(withRawSource(sanitizeConfigTestPayload(resp.Raw), channelSourceCreate)), + "error_message": "", + } + if status == "paid" { + paidAt := parseChannelTime(resp.PayTime) + if paidAt == nil { + now := time.Now() + paidAt = &now + } + updates["paid_at"] = *paidAt + } + if err := r.db.WithContext(ctx).Model(&model.PaymentConfigTestOrder{}).Where("id = ?", row.ID).Updates(updates).Error; err != nil { + return nil, err + } + return r.GetConfigTestPayment(ctx, row.ID) +} + +// RefreshConfigTestPayment 主动向渠道查单并同步测试单状态。 +func (r *Repository) RefreshConfigTestPayment(ctx context.Context, id uint64) (*ConfigTestPaymentDTO, error) { + row, err := r.findConfigTestPayment(ctx, id, true) + if err != nil { + return nil, err + } + if configTestTerminal(row.Status) { + dto := toConfigTestPaymentDTO(*row, true) + return &dto, nil + } + if r.configRepo == nil { + return nil, ErrDependencyUnavailable + } + configCtx := scopedTenantContext(ctx, row.TenantID) + dto, err := r.configRepo.FindRuntimeByID(configCtx, row.PaymentConfigID, true) + if err != nil { + return nil, err + } + runtimeConfig := runtimeConfigFromDTO(dto) + channel, err := buildConfigTestChannelClient(dto) + if err != nil { + return nil, ErrPaymentUnavailable + } + runtimeConfig.Channel = channel + now := time.Now() + if runtimeConfig.isMockMode() { + if err := r.db.WithContext(ctx).Model(&model.PaymentConfigTestOrder{}).Where("id = ?", row.ID).Updates(map[string]any{ + "status": "paid", + "paid_at": now, + "last_queried_at": now, + "query_count": gorm.Expr("query_count + 1"), + "error_message": "", + }).Error; err != nil { + return nil, err + } + return r.GetConfigTestPayment(ctx, id) + } + if runtimeConfig.Channel == nil { + return nil, ErrPaymentUnavailable + } + queryRequest := sanitizeConfigTestPayload(configTestQueryRequest(*row)) + resp, err := runtimeConfig.Channel.QueryPayment(ctx, channelQueryPaymentRequest{ + ThirdOrderID: row.ThirdOrderID, + TraceTime: paymentTraceTime(row.RawRequest), + ProviderOrderID: row.ProviderOrderID, + }) + if err != nil { + _ = r.db.WithContext(ctx).Model(&model.PaymentConfigTestOrder{}).Where("id = ?", row.ID).Updates(map[string]any{ + "last_queried_at": now, + "query_count": gorm.Expr("query_count + 1"), + "query_request": jsonMap(queryRequest), + "error_message": truncateText(err.Error(), 500), + }).Error + return nil, err + } + if resp == nil { + return nil, ErrPaymentUnavailable + } + if resp.RawRequest != nil { + queryRequest = sanitizeConfigTestPayload(resp.RawRequest) + } + if !resp.OK { + _ = r.db.WithContext(ctx).Model(&model.PaymentConfigTestOrder{}).Where("id = ?", row.ID).Updates(map[string]any{ + "last_queried_at": now, + "query_count": gorm.Expr("query_count + 1"), + "query_request": jsonMap(queryRequest), + "query_response": jsonMap(withRawSource(sanitizeConfigTestPayload(resp.Raw), channelSourceQuery)), + "error_message": configTestQueryErrorMessage(resp.Raw, resp.ErrorMessage), + }).Error + return r.GetConfigTestPayment(ctx, id) + } + status := configTestChannelStatus(resp.Status) + updates := map[string]any{ + "status": status, + "last_queried_at": now, + "query_count": gorm.Expr("query_count + 1"), + "query_request": jsonMap(queryRequest), + "query_response": jsonMap(withRawSource(sanitizeConfigTestPayload(resp.Raw), channelSourceQuery)), + "error_message": "", + } + if resp.ProviderOrderID != "" { + updates["provider_order_id"] = resp.ProviderOrderID + } + if status == "paid" { + paidAt := parseChannelTime(resp.PayTime) + if paidAt == nil { + paidAt = &now + } + updates["paid_at"] = *paidAt + } + if err := r.db.WithContext(ctx).Model(&model.PaymentConfigTestOrder{}).Where("id = ?", row.ID).Updates(updates).Error; err != nil { + return nil, err + } + return r.GetConfigTestPayment(ctx, id) +} + +// HandleConfigTestNotify 处理独立测试回调;只更新测试单,不触碰任何业务支付或订单。 +func (r *Repository) HandleConfigTestNotify(ctx context.Context, provider string, notifyToken string, params map[string]string, rawPayload string, contentType string, authorization string) (*NotifyResult, error) { + if r == nil || r.db == nil || r.configRepo == nil { + return nil, ErrDependencyUnavailable + } + var row model.PaymentConfigTestOrder + if err := r.db.WithContext(ctx). + Where("notify_token = ? AND provider = ?", notifyToken, strings.ToLower(strings.TrimSpace(provider))). + First(&row).Error; err != nil { + if err == gorm.ErrRecordNotFound { + return nil, ErrPaymentNotFound + } + return nil, err + } + if err := r.db.WithContext(ctx).Model(&model.PaymentConfigTestOrder{}).Where("id = ?", row.ID). + Update("notify_request", jsonMap(configTestNotifyRequest(params, contentType))).Error; err != nil { + return nil, err + } + if row.Status == "paid" { + return &NotifyResult{OK: true, Message: "000000"}, nil + } + configCtx := scopedTenantContext(ctx, row.TenantID) + dto, err := r.configRepo.FindRuntimeByID(configCtx, row.PaymentConfigID, true) + if err != nil { + return nil, err + } + runtimeConfig := runtimeConfigFromDTO(dto) + channel, err := buildConfigTestChannelClient(dto) + if err != nil { + return nil, ErrPaymentUnavailable + } + runtimeConfig.Channel = channel + if runtimeConfig.Channel == nil { + return nil, ErrPaymentUnavailable + } + processingParams := params + if provider == "saobei" { + processingParams = saobei.CanonicalizePayload(params) + if merchantNo := processingParams["merchant_no"]; merchantNo == "" || merchantNo != row.MerchantID { + r.recordConfigTestNotifyFailure(ctx, row, "merchant_mismatch") + return nil, ErrPaymentVerifyFailed + } + if amount := parseCent(processingParams["amount"]); amount <= 0 || amount != row.AmountCent { + r.recordConfigTestNotifyFailure(ctx, row, "amount_mismatch") + return nil, ErrPaymentVerifyFailed + } + } + if amount := parseCent(processingParams["amount"]); amount > 0 && amount != row.AmountCent { + r.recordConfigTestNotifyFailure(ctx, row, "amount_mismatch") + return nil, ErrPaymentVerifyFailed + } + verify, err := runtimeConfig.Channel.VerifyNotify(processingParams, rawPayload, contentType, authorization) + if err != nil || !verify.OK { + r.recordConfigTestNotifyFailure(ctx, row, "verify_failed") + return nil, ErrPaymentVerifyFailed + } + status := normalizeNotifyPaymentStatus(provider, processingParams["status"]) + now := time.Now() + updates := map[string]any{ + "status": status, + "notified_at": now, + "notify_request": jsonMap(configTestNotifyRequest(params, contentType)), + "notify_result": jsonMap(configTestNotifyResult(true, status, row, "")), + "provider_order_id": firstNonEmpty(processingParams["provider_order_id"], processingParams["out_trade_no"], processingParams["schc_order_id"], processingParams["leshua_order_id"], processingParams["pay_order_no"], processingParams["trade_no"], row.ProviderOrderID), + "error_message": "", + } + if status == "paid" { + paidAt := parseChannelTime(firstNonEmpty(processingParams["pay_time"], processingParams["end_time"])) + if paidAt == nil { + paidAt = &now + } + updates["paid_at"] = *paidAt + } + if err := r.db.WithContext(ctx).Model(&model.PaymentConfigTestOrder{}).Where("id = ?", row.ID).Updates(updates).Error; err != nil { + return nil, err + } + return &NotifyResult{OK: true, Message: "000000"}, nil +} + +func (r *Repository) ListConfigTestPayments(ctx context.Context, query ConfigTestPaymentQuery) (*ConfigTestPaymentListResponse, error) { + if r == nil || r.db == nil { + return nil, ErrDependencyUnavailable + } + if query.Page < 1 { + query.Page = 1 + } + if query.PageSize < 1 { + query.PageSize = 20 + } + if query.PageSize > 100 { + query.PageSize = 100 + } + db := r.db.WithContext(ctx).Model(&model.PaymentConfigTestOrder{}) + if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 { + db = db.Where("tenant_id = ?", tenantID) + } + if query.PaymentConfigID > 0 { + db = db.Where("payment_config_id = ?", query.PaymentConfigID) + } + if value := strings.TrimSpace(query.Provider); value != "" { + db = db.Where("provider = ?", value) + } + if value := strings.TrimSpace(query.PayWay); value != "" { + db = db.Where("pay_way = ?", normalizePayWay(value)) + } + if value := strings.TrimSpace(query.Status); value != "" { + db = db.Where("status = ?", value) + } + if value := strings.TrimSpace(query.TestNo); value != "" { + db = db.Where("test_no LIKE ?", "%"+value+"%") + } + var total int64 + if err := db.Count(&total).Error; err != nil { + return nil, err + } + var rows []model.PaymentConfigTestOrder + if err := db.Order("id DESC").Offset((query.Page - 1) * query.PageSize).Limit(query.PageSize).Find(&rows).Error; err != nil { + return nil, err + } + items := make([]ConfigTestPaymentDTO, 0, len(rows)) + for i := range rows { + items = append(items, toConfigTestPaymentDTO(rows[i], false)) + } + return &ConfigTestPaymentListResponse{Items: items, Total: total, Page: query.Page, PageSize: query.PageSize}, nil +} + +func (r *Repository) GetConfigTestPayment(ctx context.Context, id uint64) (*ConfigTestPaymentDTO, error) { + row, err := r.findConfigTestPayment(ctx, id, false) + if err != nil { + return nil, err + } + dto := toConfigTestPaymentDTO(*row, true) + return &dto, nil +} + +func (r *Repository) findConfigTestPayment(ctx context.Context, id uint64, lock bool) (*model.PaymentConfigTestOrder, error) { + if r == nil || r.db == nil { + return nil, ErrDependencyUnavailable + } + query := r.db.WithContext(ctx).Where("id = ?", id) + if tenantID := tenancy.IDFromContext(ctx); tenantID > 0 { + query = query.Where("tenant_id = ?", tenantID) + } + if lock { + query = query.Clauses(clause.Locking{Strength: "UPDATE"}) + } + var row model.PaymentConfigTestOrder + if err := query.First(&row).Error; err != nil { + if err == gorm.ErrRecordNotFound { + return nil, ErrPaymentNotFound + } + return nil, err + } + return &row, nil +} + +func (r *Repository) failConfigTestPayment(ctx context.Context, id uint64, message string, raw map[string]string, rawRequest map[string]string) error { + updates := map[string]any{ + "status": "failed", + "error_message": truncateText(message, 500), + } + if raw != nil { + sanitized := sanitizeConfigTestPayload(raw) + updates["raw_response"] = jsonMap(withRawSource(sanitized, channelSourceCreate)) + updates["create_response"] = jsonMap(withRawSource(sanitized, channelSourceCreate)) + } + if rawRequest != nil { + sanitized := sanitizeConfigTestPayload(rawRequest) + updates["raw_request"] = jsonMap(sanitized) + updates["create_request"] = jsonMap(sanitized) + } + return r.db.WithContext(ctx).Model(&model.PaymentConfigTestOrder{}).Where("id = ?", id).Updates(updates).Error +} + +func configTestChannelStatus(status string) string { + switch strings.ToLower(strings.TrimSpace(status)) { + case "paid": + return "paid" + case "closed": + return "closed" + case "failed": + return "failed" + default: + return "paying" + } +} + +func configTestTerminal(status string) bool { + return status == "paid" || status == "closed" || status == "failed" +} + +func newConfigTestNo(prefix string) (string, error) { + token, err := randomToken(5) + if err != nil { + return "", err + } + return fmt.Sprintf("%s%d%s", prefix, time.Now().UnixNano(), token), nil +} + +func randomToken(size int) (string, error) { + buf := make([]byte, size) + if _, err := rand.Read(buf); err != nil { + return "", err + } + return hex.EncodeToString(buf), nil +} + +func buildConfigTestNotifyURL(raw string, provider string, token string) string { + base := strings.TrimSpace(raw) + parsed, err := url.Parse(base) + if err != nil || parsed.Scheme == "" || parsed.Host == "" { + return base + } + parsed.Path = "/api/payments/config-test/" + strings.ToLower(strings.TrimSpace(provider)) + "/notify/" + token + parsed.RawQuery = "" + parsed.Fragment = "" + return parsed.String() +} + +func truncateText(value string, limit int) string { + value = strings.TrimSpace(value) + if limit <= 0 || len(value) <= limit { + return value + } + return value[:limit] +} +func configTestQueryErrorMessage(raw map[string]string, message string) string { + code := strings.TrimSpace(raw["error_code"]) + if code == "-4006" || code == "-20004" { + return "渠道暂未生成可查询订单,请完成扫码支付后再刷新" + } + if value := strings.TrimSpace(message); value != "" { + return truncateText(value, 500) + } + return "渠道查询暂未返回有效订单,请完成扫码支付后再刷新" +} +func (r *Repository) recordConfigTestNotifyFailure(ctx context.Context, row model.PaymentConfigTestOrder, reason string) { + _ = r.db.WithContext(ctx).Model(&model.PaymentConfigTestOrder{}).Where("id = ?", row.ID). + Update("notify_result", jsonMap(configTestNotifyResult(false, "rejected", row, reason))).Error +} + +func (r *Repository) RecordConfigTestNotifyAck(ctx context.Context, provider string, notifyToken string, ack string) error { + if r == nil || r.db == nil { + return ErrDependencyUnavailable + } + return r.db.WithContext(ctx).Model(&model.PaymentConfigTestOrder{}). + Where("notify_token = ? AND provider = ?", notifyToken, strings.ToLower(strings.TrimSpace(provider))). + Update("notify_ack", truncateText(ack, 500)).Error +} diff --git a/backend/internal/modules/payment/config_test_repository_test.go b/backend/internal/modules/payment/config_test_repository_test.go new file mode 100644 index 00000000..89d5433b --- /dev/null +++ b/backend/internal/modules/payment/config_test_repository_test.go @@ -0,0 +1,167 @@ +package payment + +import ( + "context" + "strings" + "testing" + + "hfb_sys/backend/internal/database" + "hfb_sys/backend/internal/model" + "hfb_sys/backend/internal/modules/paymentconfig" + "hfb_sys/backend/internal/tenancy" +) + +func TestBuildConfigTestNotifyURLKeepsPublicOrigin(t *testing.T) { + got := buildConfigTestNotifyURL("https://pay.example.com/api/payments/leshua/notify?x=1", "leshua", "token123") + want := "https://pay.example.com/api/payments/config-test/leshua/notify/token123" + if got != want { + t.Fatalf("buildConfigTestNotifyURL() = %q, want %q", got, want) + } +} + +func TestBuildConfigTestNotifyURLFallsBackForInvalidBase(t *testing.T) { + raw := "not-a-public-url" + if got := buildConfigTestNotifyURL(raw, "lakala", "token"); got != raw { + t.Fatalf("buildConfigTestNotifyURL() = %q, want %q", got, raw) + } +} + +func TestConfigTestChannelStatus(t *testing.T) { + cases := map[string]string{ + "paid": "paid", + "closed": "closed", + "failed": "failed", + "paying": "paying", + "": "paying", + "unknown": "paying", + } + for input, want := range cases { + if got := configTestChannelStatus(input); got != want { + t.Fatalf("configTestChannelStatus(%q) = %q, want %q", input, got, want) + } + } +} + +func TestBuildConfigTestChannelClientDoesNotUseSharedBreaker(t *testing.T) { + dto := &paymentconfig.ConfigDTO{Provider: "leshua", PayWay: "ZFBZF", JSPayFlag: "2", SignType: "MD5"} + testClient, err := buildConfigTestChannelClient(dto) + if err != nil { + t.Fatalf("buildConfigTestChannelClient() error = %v", err) + } + if _, ok := testClient.(breakerChannel); ok { + t.Fatal("config test channel must not use the shared production circuit breaker") + } + productionClient, err := buildChannelClient(dto) + if err != nil { + t.Fatalf("buildChannelClient() error = %v", err) + } + if _, ok := productionClient.(breakerChannel); !ok { + t.Fatal("production payment channel must keep the shared circuit breaker") + } +} + +func TestNewConfigTestNoHasPrefixAndRandomPart(t *testing.T) { + first, err := newConfigTestNo("PCT") + if err != nil { + t.Fatalf("newConfigTestNo() error = %v", err) + } + second, err := newConfigTestNo("PCT") + if err != nil { + t.Fatalf("newConfigTestNo() error = %v", err) + } + if !strings.HasPrefix(first, "PCT") || len(first) <= 10 { + t.Fatalf("unexpected test no: %q", first) + } + if first == second { + t.Fatal("test numbers should be unique") + } +} +func TestConfigTestPaymentMockFlowIsIsolated(t *testing.T) { + db := database.NewTestDB() + config := model.PaymentMerchantConfig{ + OwnerTenantID: 1, + Name: "测试模拟支付", + Provider: "mock", + MerchantID: "MOCK-TEST", + PayWay: "ZFBZF", + Status: "disabled", + Environment: "production", + IsDefault: false, + } + if err := db.Create(&config).Error; err != nil { + t.Fatalf("create payment config: %v", err) + } + repo := NewRepository(db, paymentconfig.NewRepository(db, &paymentconfig.MockEncryptor{}), nil) + ctx := tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: 1}) + dto, err := repo.StartConfigTestPayment(ctx, config.ID, StartConfigTestPaymentRequest{AmountCent: 1}, 9, "127.0.0.1") + if err != nil { + t.Fatalf("StartConfigTestPayment() error = %v", err) + } + if dto.Status != "paid" || dto.AmountCent != 1 || dto.PaymentConfigID != config.ID { + t.Fatalf("unexpected test payment: %+v", dto) + } + if dto.ConfigStatus != "disabled" { + t.Fatalf("config status snapshot = %q, want disabled", dto.ConfigStatus) + } + detail, err := repo.GetConfigTestPayment(ctx, dto.ID) + if err != nil { + t.Fatalf("GetConfigTestPayment() error = %v", err) + } + if len(detail.CreateResponse) == 0 { + t.Fatal("mock test payment should persist create_response") + } + var paymentOrders int64 + if err := db.Model(&model.PaymentOrder{}).Count(&paymentOrders).Error; err != nil { + t.Fatalf("count payment orders: %v", err) + } + if paymentOrders != 0 { + t.Fatalf("business payment_orders count = %d, want 0", paymentOrders) + } + list, err := repo.ListConfigTestPayments(ctx, ConfigTestPaymentQuery{PaymentConfigID: config.ID}) + if err != nil { + t.Fatalf("ListConfigTestPayments() error = %v", err) + } + if list.Total != 1 || len(list.Items) != 1 { + t.Fatalf("test payment list = %+v", list) + } +} +func TestConfigTestQueryErrorMessage(t *testing.T) { + got := configTestQueryErrorMessage(map[string]string{"error_code": "-4006"}, "订单不存在") + want := "渠道暂未生成可查询订单,请完成扫码支付后再刷新" + if got != want { + t.Fatalf("configTestQueryErrorMessage() = %q, want %q", got, want) + } + if got := configTestQueryErrorMessage(nil, "渠道超时"); got != "渠道超时" { + t.Fatalf("configTestQueryErrorMessage() fallback = %q", got) + } +} +func TestSanitizeConfigTestPayloadMasksSensitiveFields(t *testing.T) { + payload := sanitizeConfigTestPayload(map[string]string{ + "sign": "signature", + "openid": "wx-openid", + "status": "2", + "amount": "1", + "access_token": "token", + }) + if payload["sign"] != "***" || payload["openid"] != "***" || payload["access_token"] != "***" { + t.Fatalf("sensitive fields were not masked: %+v", payload) + } + if payload["status"] != "2" || payload["amount"] != "1" { + t.Fatalf("normal fields should remain: %+v", payload) + } +} + +func TestConfigTestNotifyAckFormats(t *testing.T) { + if got := configTestNotifyAck("leshua", true); got != "000000" { + t.Fatalf("leshua success ack = %q", got) + } + if got := configTestNotifyAck("leshua", false); got != "FAIL" { + t.Fatalf("leshua failure ack = %q", got) + } + if got := configTestNotifyAck("saobei", true); !strings.Contains(got, `"return_code":"01"`) { + t.Fatalf("saobei success ack = %q", got) + } + if got := configTestNotifyAck("lakala", true); !strings.Contains(got, `"code":"SUCCESS"`) { + t.Fatalf("lakala success ack = %q", got) + } +} diff --git a/backend/internal/modules/payment/config_test_service.go b/backend/internal/modules/payment/config_test_service.go new file mode 100644 index 00000000..eff29706 --- /dev/null +++ b/backend/internal/modules/payment/config_test_service.go @@ -0,0 +1,44 @@ +package payment + +import "context" + +func (s *Service) StartConfigTestPayment(ctx context.Context, configID uint64, req StartConfigTestPaymentRequest, adminID uint64, clientIP string) (*ConfigTestPaymentDTO, error) { + if s.repo == nil { + return nil, ErrDependencyUnavailable + } + return s.repo.StartConfigTestPayment(ctx, configID, req, adminID, clientIP) +} + +func (s *Service) ListConfigTestPayments(ctx context.Context, query ConfigTestPaymentQuery) (*ConfigTestPaymentListResponse, error) { + if s.repo == nil { + return nil, ErrDependencyUnavailable + } + return s.repo.ListConfigTestPayments(ctx, query) +} + +func (s *Service) GetConfigTestPayment(ctx context.Context, id uint64) (*ConfigTestPaymentDTO, error) { + if s.repo == nil { + return nil, ErrDependencyUnavailable + } + return s.repo.GetConfigTestPayment(ctx, id) +} + +func (s *Service) RefreshConfigTestPayment(ctx context.Context, id uint64) (*ConfigTestPaymentDTO, error) { + if s.repo == nil { + return nil, ErrDependencyUnavailable + } + return s.repo.RefreshConfigTestPayment(ctx, id) +} + +func (s *Service) HandleConfigTestNotify(ctx context.Context, provider string, notifyToken string, params map[string]string, rawPayload string, contentType string, authorization string) (*NotifyResult, error) { + if s.repo == nil { + return nil, ErrDependencyUnavailable + } + return s.repo.HandleConfigTestNotify(ctx, provider, notifyToken, params, rawPayload, contentType, authorization) +} +func (s *Service) RecordConfigTestNotifyAck(ctx context.Context, provider string, notifyToken string, ack string) error { + if s.repo == nil { + return ErrDependencyUnavailable + } + return s.repo.RecordConfigTestNotifyAck(ctx, provider, notifyToken, ack) +} diff --git a/backend/internal/router/router.go b/backend/internal/router/router.go index 92d5de86..2e4b4245 100644 --- a/backend/internal/router/router.go +++ b/backend/internal/router/router.go @@ -553,6 +553,7 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine { api.POST("/payments/lakala/notify", paymentHandler.LakalaNotify) api.POST("/payments/shuncheng/notify", paymentHandler.ShunchengNotify) api.POST("/payments/saobei/notify", paymentHandler.SaobeiNotify) + api.POST("/payments/config-test/:provider/notify/:token", paymentHandler.ConfigTestNotify) openRoutes := api.Group("/open") { @@ -1005,6 +1006,10 @@ func New(cfg config.Config, deps Dependencies, logger *zap.Logger) *gin.Engine { adminRoutes.POST("/payment-configs", requirePerm("payment_config:create"), paymentConfigHandler.Create) adminRoutes.PUT("/payment-configs/:id", requirePerm("payment_config:update"), paymentConfigHandler.Update) adminRoutes.DELETE("/payment-configs/:id", requirePerm("payment_config:delete"), paymentConfigHandler.Delete) + adminRoutes.POST("/payment-configs/:id/test-orders", requirePerm("payment_config:list"), paymentHandler.StartConfigTestPayment) + adminRoutes.GET("/payment-config-test-orders", requirePerm("payment_config:list"), paymentHandler.AdminListConfigTestPayments) + adminRoutes.GET("/payment-config-test-orders/:id", requirePerm("payment_config:list"), paymentHandler.AdminGetConfigTestPayment) + adminRoutes.POST("/payment-config-test-orders/:id/refresh", requirePerm("payment_config:list"), paymentHandler.AdminRefreshConfigTestPayment) } adminRoutes.GET("/system-configs", requirePerm("system_config:view"), systemConfigHandler.List) diff --git a/backend/migrations/000112_payment_config_test_orders.sql b/backend/migrations/000112_payment_config_test_orders.sql new file mode 100644 index 00000000..e3039689 --- /dev/null +++ b/backend/migrations/000112_payment_config_test_orders.sql @@ -0,0 +1,41 @@ +-- +goose Up +CREATE TABLE payment_config_test_orders ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + tenant_id BIGINT UNSIGNED NOT NULL DEFAULT 0, + payment_config_id BIGINT UNSIGNED NOT NULL, + config_name VARCHAR(128) NOT NULL, + provider VARCHAR(32) NOT NULL, + merchant_id VARCHAR(128) NOT NULL, + pay_way VARCHAR(16) NOT NULL DEFAULT '', + environment VARCHAR(16) NOT NULL DEFAULT '', + config_status VARCHAR(32) NOT NULL DEFAULT '', + test_no VARCHAR(64) NOT NULL, + third_order_id VARCHAR(64) NOT NULL, + notify_token VARCHAR(64) NOT NULL, + provider_order_id VARCHAR(64) NOT NULL DEFAULT '', + amount_cent BIGINT NOT NULL DEFAULT 0, + status VARCHAR(32) NOT NULL DEFAULT 'created', + td_code VARCHAR(512) NOT NULL DEFAULT '', + jspay_url VARCHAR(512) NOT NULL DEFAULT '', + jspay_info TEXT, + error_message VARCHAR(512) NOT NULL DEFAULT '', + raw_request JSON DEFAULT NULL, + raw_response JSON DEFAULT NULL, + query_count INT NOT NULL DEFAULT 0, + last_queried_at DATETIME DEFAULT NULL, + paid_at DATETIME DEFAULT NULL, + notified_at DATETIME DEFAULT NULL, + created_by BIGINT UNSIGNED DEFAULT NULL, + created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (id), + UNIQUE KEY uk_payment_config_test_no (test_no), + UNIQUE KEY uk_payment_config_test_third_order (third_order_id), + UNIQUE KEY uk_payment_config_test_notify_token (notify_token), + KEY idx_payment_config_test_tenant_created (tenant_id, created_at), + KEY idx_payment_config_test_config (payment_config_id, created_at), + KEY idx_payment_config_test_status (status, created_at) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='支付配置真实通道测试单'; + +-- +goose Down +DROP TABLE IF EXISTS payment_config_test_orders; \ No newline at end of file diff --git a/backend/migrations/000113_payment_config_test_trace.sql b/backend/migrations/000113_payment_config_test_trace.sql new file mode 100644 index 00000000..d20e4f3e --- /dev/null +++ b/backend/migrations/000113_payment_config_test_trace.sql @@ -0,0 +1,19 @@ +-- +goose Up +ALTER TABLE payment_config_test_orders + ADD COLUMN create_request JSON DEFAULT NULL AFTER raw_request, + ADD COLUMN create_response JSON DEFAULT NULL AFTER create_request, + ADD COLUMN query_request JSON DEFAULT NULL AFTER create_response, + ADD COLUMN query_response JSON DEFAULT NULL AFTER query_request, + ADD COLUMN notify_request JSON DEFAULT NULL AFTER query_response, + ADD COLUMN notify_result JSON DEFAULT NULL AFTER notify_request, + ADD COLUMN notify_ack VARCHAR(512) NOT NULL DEFAULT '' AFTER notify_result; + +-- +goose Down +ALTER TABLE payment_config_test_orders + DROP COLUMN notify_ack, + DROP COLUMN notify_result, + DROP COLUMN notify_request, + DROP COLUMN query_response, + DROP COLUMN query_request, + DROP COLUMN create_response, + DROP COLUMN create_request; \ No newline at end of file diff --git a/frontend/src/features/admin/api/paymentConfigTest.ts b/frontend/src/features/admin/api/paymentConfigTest.ts new file mode 100644 index 00000000..b790c2c4 --- /dev/null +++ b/frontend/src/features/admin/api/paymentConfigTest.ts @@ -0,0 +1,96 @@ +import { apiClient } from '@/shared/api/client' +import type { ApiResponse } from '@/shared/types/types' + +export interface ConfigTestPayment { + id: number + tenant_id: number + payment_config_id: number + config_name: string + provider: string + merchant_id: string + pay_way: string + environment: string + config_status: string + test_no: string + third_order_id: string + provider_order_id: string + amount_cent: number + status: string + td_code?: string + jspay_url?: string + jspay_info?: string + error_message: string + raw_request?: Record | null + raw_response?: Record | null + create_request?: Record | null + create_response?: Record | null + query_request?: Record | null + query_response?: Record | null + notify_request?: Record | null + notify_result?: Record | null + notify_ack?: string + query_count: number + last_queried_at?: string + paid_at?: string + notified_at?: string + created_at: string + updated_at: string +} + +export interface ConfigTestPaymentList { + items: ConfigTestPayment[] + total: number + page: number + page_size: number +} + +export interface ConfigTestPaymentQuery { + payment_config_id?: number + provider?: string + pay_way?: string + status?: string + test_no?: string + page?: number + page_size?: number +} + +export async function createConfigTestPayment(configId: number, amountCent: number) { + const { data } = await apiClient.post>( + `/admin/payment-configs/${configId}/test-orders`, + { amount_cent: amountCent } + ) + return data.data +} + +export async function fetchConfigTestPayments(query: ConfigTestPaymentQuery = {}) { + const params = Object.fromEntries( + Object.entries(query).filter(([, value]) => value !== '' && value !== undefined) + ) + const { data } = await apiClient.get>( + '/admin/payment-config-test-orders', + { params } + ) + const result = data.data + return { + items: Array.isArray(result?.items) ? result.items : [], + total: Number(result?.total ?? 0), + page: Number(result?.page ?? query.page ?? 1), + page_size: Number(result?.page_size ?? query.page_size ?? 20), + } +} + +export async function fetchConfigTestPayment(id: number) { + const { data } = await apiClient.get>( + `/admin/payment-config-test-orders/${id}` + ) + return data.data +} + +export async function refreshConfigTestPayment(id: number, silent = false) { + const { data } = await apiClient.post>( + `/admin/payment-config-test-orders/${id}/refresh`, + undefined, + { silent } + ) + return data.data +} diff --git a/frontend/src/features/admin/components/PaymentConfigTestDialog.vue b/frontend/src/features/admin/components/PaymentConfigTestDialog.vue new file mode 100644 index 00000000..6d6b1efc --- /dev/null +++ b/frontend/src/features/admin/components/PaymentConfigTestDialog.vue @@ -0,0 +1,478 @@ + + + + + diff --git a/frontend/src/features/admin/components/PaymentConfigTestRecordsDrawer.vue b/frontend/src/features/admin/components/PaymentConfigTestRecordsDrawer.vue new file mode 100644 index 00000000..3cbb093e --- /dev/null +++ b/frontend/src/features/admin/components/PaymentConfigTestRecordsDrawer.vue @@ -0,0 +1,508 @@ + + + + + diff --git a/frontend/src/features/admin/views/AdminPaymentConfigsView.vue b/frontend/src/features/admin/views/AdminPaymentConfigsView.vue index 532aa324..3f04937c 100644 --- a/frontend/src/features/admin/views/AdminPaymentConfigsView.vue +++ b/frontend/src/features/admin/views/AdminPaymentConfigsView.vue @@ -10,6 +10,8 @@ import { Download, Upload, StarFilled, + Tickets, + VideoPlay, } from '@element-plus/icons-vue' import { @@ -21,6 +23,8 @@ import { } from '@/features/admin/api/paymentConfig' import { readError } from '@/shared/utils/error' import PaymentConfigDialog from '../components/PaymentConfigDialog.vue' +import PaymentConfigTestDialog from '../components/PaymentConfigTestDialog.vue' +import PaymentConfigTestRecordsDrawer from '../components/PaymentConfigTestRecordsDrawer.vue' const loading = ref(false) const configs = ref([]) @@ -34,6 +38,9 @@ const backupFileInput = ref(null) const dialogVisible = ref(false) const dialogMode = ref<'create' | 'edit' | 'view'>('create') const currentConfig = ref(null) +const testDialogVisible = ref(false) +const testConfig = ref(null) +const testRecordsVisible = ref(false) const filterProvider = ref('') const filterPayWay = ref('') @@ -110,6 +117,11 @@ function handleEdit(row: PaymentConfig) { dialogVisible.value = true } +function handleTest(row: PaymentConfig) { + testConfig.value = row + testDialogVisible.value = true +} + async function handleDelete(row: PaymentConfig) { if (!canDeleteConfig(row)) { ElMessage.warning('该配置已有交易记录,需要保留用于退款、查询和回调验签') @@ -315,6 +327,7 @@ function deleteDisabledReason(row: PaymentConfig) {
+ 测试支付记录 导入备份 @@ -448,9 +461,17 @@ function deleteDisabledReason(row: PaymentConfig) { 备用 - + @@ -783,6 +807,18 @@ function deleteDisabledReason(row: PaymentConfig) { padding: 0 10px; } +.action-button.test { + color: #7c3aed; + background: #f5f3ff; + border-color: #ddd6fe; +} + +.action-button.test:hover { + color: #ffffff; + background: #7c3aed; + border-color: #7c3aed; +} + .action-button.view { color: #1d4ed8; background: #eff6ff;