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
@@ -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
}
@@ -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
}
@@ -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
}
@@ -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
}
@@ -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"
}
@@ -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)
}
+5
View File
@@ -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)
@@ -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;
@@ -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;
@@ -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<string, unknown> | null
raw_response?: Record<string, unknown> | null
create_request?: Record<string, unknown> | null
create_response?: Record<string, unknown> | null
query_request?: Record<string, unknown> | null
query_response?: Record<string, unknown> | null
notify_request?: Record<string, unknown> | null
notify_result?: Record<string, unknown> | 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<ApiResponse<ConfigTestPayment>>(
`/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<ApiResponse<ConfigTestPaymentList>>(
'/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<ApiResponse<ConfigTestPayment>>(
`/admin/payment-config-test-orders/${id}`
)
return data.data
}
export async function refreshConfigTestPayment(id: number, silent = false) {
const { data } = await apiClient.post<ApiResponse<ConfigTestPayment>>(
`/admin/payment-config-test-orders/${id}/refresh`,
undefined,
{ silent }
)
return data.data
}
@@ -0,0 +1,478 @@
<script setup lang="ts">
import { Loading, Refresh, VideoPlay, WarningFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import QRCode from 'qrcode'
import { computed, onBeforeUnmount, ref, watch } from 'vue'
import {
createConfigTestPayment,
refreshConfigTestPayment,
type ConfigTestPayment,
} from '@/features/admin/api/paymentConfigTest'
import type { PaymentConfig } from '@/features/admin/api/paymentConfig'
import { readError } from '@/shared/utils/error'
const props = defineProps<{
modelValue: boolean
config: PaymentConfig | null
}>()
const emit = defineEmits<{
'update:modelValue': [value: boolean]
changed: []
}>()
const visible = computed({
get: () => props.modelValue,
set: value => emit('update:modelValue', value),
})
const amountYuan = ref(0.01)
const creating = ref(false)
const refreshing = ref(false)
const qrGenerating = ref(false)
const qrDataUrl = ref('')
const payment = ref<ConfigTestPayment | null>(null)
let pollingTimer: number | undefined
const payUrl = computed(
() => payment.value?.jspay_url || payment.value?.td_code || payment.value?.jspay_info || ''
)
const hasRenderablePayURL = computed(() => /^https?:\/\//i.test(payUrl.value))
const terminal = computed(() =>
payment.value ? ['paid', 'closed', 'failed'].includes(payment.value.status) : false
)
const statusLabel = computed(() => {
const map: Record<string, string> = {
created: '创建中',
paying: '待扫码支付',
paid: '已支付',
failed: '失败',
closed: '已关闭',
}
return map[payment.value?.status || ''] || payment.value?.status || ''
})
const statusType = computed(() => {
if (payment.value?.status === 'paid') return 'success'
if (payment.value?.status === 'failed') return 'danger'
if (payment.value?.status === 'closed') return 'info'
return 'warning'
})
watch(
() => props.modelValue,
value => {
if (value) {
reset()
} else {
stopPolling()
}
}
)
watch(
() => props.config?.id,
() => {
if (props.modelValue) reset()
}
)
onBeforeUnmount(stopPolling)
function reset() {
stopPolling()
amountYuan.value = 0.01
payment.value = null
qrDataUrl.value = ''
qrGenerating.value = false
creating.value = false
refreshing.value = false
}
async function startTestPayment() {
if (!props.config) return
const amountCent = Math.round(Number(amountYuan.value) * 100)
if (!Number.isFinite(amountCent) || amountCent <= 0) {
ElMessage.warning('测试金额必须大于 0')
return
}
creating.value = true
stopPolling()
try {
payment.value = await createConfigTestPayment(props.config.id, amountCent)
await renderQRCode()
emit('changed')
if (!terminal.value) startPolling()
} catch (error) {
ElMessage.error(readError(error, '创建测试支付失败'))
} finally {
creating.value = false
}
}
async function refreshStatus(silent = false) {
if (!payment.value || refreshing.value) return
refreshing.value = true
try {
payment.value = await refreshConfigTestPayment(payment.value.id, silent)
if (payment.value.status === 'paid') {
stopPolling()
if (!silent) ElMessage.success('测试支付已到账')
} else if (payment.value.status === 'failed') {
stopPolling()
if (!silent) ElMessage.error(payment.value.error_message || '测试支付失败')
} else if (payment.value.status === 'closed') {
stopPolling()
} else if (payment.value.status === 'paying' && payment.value.error_message && !silent) {
ElMessage.warning(payment.value.error_message)
}
emit('changed')
} catch (error) {
if (!silent) ElMessage.error(readError(error, '查询测试支付状态失败'))
} finally {
refreshing.value = false
}
}
async function renderQRCode() {
qrDataUrl.value = ''
const url = payUrl.value
if (!url || !/^https?:\/\//i.test(url)) return
qrGenerating.value = true
try {
qrDataUrl.value = await QRCode.toDataURL(url, {
width: 280,
margin: 1,
errorCorrectionLevel: 'M',
color: { dark: '#111827', light: '#ffffff' },
})
} catch {
ElMessage.error('二维码生成失败')
} finally {
qrGenerating.value = false
}
}
function startPolling() {
stopPolling()
pollingTimer = window.setInterval(() => {
void refreshStatus(true)
}, 3000)
}
function stopPolling() {
if (pollingTimer === undefined) return
window.clearInterval(pollingTimer)
pollingTimer = undefined
}
function formatAmount(cent: number) {
return (Number(cent || 0) / 100).toFixed(2)
}
function formatPayWay(value?: string) {
return value === 'WXZF' ? '微信' : value === 'ZFBZF' ? '支付宝' : value || '-'
}
</script>
<template>
<el-dialog
v-model="visible"
title="支付配置测试"
width="720px"
class="config-test-dialog"
destroy-on-close
@closed="stopPolling"
>
<div v-if="config" class="test-shell">
<div class="config-summary">
<div>
<span class="summary-label">配置</span>
<strong>{{ config.name }}</strong>
</div>
<div>
<span class="summary-label">服务商</span>
<strong>{{ config.provider }}</strong>
</div>
<div>
<span class="summary-label">商户号</span>
<strong>{{ config.merchant_id }}</strong>
</div>
<div>
<span class="summary-label">支付方式</span>
<strong>{{ formatPayWay(config.pay_way) }}</strong>
</div>
</div>
<el-alert
v-if="config.environment === 'production' || config.status !== 'active'"
type="warning"
:closable="false"
show-icon
class="test-warning"
>
当前为{{
config.environment === 'production' ? '生产环境' : '非启用状态'
}}配置,本次测试会产生真实渠道订单。
</el-alert>
<div class="amount-row">
<div>
<span class="summary-label">测试金额(元)</span>
<p class="amount-tip">默认 0.01 元,可修改;真实扫码支付会实际扣款。</p>
</div>
<el-input-number
v-model="amountYuan"
:min="0.01"
:step="0.01"
:precision="2"
size="large"
controls-position="right"
/>
</div>
<div class="test-actions">
<el-button
type="primary"
size="large"
:icon="VideoPlay"
:loading="creating"
@click="startTestPayment"
>
{{ payment ? '重新生成测试支付' : '生成支付二维码' }}
</el-button>
<el-button
v-if="payment"
:icon="Refresh"
size="large"
:loading="refreshing"
@click="refreshStatus(false)"
>
刷新状态
</el-button>
</div>
<div v-if="payment" class="payment-result">
<div class="result-head">
<div>
<span class="summary-label">测试单号</span>
<strong class="mono">{{ payment.test_no }}</strong>
</div>
<el-tag :type="statusType" effect="light">{{ statusLabel }}</el-tag>
</div>
<div v-if="payment.status === 'paying'" class="qr-area">
<div class="qr-box">
<el-icon v-if="qrGenerating" class="is-loading" :size="32"><Loading /></el-icon>
<img v-else-if="qrDataUrl" :src="qrDataUrl" alt="测试支付二维码" />
<el-icon v-else :size="42"><WarningFilled /></el-icon>
</div>
<div class="qr-copy">
<h3>
请使用{{ formatPayWay(payment.pay_way) }}扫码支付 ¥{{
formatAmount(payment.amount_cent)
}}
</h3>
<p>支付完成后系统会自动查单;也可以点击“刷新状态”立即查询。</p>
<p class="mono">渠道单号:{{ payment.provider_order_id || '等待渠道返回' }}</p>
<el-alert
v-if="!hasRenderablePayURL"
type="warning"
:closable="false"
show-icon
title="渠道未返回可识别的支付链接,请查看测试记录或稍后刷新状态"
/>
<el-alert
v-else-if="payment.error_message"
type="warning"
:closable="false"
show-icon
:title="payment.error_message"
/>
</div>
</div>
<el-alert
v-if="payment.status === 'paid'"
type="success"
:closable="false"
show-icon
title="测试支付已成功"
:description="`支付时间:${payment.paid_at || payment.updated_at}`"
/>
<el-alert
v-else-if="payment.status === 'failed'"
type="error"
:closable="false"
show-icon
title="测试支付失败"
:description="payment.error_message || '请查看测试支付记录中的渠道报文'"
/>
<el-alert
v-else-if="payment.status === 'closed'"
type="info"
:closable="false"
show-icon
title="测试支付已关闭"
/>
</div>
</div>
<template #footer>
<el-button @click="visible = false">关闭</el-button>
</template>
</el-dialog>
</template>
<style scoped>
.test-shell {
display: flex;
flex-direction: column;
gap: 18px;
}
.config-summary {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 12px;
padding: 16px;
border: 1px solid #e2e8f0;
border-radius: 12px;
background: #f8fafc;
}
.config-summary > div,
.result-head > div {
display: flex;
min-width: 0;
flex-direction: column;
gap: 4px;
}
.summary-label {
color: #64748b;
font-size: 12px;
font-weight: 600;
}
.config-summary strong,
.result-head strong {
overflow: hidden;
color: #0f172a;
font-size: 13px;
text-overflow: ellipsis;
white-space: nowrap;
}
.test-warning {
border-radius: 10px;
}
.amount-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 24px;
padding: 16px 18px;
border: 1px solid #e2e8f0;
border-radius: 12px;
}
.amount-row :deep(.el-input-number) {
width: 180px;
}
.amount-tip {
margin: 5px 0 0;
color: #94a3b8;
font-size: 12px;
}
.test-actions {
display: flex;
justify-content: center;
gap: 12px;
}
.payment-result {
display: flex;
flex-direction: column;
gap: 16px;
padding-top: 4px;
}
.result-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
}
.mono {
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
}
.qr-area {
display: flex;
align-items: center;
gap: 24px;
padding: 18px;
border: 1px solid #dbeafe;
border-radius: 14px;
background: linear-gradient(135deg, #eff6ff, #ffffff);
}
.qr-box {
display: grid;
width: 240px;
height: 240px;
flex: 0 0 240px;
place-items: center;
border: 1px solid #e2e8f0;
border-radius: 12px;
background: #fff;
}
.qr-box img {
width: 224px;
height: 224px;
}
.qr-copy h3 {
margin: 0 0 10px;
color: #0f172a;
font-size: 16px;
}
.qr-copy p {
margin: 6px 0;
color: #64748b;
font-size: 12.5px;
line-height: 1.6;
word-break: break-all;
}
@media (max-width: 720px) {
.config-summary {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.amount-row,
.qr-area {
align-items: stretch;
flex-direction: column;
}
.qr-box {
width: 220px;
height: 220px;
flex-basis: 220px;
align-self: center;
}
.qr-box img {
width: 204px;
height: 204px;
}
}
</style>
@@ -0,0 +1,508 @@
<script setup lang="ts">
import { Refresh, Search, View } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { computed, reactive, ref, watch } from 'vue'
import {
fetchConfigTestPayment,
fetchConfigTestPayments,
refreshConfigTestPayment,
type ConfigTestPayment,
} from '@/features/admin/api/paymentConfigTest'
import { fetchPaymentConfigs, type PaymentConfig } from '@/features/admin/api/paymentConfig'
import { readError } from '@/shared/utils/error'
import { formatDateTime } from '@/shared/utils/time'
const props = defineProps<{
modelValue: boolean
configs: PaymentConfig[]
}>()
const emit = defineEmits<{
'update:modelValue': [value: boolean]
}>()
const visible = computed({
get: () => props.modelValue,
set: value => emit('update:modelValue', value),
})
const loading = ref(false)
const refreshingID = ref(0)
const records = ref<ConfigTestPayment[]>([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(20)
const detailVisible = ref(false)
const detailLoading = ref(false)
const activeRecord = ref<ConfigTestPayment | null>(null)
const configOptions = ref<PaymentConfig[]>([])
const hasChainPayloads = computed(() =>
Boolean(
activeRecord.value &&
(activeRecord.value.create_request ||
activeRecord.value.create_response ||
activeRecord.value.query_request ||
activeRecord.value.query_response ||
activeRecord.value.notify_request ||
activeRecord.value.notify_result ||
activeRecord.value.notify_ack)
)
)
const filters = reactive({
payment_config_id: '',
provider: '',
status: '',
test_no: '',
})
const providerOptions = [
{ label: '全部服务商', value: '' },
{ label: '乐刷支付', value: 'leshua' },
{ label: '拉卡拉支付', value: 'lakala' },
{ label: '顺成支付', value: 'shuncheng' },
{ label: '扫呗支付', value: 'saobei' },
{ label: '模拟支付', value: 'mock' },
]
const statusOptions = [
{ label: '全部状态', value: '' },
{ label: '创建中', value: 'created' },
{ label: '待扫码支付', value: 'paying' },
{ label: '已支付', value: 'paid' },
{ label: '失败', value: 'failed' },
{ label: '已关闭', value: 'closed' },
]
watch(
() => props.modelValue,
value => {
if (value) {
configOptions.value = props.configs
page.value = 1
void loadConfigOptions()
void loadRecords()
}
}
)
async function loadConfigOptions() {
try {
const result = await fetchPaymentConfigs({ page: 1, page_size: 100 })
configOptions.value = result.items
} catch {
configOptions.value = props.configs
}
}
async function loadRecords() {
loading.value = true
try {
const result = await fetchConfigTestPayments({
payment_config_id: filters.payment_config_id ? Number(filters.payment_config_id) : undefined,
provider: filters.provider || undefined,
status: filters.status || undefined,
test_no: filters.test_no.trim() || undefined,
page: page.value,
page_size: pageSize.value,
})
records.value = result.items
total.value = result.total
} catch (error) {
records.value = []
total.value = 0
ElMessage.error(readError(error, '加载测试支付记录失败'))
} finally {
loading.value = false
}
}
function resetFilters() {
filters.payment_config_id = ''
filters.provider = ''
filters.status = ''
filters.test_no = ''
page.value = 1
void loadRecords()
}
async function refreshRecord(row: ConfigTestPayment) {
refreshingID.value = row.id
try {
const latest = await refreshConfigTestPayment(row.id)
const index = records.value.findIndex(item => item.id === latest.id)
if (index >= 0) records.value[index] = latest
if (activeRecord.value?.id === latest.id) activeRecord.value = latest
ElMessage.success(latest.status === 'paid' ? '已确认支付成功' : '状态已刷新')
} catch (error) {
ElMessage.error(readError(error, '刷新测试支付状态失败'))
} finally {
refreshingID.value = 0
}
}
async function openDetail(row: ConfigTestPayment) {
activeRecord.value = row
detailVisible.value = true
detailLoading.value = true
try {
activeRecord.value = await fetchConfigTestPayment(row.id)
} catch (error) {
ElMessage.error(readError(error, '加载测试支付详情失败'))
} finally {
detailLoading.value = false
}
}
function statusLabel(status: string) {
const map: Record<string, string> = {
created: '创建中',
paying: '待扫码支付',
paid: '已支付',
failed: '失败',
closed: '已关闭',
}
return map[status] || status
}
function statusType(status: string): 'success' | 'danger' | 'warning' | 'info' {
if (status === 'paid') return 'success'
if (status === 'failed') return 'danger'
if (status === 'closed') return 'info'
return 'warning'
}
function environmentLabel(value: string) {
if (value === 'production') return '生产环境'
if (value === 'sandbox') return '测试环境'
return value || '-'
}
function providerLabel(provider: string) {
const map: Record<string, string> = {
leshua: '乐刷支付',
lakala: '拉卡拉支付',
shuncheng: '顺成支付',
saobei: '扫呗支付',
mock: '模拟支付',
}
return map[provider] || provider
}
function payWayLabel(value: string) {
return value === 'WXZF' ? '微信' : value === 'ZFBZF' ? '支付宝' : value || '-'
}
function money(cent: number) {
return `¥${(Number(cent || 0) / 100).toFixed(2)}`
}
function jsonText(value: unknown) {
if (!value) return '{}'
try {
return JSON.stringify(value, null, 2)
} catch {
return String(value)
}
}
</script>
<template>
<el-drawer v-model="visible" title="测试支付记录" size="76%" destroy-on-close>
<div class="records-shell">
<div class="filter-bar">
<el-select
v-model="filters.payment_config_id"
placeholder="支付配置"
clearable
class="filter-select"
>
<el-option
v-for="config in configOptions"
:key="config.id"
:label="config.name"
:value="String(config.id)"
/>
</el-select>
<el-select v-model="filters.provider" placeholder="服务商" class="filter-select">
<el-option
v-for="item in providerOptions"
:key="item.value"
:label="item.label"
:value="item.value"
/>
</el-select>
<el-select v-model="filters.status" placeholder="状态" class="filter-select">
<el-option
v-for="item in statusOptions"
:key="item.value"
:label="item.label"
:value="item.value"
/>
</el-select>
<el-input
v-model="filters.test_no"
placeholder="测试单号"
clearable
class="filter-input"
@keyup.enter="loadRecords"
/>
<el-button :icon="Search" type="primary" @click="loadRecords">查询</el-button>
<el-button :icon="Refresh" @click="resetFilters">重置</el-button>
</div>
<el-table v-loading="loading" :data="records" stripe class="records-table">
<el-table-column prop="test_no" label="测试单号" min-width="230">
<template #default="{ row }">
<span class="mono">{{ row.test_no }}</span>
</template>
</el-table-column>
<el-table-column
prop="config_name"
label="支付配置"
min-width="180"
show-overflow-tooltip
/>
<el-table-column label="服务商 / 方式" min-width="150">
<template #default="{ row }">
<div class="provider-cell">
<span>{{ providerLabel(row.provider) }}</span>
<small>{{ payWayLabel(row.pay_way) }}</small>
</div>
</template>
</el-table-column>
<el-table-column label="金额" width="110" align="right">
<template #default="{ row }">
<strong>{{ money(row.amount_cent) }}</strong>
</template>
</el-table-column>
<el-table-column label="状态" width="110" align="center">
<template #default="{ row }">
<el-tag :type="statusType(row.status)" effect="light">{{
statusLabel(row.status)
}}</el-tag>
</template>
</el-table-column>
<el-table-column label="渠道单号" min-width="170" show-overflow-tooltip>
<template #default="{ row }">
<span class="mono muted">{{ row.provider_order_id || '-' }}</span>
</template>
</el-table-column>
<el-table-column label="创建时间" width="170">
<template #default="{ row }">{{ formatDateTime(row.created_at) }}</template>
</el-table-column>
<el-table-column label="操作" width="150" fixed="right">
<template #default="{ row }">
<el-button link type="primary" :icon="View" @click="openDetail(row)">详情</el-button>
<el-button
v-if="!['paid', 'failed', 'closed'].includes(row.status)"
link
type="success"
:icon="Refresh"
:loading="refreshingID === row.id"
@click="refreshRecord(row)"
>
刷状态
</el-button>
</template>
</el-table-column>
</el-table>
<div class="pagination-row">
<el-pagination
v-model:current-page="page"
v-model:page-size="pageSize"
:total="total"
:page-sizes="[10, 20, 50, 100]"
layout="total, sizes, prev, pager, next, jumper"
@current-change="loadRecords"
@size-change="loadRecords"
/>
</div>
</div>
<el-dialog v-model="detailVisible" title="测试支付详情" width="720px" append-to-body>
<div v-if="activeRecord" v-loading="detailLoading" class="detail-shell">
<el-descriptions :column="2" border>
<el-descriptions-item label="测试单号">{{ activeRecord.test_no }}</el-descriptions-item>
<el-descriptions-item label="状态">
<el-tag :type="statusType(activeRecord.status)">{{
statusLabel(activeRecord.status)
}}</el-tag>
</el-descriptions-item>
<el-descriptions-item label="支付配置">{{
activeRecord.config_name
}}</el-descriptions-item>
<el-descriptions-item label="服务商">{{
providerLabel(activeRecord.provider)
}}</el-descriptions-item>
<el-descriptions-item label="商户号">{{ activeRecord.merchant_id }}</el-descriptions-item>
<el-descriptions-item label="支付方式">{{
payWayLabel(activeRecord.pay_way)
}}</el-descriptions-item>
<el-descriptions-item label="测试金额">{{
money(activeRecord.amount_cent)
}}</el-descriptions-item>
<el-descriptions-item label="环境">{{
environmentLabel(activeRecord.environment)
}}</el-descriptions-item>
<el-descriptions-item label="渠道订单号" :span="2">
{{ activeRecord.provider_order_id || '-' }}
</el-descriptions-item>
<el-descriptions-item label="错误信息" :span="2">
{{ activeRecord.error_message || '-' }}
</el-descriptions-item>
<el-descriptions-item label="创建时间">{{
formatDateTime(activeRecord.created_at)
}}</el-descriptions-item>
<el-descriptions-item label="支付时间">
{{ activeRecord.paid_at ? formatDateTime(activeRecord.paid_at) : '-' }}
</el-descriptions-item>
</el-descriptions>
<div v-if="hasChainPayloads" class="payload-grid">
<div v-if="activeRecord.create_request" class="payload-item">
<h4>下单请求</h4>
<pre class="payload-code">{{ jsonText(activeRecord.create_request) }}</pre>
</div>
<div v-if="activeRecord.create_response" class="payload-item">
<h4>下单响应</h4>
<pre class="payload-code">{{ jsonText(activeRecord.create_response) }}</pre>
</div>
<div v-if="activeRecord.query_request" class="payload-item">
<h4>最近一次查单请求</h4>
<pre class="payload-code">{{ jsonText(activeRecord.query_request) }}</pre>
</div>
<div v-if="activeRecord.query_response" class="payload-item">
<h4>最近一次查单响应</h4>
<pre class="payload-code">{{ jsonText(activeRecord.query_response) }}</pre>
</div>
<div v-if="activeRecord.notify_request" class="payload-item">
<h4>支付回调请求</h4>
<pre class="payload-code">{{ jsonText(activeRecord.notify_request) }}</pre>
</div>
<div v-if="activeRecord.notify_result" class="payload-item">
<h4>回调处理结果</h4>
<pre class="payload-code">{{ jsonText(activeRecord.notify_result) }}</pre>
</div>
<div v-if="activeRecord.notify_ack" class="payload-item">
<h4>返回渠道应答</h4>
<pre class="payload-code">{{ activeRecord.notify_ack }}</pre>
</div>
</div>
<div v-else-if="activeRecord.raw_request || activeRecord.raw_response" class="payload-grid">
<div v-if="activeRecord.raw_request" class="payload-item">
<h4>历史下单请求</h4>
<pre class="payload-code">{{ jsonText(activeRecord.raw_request) }}</pre>
</div>
<div v-if="activeRecord.raw_response" class="payload-item">
<h4>历史渠道响应</h4>
<pre class="payload-code">{{ jsonText(activeRecord.raw_response) }}</pre>
</div>
</div>
<div v-else class="payload-empty">暂无报文</div>
</div>
</el-dialog>
</el-drawer>
</template>
<style scoped>
.records-shell {
display: flex;
flex-direction: column;
gap: 16px;
}
.filter-bar {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 10px;
}
.filter-select {
width: 160px;
}
.filter-input {
width: 210px;
}
.records-table {
width: 100%;
}
.mono {
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
font-size: 12px;
}
.muted {
color: #64748b;
}
.provider-cell {
display: flex;
flex-direction: column;
gap: 2px;
}
.provider-cell small {
color: #94a3b8;
}
.pagination-row {
display: flex;
justify-content: flex-end;
}
.detail-shell {
display: flex;
flex-direction: column;
gap: 18px;
}
.payload-item {
min-width: 0;
}
.payload-empty {
padding: 24px;
border: 1px dashed #cbd5e1;
border-radius: 10px;
color: #94a3b8;
text-align: center;
}
.payload-grid {
display: grid;
grid-template-columns: minmax(0, 1fr);
gap: 14px;
}
.payload-grid h4 {
margin: 0 0 8px;
color: #475569;
font-size: 13px;
}
.payload-grid pre.payload-code {
box-sizing: border-box;
min-width: 0;
min-height: 180px;
max-height: 320px;
margin: 0;
overflow-x: hidden;
overflow-y: auto;
white-space: pre-wrap;
word-break: break-all;
overflow-wrap: anywhere;
border-radius: 10px;
background: #0f172a !important;
color: #e2e8f0 !important;
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
font-size: 12px;
padding: 12px;
}
</style>
@@ -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<PaymentConfig[]>([])
@@ -34,6 +38,9 @@ const backupFileInput = ref<HTMLInputElement | null>(null)
const dialogVisible = ref(false)
const dialogMode = ref<'create' | 'edit' | 'view'>('create')
const currentConfig = ref<PaymentConfig | null>(null)
const testDialogVisible = ref(false)
const testConfig = ref<PaymentConfig | null>(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) {
</div>
<div class="toolbar-actions">
<el-button :icon="Tickets" @click="testRecordsVisible = true">测试支付记录</el-button>
<el-button :icon="Upload" :loading="importing" @click="handleImportBackup">
导入备份
</el-button>
@@ -448,9 +461,17 @@ function deleteDisabledReason(row: PaymentConfig) {
<span v-else class="standby-badge">备用</span>
</template>
</el-table-column>
<el-table-column label="操作" width="226" class-name="operation-column">
<el-table-column label="操作" width="286" class-name="operation-column">
<template #default="{ row }">
<div class="action-buttons">
<el-button
class="action-button test"
size="small"
:icon="VideoPlay"
@click="handleTest(row)"
>
测试
</el-button>
<el-button
class="action-button view"
size="small"
@@ -506,6 +527,9 @@ function deleteDisabledReason(row: PaymentConfig) {
@close="handleDialogClose"
@saved="handleSaved"
/>
<PaymentConfigTestDialog v-model="testDialogVisible" :config="testConfig" />
<PaymentConfigTestRecordsDrawer v-model="testRecordsVisible" :configs="configs" />
</div>
</template>
@@ -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;