feat(payment): 增加支付配置测试支付与全链路报文

This commit is contained in:
2026-11-20 14:51:17 +08:00
parent b539e3a42f
commit 8fec2fa5a2
19 changed files with 2353 additions and 5 deletions
@@ -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)
}
@@ -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
}
@@ -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
}
@@ -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"
}
}
@@ -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
}
@@ -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)
}
}
@@ -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)
}