chore(init): 初始化解忧商行项目并完成 Phase 0 基座
This commit is contained in:
@@ -0,0 +1,27 @@
|
||||
package paymentconfig
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"hfb_sys/backend/internal/model"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func appendAuditLog(tx *gorm.DB, actorID uint64, action string, bizID uint64, meta AuditMeta, detail map[string]any) error {
|
||||
detailJSON, err := json.Marshal(detail)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
log := model.AuditLog{
|
||||
ActorType: "admin",
|
||||
ActorID: actorID,
|
||||
Action: action,
|
||||
BizType: "payment_config",
|
||||
BizID: &bizID,
|
||||
IP: meta.IP,
|
||||
UserAgent: meta.UserAgent,
|
||||
Detail: detailJSON,
|
||||
}
|
||||
return tx.Create(&log).Error
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
package paymentconfig
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/model"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
// ExportBackup 导出所有支付配置备份,包含解密后的密钥。
|
||||
func (r *Repository) ExportBackup(ctx context.Context, actorID uint64, meta AuditMeta) (*ExportBackup, error) {
|
||||
var backup *ExportBackup
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var items []model.PaymentMerchantConfig
|
||||
if err := tx.Order("is_default DESC, id DESC").Find(&items).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
configs := make([]ConfigDTO, 0, len(items))
|
||||
for _, item := range items {
|
||||
dto, err := r.toDTO(item, true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
configs = append(configs, dto)
|
||||
}
|
||||
|
||||
exportedAt := time.Now().Format(time.RFC3339)
|
||||
backup = &ExportBackup{
|
||||
Type: "payment_config_backup",
|
||||
Version: 1,
|
||||
ExportedAt: exportedAt,
|
||||
ExportedBy: actorID,
|
||||
Total: len(configs),
|
||||
Configs: configs,
|
||||
}
|
||||
|
||||
return appendAuditLog(tx, actorID, "payment_config.export", 0, meta, map[string]any{
|
||||
"total": len(configs),
|
||||
"exported_at": exportedAt,
|
||||
})
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return backup, nil
|
||||
}
|
||||
|
||||
// ImportBackup 导入支付配置备份,按 provider + merchant_id + pay_way 更新或新增。
|
||||
func (r *Repository) ImportBackup(ctx context.Context, backup ExportBackup, actorID uint64, meta AuditMeta) (*ImportBackupResult, error) {
|
||||
if backup.Type != "payment_config_backup" || backup.Version <= 0 {
|
||||
return nil, ErrInvalidBackup
|
||||
}
|
||||
if len(backup.Configs) == 0 {
|
||||
return nil, ErrEmptyBackup
|
||||
}
|
||||
|
||||
activeKeys := backupActiveKeys(backup.Configs)
|
||||
result := &ImportBackupResult{Total: len(backup.Configs)}
|
||||
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
for payWay := range activeKeys {
|
||||
if err := deactivateOtherConfigs(tx, 0, actorID, payWay); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
for _, cfg := range backup.Configs {
|
||||
req := importCreateRequest(cfg, activeKeys)
|
||||
if err := r.validateCreateRequest(req); err != nil {
|
||||
return err
|
||||
}
|
||||
payWay := firstNonEmpty(req.PayWay, "ZFBZF")
|
||||
|
||||
encryptedSignKey, err := r.encryptor.Encrypt(req.SignKey)
|
||||
if err != nil {
|
||||
return ErrEncryptionFailed
|
||||
}
|
||||
encryptedNotifyKey, err := r.encryptor.Encrypt(req.NotifyKey)
|
||||
if err != nil {
|
||||
return ErrEncryptionFailed
|
||||
}
|
||||
|
||||
updates := map[string]any{
|
||||
"name": req.Name,
|
||||
"gateway_url": req.GatewayURL,
|
||||
"sign_key": encryptedSignKey,
|
||||
"notify_key": encryptedNotifyKey,
|
||||
"notify_url": req.NotifyURL,
|
||||
"jump_url": req.JumpURL,
|
||||
"pay_way": payWay,
|
||||
"jspay_flag": firstNonEmpty(req.JSPayFlag, "2"),
|
||||
"sign_type": firstNonEmpty(req.SignType, defaultSignType(req.Provider)),
|
||||
"extra_config": model.JSONMap(req.ExtraConfig),
|
||||
"is_default": req.IsDefault,
|
||||
"status": firstNonEmpty(req.Status, "active"),
|
||||
"environment": firstNonEmpty(req.Environment, "production"),
|
||||
"business_tags": model.JSONArray(req.BusinessTags),
|
||||
"updated_by": actorID,
|
||||
}
|
||||
|
||||
var existing model.PaymentMerchantConfig
|
||||
err = tx.Clauses(clause.Locking{Strength: "UPDATE"}).
|
||||
Where("provider = ? AND merchant_id = ? AND pay_way = ?", req.Provider, req.MerchantID, payWay).
|
||||
First(&existing).Error
|
||||
if err == nil {
|
||||
if err := tx.Model(&existing).Updates(updates).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
result.Updated++
|
||||
continue
|
||||
}
|
||||
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return err
|
||||
}
|
||||
|
||||
createdBy := actorID
|
||||
item := model.PaymentMerchantConfig{
|
||||
Name: req.Name,
|
||||
Provider: req.Provider,
|
||||
MerchantID: req.MerchantID,
|
||||
GatewayURL: req.GatewayURL,
|
||||
SignKey: encryptedSignKey,
|
||||
NotifyKey: encryptedNotifyKey,
|
||||
NotifyURL: req.NotifyURL,
|
||||
JumpURL: req.JumpURL,
|
||||
PayWay: payWay,
|
||||
JSPayFlag: firstNonEmpty(req.JSPayFlag, "2"),
|
||||
SignType: firstNonEmpty(req.SignType, defaultSignType(req.Provider)),
|
||||
ExtraConfig: model.JSONMap(req.ExtraConfig),
|
||||
IsDefault: req.IsDefault,
|
||||
Status: firstNonEmpty(req.Status, "active"),
|
||||
Environment: firstNonEmpty(req.Environment, "production"),
|
||||
BusinessTags: req.BusinessTags,
|
||||
CreatedBy: &createdBy,
|
||||
UpdatedBy: &actorID,
|
||||
}
|
||||
if err := tx.Create(&item).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
result.Created++
|
||||
}
|
||||
|
||||
return appendAuditLog(tx, actorID, "payment_config.import", 0, meta, map[string]any{
|
||||
"total": result.Total,
|
||||
"created": result.Created,
|
||||
"updated": result.Updated,
|
||||
})
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// backupActiveKeys 提取备份中每个支付方式的启用配置键。
|
||||
func backupActiveKeys(configs []ConfigDTO) map[string]string {
|
||||
keys := make(map[string]string)
|
||||
for _, cfg := range configs {
|
||||
payWay := firstNonEmpty(cfg.PayWay, "ZFBZF")
|
||||
if _, exists := keys[payWay]; exists {
|
||||
continue
|
||||
}
|
||||
if cfg.Status == "active" || cfg.IsDefault {
|
||||
keys[payWay] = paymentConfigImportKey(cfg.Provider, cfg.MerchantID, payWay)
|
||||
}
|
||||
}
|
||||
return keys
|
||||
}
|
||||
|
||||
// importCreateRequest 将备份 DTO 转为创建请求,并保留每个支付方式唯一启用配置。
|
||||
func importCreateRequest(cfg ConfigDTO, activeKeys map[string]string) CreateRequest {
|
||||
status := cfg.Status
|
||||
if status == "" {
|
||||
status = "disabled"
|
||||
}
|
||||
payWay := firstNonEmpty(cfg.PayWay, "ZFBZF")
|
||||
activeKey := activeKeys[payWay]
|
||||
isActive := activeKey != "" && paymentConfigImportKey(cfg.Provider, cfg.MerchantID, payWay) == activeKey
|
||||
if isActive {
|
||||
status = "active"
|
||||
} else if status == "active" {
|
||||
status = "disabled"
|
||||
}
|
||||
|
||||
return CreateRequest{
|
||||
Name: cfg.Name,
|
||||
Provider: cfg.Provider,
|
||||
MerchantID: cfg.MerchantID,
|
||||
GatewayURL: cfg.GatewayURL,
|
||||
SignKey: cfg.SignKey,
|
||||
NotifyKey: cfg.NotifyKey,
|
||||
NotifyURL: cfg.NotifyURL,
|
||||
JumpURL: cfg.JumpURL,
|
||||
PayWay: payWay,
|
||||
JSPayFlag: cfg.JSPayFlag,
|
||||
SignType: cfg.SignType,
|
||||
ExtraConfig: cfg.ExtraConfig,
|
||||
IsDefault: isActive,
|
||||
Status: status,
|
||||
Environment: cfg.Environment,
|
||||
BusinessTags: cfg.BusinessTags,
|
||||
}
|
||||
}
|
||||
|
||||
// paymentConfigImportKey 生成导入去重键,同商户可按支付方式拆分为多条配置。
|
||||
func paymentConfigImportKey(provider string, merchantID string, payWay string) string {
|
||||
return provider + ":" + merchantID + ":" + payWay
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package paymentconfig
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrConfigNotFound = errors.New("payment config not found")
|
||||
ErrDuplicateDefault = errors.New("duplicate default config for provider")
|
||||
ErrInvalidProvider = errors.New("invalid payment provider")
|
||||
ErrInvalidPayWay = errors.New("invalid pay_way")
|
||||
ErrInvalidStatus = errors.New("invalid status")
|
||||
ErrInvalidBackup = errors.New("invalid payment config backup")
|
||||
ErrEmptyBackup = errors.New("payment config backup is empty")
|
||||
ErrCannotDeleteInUse = errors.New("cannot delete config in use")
|
||||
ErrEncryptionFailed = errors.New("encryption failed")
|
||||
ErrDecryptionFailed = errors.New("decryption failed")
|
||||
ErrNoActiveConfigFound = errors.New("no active config found for provider")
|
||||
ErrMerchantIDRequired = errors.New("merchant_id is required")
|
||||
ErrNameRequired = errors.New("name is required")
|
||||
ErrGatewayURLRequired = errors.New("gateway_url is required for leshua provider")
|
||||
ErrSignKeyRequired = errors.New("sign_key is required for leshua provider")
|
||||
ErrNotifyKeyRequired = errors.New("notify_key is required for leshua provider")
|
||||
ErrNotifyURLRequired = errors.New("notify_url is required for leshua provider")
|
||||
ErrInvalidSignType = errors.New("invalid sign_type")
|
||||
ErrAppIDRequired = errors.New("extra_config.app_id is required for lakala provider")
|
||||
ErrSerialNoRequired = errors.New("extra_config.serial_no is required for lakala provider")
|
||||
ErrTermNoRequired = errors.New("extra_config.term_no is required for lakala provider")
|
||||
ErrSecretIDRequired = errors.New("extra_config.secret_id is required for shuncheng provider")
|
||||
)
|
||||
|
||||
// DTO 数据传输对象
|
||||
type ConfigDTO struct {
|
||||
ID uint64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Provider string `json:"provider"`
|
||||
MerchantID string `json:"merchant_id"`
|
||||
GatewayURL string `json:"gateway_url"`
|
||||
SignKey string `json:"sign_key,omitempty"` // 默认不返回
|
||||
NotifyKey string `json:"notify_key,omitempty"` // 默认不返回
|
||||
NotifyURL string `json:"notify_url"`
|
||||
JumpURL string `json:"jump_url"`
|
||||
PayWay string `json:"pay_way"`
|
||||
JSPayFlag string `json:"jspay_flag"`
|
||||
SignType string `json:"sign_type"`
|
||||
ExtraConfig map[string]any `json:"extra_config"`
|
||||
IsDefault bool `json:"is_default"`
|
||||
Status string `json:"status"`
|
||||
Environment string `json:"environment"`
|
||||
BusinessTags []string `json:"business_tags"`
|
||||
ReferenceCount int64 `json:"reference_count"`
|
||||
TotalTransactions int64 `json:"total_transactions"`
|
||||
TotalAmountCent int64 `json:"total_amount_cent"`
|
||||
LastUsedAt *string `json:"last_used_at"`
|
||||
CreatedBy *uint64 `json:"created_by"`
|
||||
UpdatedBy *uint64 `json:"updated_by"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
}
|
||||
|
||||
// CreateRequest 创建支付配置请求
|
||||
type CreateRequest struct {
|
||||
Name string `json:"name" binding:"required"`
|
||||
Provider string `json:"provider" binding:"required,oneof=leshua lakala shuncheng mock"`
|
||||
MerchantID string `json:"merchant_id" binding:"required"`
|
||||
GatewayURL string `json:"gateway_url"`
|
||||
SignKey string `json:"sign_key"`
|
||||
NotifyKey string `json:"notify_key"`
|
||||
NotifyURL string `json:"notify_url"`
|
||||
JumpURL string `json:"jump_url"`
|
||||
PayWay string `json:"pay_way"`
|
||||
JSPayFlag string `json:"jspay_flag"`
|
||||
SignType string `json:"sign_type"`
|
||||
ExtraConfig map[string]any `json:"extra_config"`
|
||||
IsDefault bool `json:"is_default"`
|
||||
Status string `json:"status" binding:"omitempty,oneof=active disabled testing"`
|
||||
Environment string `json:"environment" binding:"omitempty,oneof=production sandbox"`
|
||||
BusinessTags []string `json:"business_tags"`
|
||||
}
|
||||
|
||||
// UpdateRequest 更新支付配置请求
|
||||
type UpdateRequest struct {
|
||||
Name *string `json:"name"`
|
||||
MerchantID *string `json:"merchant_id"`
|
||||
GatewayURL *string `json:"gateway_url"`
|
||||
SignKey *string `json:"sign_key"`
|
||||
NotifyKey *string `json:"notify_key"`
|
||||
NotifyURL *string `json:"notify_url"`
|
||||
JumpURL *string `json:"jump_url"`
|
||||
PayWay *string `json:"pay_way"`
|
||||
JSPayFlag *string `json:"jspay_flag"`
|
||||
SignType *string `json:"sign_type"`
|
||||
ExtraConfig map[string]any `json:"extra_config"`
|
||||
IsDefault *bool `json:"is_default"`
|
||||
Status *string `json:"status"`
|
||||
Environment *string `json:"environment"`
|
||||
BusinessTags []string `json:"business_tags"`
|
||||
}
|
||||
|
||||
// ListQuery 列表查询参数
|
||||
type ListQuery struct {
|
||||
Provider string `form:"provider"`
|
||||
PayWay string `form:"pay_way"`
|
||||
Status string `form:"status"`
|
||||
Environment string `form:"environment"`
|
||||
Page int `form:"page"`
|
||||
PageSize int `form:"page_size"`
|
||||
}
|
||||
|
||||
// ListResponse 列表响应
|
||||
type ListResponse struct {
|
||||
Items []ConfigDTO `json:"items"`
|
||||
Total int64 `json:"total"`
|
||||
Page int `json:"page"`
|
||||
PageSize int `json:"page_size"`
|
||||
}
|
||||
|
||||
// ExportBackup 支付配置备份导出内容。
|
||||
type ExportBackup struct {
|
||||
Type string `json:"type"`
|
||||
Version int `json:"version"`
|
||||
ExportedAt string `json:"exported_at"`
|
||||
ExportedBy uint64 `json:"exported_by"`
|
||||
Total int `json:"total"`
|
||||
Configs []ConfigDTO `json:"configs"`
|
||||
}
|
||||
|
||||
// ImportBackupResult 支付配置备份导入结果。
|
||||
type ImportBackupResult struct {
|
||||
Total int `json:"total"`
|
||||
Created int `json:"created"`
|
||||
Updated int `json:"updated"`
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package paymentconfig
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"io"
|
||||
)
|
||||
|
||||
// Encryptor 密钥加密器接口
|
||||
type Encryptor interface {
|
||||
Encrypt(plaintext string) (string, error)
|
||||
Decrypt(ciphertext string) (string, error)
|
||||
}
|
||||
|
||||
// AESEncryptor AES 加密器
|
||||
type AESEncryptor struct {
|
||||
key []byte
|
||||
}
|
||||
|
||||
// NewAESEncryptor 创建 AES 加密器
|
||||
// key 必须是 16、24 或 32 字节(对应 AES-128、AES-192、AES-256)
|
||||
func NewAESEncryptor(key string) (*AESEncryptor, error) {
|
||||
keyBytes := []byte(key)
|
||||
if len(keyBytes) != 16 && len(keyBytes) != 24 && len(keyBytes) != 32 {
|
||||
return nil, errors.New("invalid key length: must be 16, 24, or 32 bytes")
|
||||
}
|
||||
return &AESEncryptor{key: keyBytes}, nil
|
||||
}
|
||||
|
||||
// Encrypt 加密明文(使用 AES-GCM)
|
||||
func (e *AESEncryptor) Encrypt(plaintext string) (string, error) {
|
||||
if plaintext == "" {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
block, err := aes.NewCipher(e.key)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
gcm, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
nonce := make([]byte, gcm.NonceSize())
|
||||
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
ciphertext := gcm.Seal(nonce, nonce, []byte(plaintext), nil)
|
||||
return base64.StdEncoding.EncodeToString(ciphertext), nil
|
||||
}
|
||||
|
||||
// Decrypt 解密密文(使用 AES-GCM)
|
||||
func (e *AESEncryptor) Decrypt(ciphertext string) (string, error) {
|
||||
if ciphertext == "" {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
ciphertextBytes, err := base64.StdEncoding.DecodeString(ciphertext)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
block, err := aes.NewCipher(e.key)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
gcm, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
nonceSize := gcm.NonceSize()
|
||||
if len(ciphertextBytes) < nonceSize {
|
||||
return "", errors.New("ciphertext too short")
|
||||
}
|
||||
|
||||
nonce, ciphertextBytes := ciphertextBytes[:nonceSize], ciphertextBytes[nonceSize:]
|
||||
plaintext, err := gcm.Open(nil, nonce, ciphertextBytes, nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return string(plaintext), nil
|
||||
}
|
||||
|
||||
// MockEncryptor 模拟加密器(用于测试)
|
||||
type MockEncryptor struct{}
|
||||
|
||||
func (e *MockEncryptor) Encrypt(plaintext string) (string, error) {
|
||||
return plaintext, nil
|
||||
}
|
||||
|
||||
func (e *MockEncryptor) Decrypt(ciphertext string) (string, error) {
|
||||
return ciphertext, nil
|
||||
}
|
||||
@@ -0,0 +1,300 @@
|
||||
package paymentconfig
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/middleware"
|
||||
"hfb_sys/backend/pkg/response"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
service *Service
|
||||
}
|
||||
|
||||
func NewHandler(service *Service) *Handler {
|
||||
return &Handler{service: service}
|
||||
}
|
||||
|
||||
// List 获取支付配置列表
|
||||
// @Summary 获取支付配置列表
|
||||
// @Tags 管理后台-支付配置
|
||||
// @Param provider query string false "支付服务商"
|
||||
// @Param pay_way query string false "支付方式"
|
||||
// @Param status query string false "状态"
|
||||
// @Param environment query string false "环境"
|
||||
// @Param page query int false "页码"
|
||||
// @Param page_size query int false "每页数量"
|
||||
// @Success 200 {object} response.Response{data=ListResponse}
|
||||
// @Router /admin/payment-configs [get]
|
||||
func (h *Handler) List(c *gin.Context) {
|
||||
var query ListQuery
|
||||
if err := c.ShouldBindQuery(&query); err != nil {
|
||||
response.BadRequest(c, "参数错误")
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := h.service.List(c.Request.Context(), query)
|
||||
if err != nil {
|
||||
response.RecordError(c, err)
|
||||
response.Error(c, http.StatusInternalServerError, "internal_error", "查询失败")
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, resp)
|
||||
}
|
||||
|
||||
// Get 获取单个支付配置
|
||||
// @Summary 获取单个支付配置
|
||||
// @Tags 管理后台-支付配置
|
||||
// @Param id path int true "配置ID"
|
||||
// @Param include_secret query bool false "是否包含密钥"
|
||||
// @Success 200 {object} response.Response{data=ConfigDTO}
|
||||
// @Router /admin/payment-configs/{id} [get]
|
||||
func (h *Handler) Get(c *gin.Context) {
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
response.BadRequest(c, "无效的ID")
|
||||
return
|
||||
}
|
||||
|
||||
includeSecret := c.Query("include_secret") == "true"
|
||||
var actorID uint64
|
||||
if includeSecret {
|
||||
var ok bool
|
||||
actorID, ok = currentAdminID(c)
|
||||
if !ok {
|
||||
response.Unauthorized(c, "未授权")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
config, err := h.service.Get(c.Request.Context(), id, includeSecret, actorID, auditMeta(c))
|
||||
if err == ErrConfigNotFound {
|
||||
response.NotFound(c, "配置不存在")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.RecordError(c, err)
|
||||
response.Error(c, http.StatusInternalServerError, "internal_error", "查询失败")
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, config)
|
||||
}
|
||||
|
||||
// ExportBackup 导出支付配置备份
|
||||
// @Summary 导出支付配置备份
|
||||
// @Tags 管理后台-支付配置
|
||||
// @Success 200 {file} file "支付配置备份 JSON"
|
||||
// @Router /admin/payment-configs/export [get]
|
||||
func (h *Handler) ExportBackup(c *gin.Context) {
|
||||
adminID, ok := currentAdminID(c)
|
||||
if !ok {
|
||||
response.Unauthorized(c, "未授权")
|
||||
return
|
||||
}
|
||||
|
||||
backup, err := h.service.ExportBackup(c.Request.Context(), adminID, auditMeta(c))
|
||||
if err == ErrDecryptionFailed {
|
||||
response.RecordError(c, err)
|
||||
response.Error(c, http.StatusInternalServerError, "decrypt_failed", "密钥解密失败")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.RecordError(c, err)
|
||||
response.Error(c, http.StatusInternalServerError, "internal_error", "导出失败")
|
||||
return
|
||||
}
|
||||
|
||||
data, err := json.MarshalIndent(backup, "", " ")
|
||||
if err != nil {
|
||||
response.RecordError(c, err)
|
||||
response.Error(c, http.StatusInternalServerError, "internal_error", "导出失败")
|
||||
return
|
||||
}
|
||||
|
||||
filename := "payment-config-backup-" + time.Now().Format("20060102-150405") + ".json"
|
||||
contentType := "application/json; charset=utf-8"
|
||||
c.Header("Content-Disposition", `attachment; filename="`+filename+`"`)
|
||||
c.Data(http.StatusOK, contentType, data)
|
||||
}
|
||||
|
||||
// ImportBackup 导入支付配置备份
|
||||
// @Summary 导入支付配置备份
|
||||
// @Tags 管理后台-支付配置
|
||||
// @Param body body ExportBackup true "支付配置备份 JSON"
|
||||
// @Success 200 {object} response.Response{data=ImportBackupResult}
|
||||
// @Router /admin/payment-configs/import [post]
|
||||
func (h *Handler) ImportBackup(c *gin.Context) {
|
||||
adminID, ok := currentAdminID(c)
|
||||
if !ok {
|
||||
response.Unauthorized(c, "未授权")
|
||||
return
|
||||
}
|
||||
|
||||
var backup ExportBackup
|
||||
if err := c.ShouldBindJSON(&backup); err != nil {
|
||||
response.BadRequest(c, "备份文件格式错误")
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.service.ImportBackup(c.Request.Context(), backup, adminID, auditMeta(c))
|
||||
if err == ErrInvalidBackup || err == ErrEmptyBackup || err == ErrInvalidProvider ||
|
||||
err == ErrNameRequired || err == ErrMerchantIDRequired || err == ErrGatewayURLRequired ||
|
||||
err == ErrSignKeyRequired || err == ErrNotifyKeyRequired || err == ErrNotifyURLRequired ||
|
||||
err == ErrInvalidSignType || err == ErrInvalidStatus || err == ErrInvalidPayWay || err == ErrAppIDRequired ||
|
||||
err == ErrSerialNoRequired || err == ErrTermNoRequired {
|
||||
response.BadRequest(c, err.Error())
|
||||
return
|
||||
}
|
||||
if err == ErrEncryptionFailed {
|
||||
response.RecordError(c, err)
|
||||
response.Error(c, http.StatusInternalServerError, "encrypt_failed", "密钥加密失败")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.RecordError(c, err)
|
||||
response.Error(c, http.StatusInternalServerError, "internal_error", "导入失败")
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, result)
|
||||
}
|
||||
|
||||
// Create 创建支付配置
|
||||
// @Summary 创建支付配置
|
||||
// @Tags 管理后台-支付配置
|
||||
// @Param body body CreateRequest true "创建请求"
|
||||
// @Success 200 {object} response.Response{data=ConfigDTO}
|
||||
// @Router /admin/payment-configs [post]
|
||||
func (h *Handler) Create(c *gin.Context) {
|
||||
adminID, ok := currentAdminID(c)
|
||||
if !ok {
|
||||
response.Unauthorized(c, "未授权")
|
||||
return
|
||||
}
|
||||
|
||||
var req CreateRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.BadRequest(c, "参数错误: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
config, err := h.service.Create(c.Request.Context(), req, adminID, auditMeta(c))
|
||||
if err == ErrNameRequired || err == ErrMerchantIDRequired || err == ErrGatewayURLRequired ||
|
||||
err == ErrSignKeyRequired || err == ErrNotifyKeyRequired || err == ErrInvalidProvider ||
|
||||
err == ErrNotifyURLRequired || err == ErrInvalidSignType || err == ErrInvalidPayWay || err == ErrAppIDRequired ||
|
||||
err == ErrInvalidStatus || err == ErrSerialNoRequired || err == ErrTermNoRequired {
|
||||
response.BadRequest(c, err.Error())
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.RecordError(c, err)
|
||||
response.Error(c, http.StatusInternalServerError, "internal_error", "创建失败")
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, config)
|
||||
}
|
||||
|
||||
// Update 更新支付配置
|
||||
// @Summary 更新支付配置
|
||||
// @Tags 管理后台-支付配置
|
||||
// @Param id path int true "配置ID"
|
||||
// @Param body body UpdateRequest true "更新请求"
|
||||
// @Success 200 {object} response.Response{data=ConfigDTO}
|
||||
// @Router /admin/payment-configs/{id} [put]
|
||||
func (h *Handler) Update(c *gin.Context) {
|
||||
adminID, ok := currentAdminID(c)
|
||||
if !ok {
|
||||
response.Unauthorized(c, "未授权")
|
||||
return
|
||||
}
|
||||
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
response.BadRequest(c, "无效的ID")
|
||||
return
|
||||
}
|
||||
|
||||
var req UpdateRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.BadRequest(c, "参数错误: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
config, err := h.service.Update(c.Request.Context(), id, req, adminID, auditMeta(c))
|
||||
if err == ErrConfigNotFound {
|
||||
response.NotFound(c, "配置不存在")
|
||||
return
|
||||
}
|
||||
if err == ErrInvalidSignType || err == ErrInvalidStatus || err == ErrInvalidPayWay || err == ErrNotifyURLRequired {
|
||||
response.BadRequest(c, err.Error())
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.RecordError(c, err)
|
||||
response.Error(c, http.StatusInternalServerError, "internal_error", "更新失败")
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, config)
|
||||
}
|
||||
|
||||
// Delete 删除支付配置
|
||||
// @Summary 删除支付配置
|
||||
// @Tags 管理后台-支付配置
|
||||
// @Param id path int true "配置ID"
|
||||
// @Success 200 {object} response.Response
|
||||
// @Router /admin/payment-configs/{id} [delete]
|
||||
func (h *Handler) Delete(c *gin.Context) {
|
||||
adminID, ok := currentAdminID(c)
|
||||
if !ok {
|
||||
response.Unauthorized(c, "未授权")
|
||||
return
|
||||
}
|
||||
|
||||
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
response.BadRequest(c, "无效的ID")
|
||||
return
|
||||
}
|
||||
|
||||
err = h.service.Delete(c.Request.Context(), id, adminID, auditMeta(c))
|
||||
if err == ErrConfigNotFound {
|
||||
response.NotFound(c, "配置不存在")
|
||||
return
|
||||
}
|
||||
if err == ErrCannotDeleteInUse {
|
||||
response.BadRequest(c, "配置正在使用中,无法删除")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.RecordError(c, err)
|
||||
response.Error(c, http.StatusInternalServerError, "internal_error", "删除失败")
|
||||
return
|
||||
}
|
||||
|
||||
response.OK(c, gin.H{"message": "删除成功"})
|
||||
}
|
||||
|
||||
func currentAdminID(c *gin.Context) (uint64, bool) {
|
||||
val, exists := c.Get(middleware.ContextAdminID)
|
||||
if !exists {
|
||||
return 0, false
|
||||
}
|
||||
id, ok := val.(uint64)
|
||||
return id, ok
|
||||
}
|
||||
|
||||
func auditMeta(c *gin.Context) AuditMeta {
|
||||
return AuditMeta{
|
||||
IP: c.ClientIP(),
|
||||
UserAgent: c.Request.UserAgent(),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,336 @@
|
||||
package paymentconfig
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"hfb_sys/backend/internal/model"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
// Create 创建配置
|
||||
func (r *Repository) Create(ctx context.Context, req CreateRequest, actorID uint64, meta AuditMeta) (*ConfigDTO, error) {
|
||||
req = normalizeCreateRequest(req)
|
||||
// 验证必填字段
|
||||
if err := r.validateCreateRequest(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var dto ConfigDTO
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
// 加密密钥
|
||||
encryptedSignKey, err := r.encryptor.Encrypt(req.SignKey)
|
||||
if err != nil {
|
||||
return ErrEncryptionFailed
|
||||
}
|
||||
encryptedNotifyKey, err := r.encryptor.Encrypt(req.NotifyKey)
|
||||
if err != nil {
|
||||
return ErrEncryptionFailed
|
||||
}
|
||||
|
||||
status := req.Status
|
||||
if status == "" {
|
||||
status = "active"
|
||||
}
|
||||
environment := req.Environment
|
||||
if environment == "" {
|
||||
environment = "production"
|
||||
}
|
||||
payWay := firstNonEmpty(req.PayWay, "ZFBZF")
|
||||
isDefault := req.IsDefault
|
||||
if status == "active" {
|
||||
if err := deactivateOtherConfigs(tx, 0, actorID, payWay); err != nil {
|
||||
return err
|
||||
}
|
||||
isDefault = true
|
||||
} else {
|
||||
isDefault = false
|
||||
}
|
||||
|
||||
item := model.PaymentMerchantConfig{
|
||||
Name: req.Name,
|
||||
Provider: req.Provider,
|
||||
MerchantID: req.MerchantID,
|
||||
GatewayURL: req.GatewayURL,
|
||||
SignKey: encryptedSignKey,
|
||||
NotifyKey: encryptedNotifyKey,
|
||||
NotifyURL: req.NotifyURL,
|
||||
JumpURL: req.JumpURL,
|
||||
PayWay: payWay,
|
||||
JSPayFlag: firstNonEmpty(req.JSPayFlag, "2"),
|
||||
SignType: firstNonEmpty(req.SignType, defaultSignType(req.Provider)),
|
||||
ExtraConfig: req.ExtraConfig,
|
||||
IsDefault: isDefault,
|
||||
Status: status,
|
||||
Environment: environment,
|
||||
BusinessTags: req.BusinessTags,
|
||||
CreatedBy: &actorID,
|
||||
UpdatedBy: &actorID,
|
||||
}
|
||||
|
||||
if err := tx.Create(&item).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 记录审计日志
|
||||
if err := appendAuditLog(tx, actorID, "payment_config.create", item.ID, meta, map[string]any{
|
||||
"name": item.Name,
|
||||
"provider": item.Provider,
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
dto, err = r.toDTO(item, false)
|
||||
return err
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &dto, nil
|
||||
}
|
||||
|
||||
// Update 更新配置
|
||||
func (r *Repository) Update(ctx context.Context, id uint64, req UpdateRequest, actorID uint64, meta AuditMeta) (*ConfigDTO, error) {
|
||||
req = normalizeUpdateRequest(req)
|
||||
if req.SignType != nil && *req.SignType != "" && !isValidSignType(*req.SignType) {
|
||||
return nil, ErrInvalidSignType
|
||||
}
|
||||
if req.PayWay != nil && !isValidPayWay(*req.PayWay) {
|
||||
return nil, ErrInvalidPayWay
|
||||
}
|
||||
if req.Status != nil && !isValidStatus(*req.Status) {
|
||||
return nil, ErrInvalidStatus
|
||||
}
|
||||
if req.NotifyURL != nil && *req.NotifyURL == "" {
|
||||
return nil, ErrNotifyURLRequired
|
||||
}
|
||||
|
||||
var dto ConfigDTO
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var item model.PaymentMerchantConfig
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", id).First(&item).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrConfigNotFound
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
updates := make(map[string]any)
|
||||
if req.Name != nil {
|
||||
updates["name"] = *req.Name
|
||||
}
|
||||
if req.MerchantID != nil {
|
||||
updates["merchant_id"] = *req.MerchantID
|
||||
}
|
||||
if req.GatewayURL != nil {
|
||||
updates["gateway_url"] = *req.GatewayURL
|
||||
}
|
||||
if req.SignKey != nil {
|
||||
encrypted, err := r.encryptor.Encrypt(*req.SignKey)
|
||||
if err != nil {
|
||||
return ErrEncryptionFailed
|
||||
}
|
||||
updates["sign_key"] = encrypted
|
||||
}
|
||||
if req.NotifyKey != nil {
|
||||
encrypted, err := r.encryptor.Encrypt(*req.NotifyKey)
|
||||
if err != nil {
|
||||
return ErrEncryptionFailed
|
||||
}
|
||||
updates["notify_key"] = encrypted
|
||||
}
|
||||
if req.NotifyURL != nil {
|
||||
updates["notify_url"] = *req.NotifyURL
|
||||
}
|
||||
if req.JumpURL != nil {
|
||||
updates["jump_url"] = *req.JumpURL
|
||||
}
|
||||
if req.PayWay != nil {
|
||||
updates["pay_way"] = firstNonEmpty(*req.PayWay, "ZFBZF")
|
||||
}
|
||||
if req.JSPayFlag != nil {
|
||||
updates["jspay_flag"] = *req.JSPayFlag
|
||||
}
|
||||
if req.SignType != nil {
|
||||
updates["sign_type"] = *req.SignType
|
||||
}
|
||||
if req.ExtraConfig != nil {
|
||||
updates["extra_config"] = model.JSONMap(req.ExtraConfig)
|
||||
}
|
||||
if req.IsDefault != nil {
|
||||
updates["is_default"] = *req.IsDefault
|
||||
}
|
||||
if req.Status != nil {
|
||||
updates["status"] = *req.Status
|
||||
}
|
||||
if req.Environment != nil {
|
||||
updates["environment"] = *req.Environment
|
||||
}
|
||||
if req.BusinessTags != nil {
|
||||
updates["business_tags"] = model.JSONArray(req.BusinessTags)
|
||||
}
|
||||
updates["updated_by"] = actorID
|
||||
|
||||
finalStatus := item.Status
|
||||
if req.Status != nil {
|
||||
finalStatus = *req.Status
|
||||
}
|
||||
finalPayWay := item.PayWay
|
||||
if req.PayWay != nil && *req.PayWay != "" {
|
||||
finalPayWay = *req.PayWay
|
||||
}
|
||||
if finalPayWay == "" {
|
||||
finalPayWay = "ZFBZF"
|
||||
}
|
||||
if finalStatus == "active" {
|
||||
if err := deactivateOtherConfigs(tx, id, actorID, finalPayWay); err != nil {
|
||||
return err
|
||||
}
|
||||
updates["status"] = "active"
|
||||
updates["is_default"] = true
|
||||
} else {
|
||||
updates["is_default"] = false
|
||||
}
|
||||
|
||||
if err := tx.Model(&item).Updates(updates).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 记录审计日志
|
||||
if err := appendAuditLog(tx, actorID, "payment_config.update", item.ID, meta, map[string]any{
|
||||
"updates": updates,
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 重新查询
|
||||
if err := tx.Where("id = ?", id).First(&item).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var dtoErr error
|
||||
dto, dtoErr = r.toDTO(item, false)
|
||||
return dtoErr
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &dto, nil
|
||||
}
|
||||
|
||||
// normalizeCreateRequest 清理后台创建配置时常见的复制粘贴空白,避免隐藏字符进入渠道请求。
|
||||
func normalizeCreateRequest(req CreateRequest) CreateRequest {
|
||||
req.Name = strings.TrimSpace(req.Name)
|
||||
req.Provider = strings.TrimSpace(req.Provider)
|
||||
req.MerchantID = strings.TrimSpace(req.MerchantID)
|
||||
req.GatewayURL = strings.TrimSpace(req.GatewayURL)
|
||||
req.SignKey = strings.TrimSpace(req.SignKey)
|
||||
req.NotifyKey = strings.TrimSpace(req.NotifyKey)
|
||||
req.NotifyURL = strings.TrimSpace(req.NotifyURL)
|
||||
req.JumpURL = strings.TrimSpace(req.JumpURL)
|
||||
req.PayWay = strings.TrimSpace(req.PayWay)
|
||||
req.JSPayFlag = strings.TrimSpace(req.JSPayFlag)
|
||||
req.SignType = strings.TrimSpace(req.SignType)
|
||||
req.Status = strings.TrimSpace(req.Status)
|
||||
req.Environment = strings.TrimSpace(req.Environment)
|
||||
req.ExtraConfig = trimExtraConfig(req.ExtraConfig)
|
||||
return req
|
||||
}
|
||||
|
||||
// normalizeUpdateRequest 清理后台更新配置时提交的字符串字段。
|
||||
func normalizeUpdateRequest(req UpdateRequest) UpdateRequest {
|
||||
trimStringPtr(req.Name)
|
||||
trimStringPtr(req.MerchantID)
|
||||
trimStringPtr(req.GatewayURL)
|
||||
trimStringPtr(req.SignKey)
|
||||
trimStringPtr(req.NotifyKey)
|
||||
trimStringPtr(req.NotifyURL)
|
||||
trimStringPtr(req.JumpURL)
|
||||
trimStringPtr(req.PayWay)
|
||||
trimStringPtr(req.JSPayFlag)
|
||||
trimStringPtr(req.SignType)
|
||||
trimStringPtr(req.Status)
|
||||
trimStringPtr(req.Environment)
|
||||
req.ExtraConfig = trimExtraConfig(req.ExtraConfig)
|
||||
return req
|
||||
}
|
||||
|
||||
// trimStringPtr 原地清理可选字符串字段。
|
||||
func trimStringPtr(value *string) {
|
||||
if value == nil {
|
||||
return
|
||||
}
|
||||
*value = strings.TrimSpace(*value)
|
||||
}
|
||||
|
||||
// trimExtraConfig 清理扩展配置里的字符串值,证书和私钥内部换行会被保留。
|
||||
func trimExtraConfig(config map[string]any) map[string]any {
|
||||
if config == nil {
|
||||
return nil
|
||||
}
|
||||
trimmed := make(map[string]any, len(config))
|
||||
for key, value := range config {
|
||||
if text, ok := value.(string); ok {
|
||||
trimmed[key] = strings.TrimSpace(text)
|
||||
continue
|
||||
}
|
||||
trimmed[key] = value
|
||||
}
|
||||
return trimmed
|
||||
}
|
||||
|
||||
// Delete 删除配置
|
||||
func (r *Repository) Delete(ctx context.Context, id uint64, actorID uint64, meta AuditMeta) error {
|
||||
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var item model.PaymentMerchantConfig
|
||||
if err := tx.Where("id = ?", id).First(&item).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrConfigNotFound
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
var usedCount int64
|
||||
usedDB := tx.Model(&model.PaymentOrder{}).
|
||||
Where("payment_config_id = ?", item.ID).
|
||||
Or("(payment_config_id = ? OR payment_config_id IS NULL) AND provider = ? AND merchant_id = ? AND pay_way = ?", 0, item.Provider, item.MerchantID, item.PayWay)
|
||||
if err := usedDB.
|
||||
Count(&usedCount).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if usedCount > 0 {
|
||||
return ErrCannotDeleteInUse
|
||||
}
|
||||
|
||||
if err := tx.Delete(&item).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 记录审计日志
|
||||
return appendAuditLog(tx, actorID, "payment_config.delete", item.ID, meta, map[string]any{
|
||||
"name": item.Name,
|
||||
"provider": item.Provider,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// deactivateOtherConfigs 保证同一个支付方式同一时间只有一个启用配置。
|
||||
func deactivateOtherConfigs(tx *gorm.DB, activeID uint64, actorID uint64, payWay string) error {
|
||||
db := tx.Model(&model.PaymentMerchantConfig{}).
|
||||
Where("pay_way = ? AND (status = ? OR is_default = ?)", payWay, "active", true)
|
||||
if activeID > 0 {
|
||||
db = db.Where("id != ?", activeID)
|
||||
}
|
||||
return db.Updates(map[string]any{
|
||||
"status": "disabled",
|
||||
"is_default": false,
|
||||
"updated_by": actorID,
|
||||
}).Error
|
||||
}
|
||||
|
||||
// toDTO 转换为 DTO
|
||||
@@ -0,0 +1,73 @@
|
||||
package paymentconfig
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/model"
|
||||
)
|
||||
|
||||
// toDTO 转换为 DTO
|
||||
func (r *Repository) toDTO(item model.PaymentMerchantConfig, includeSecret bool) (ConfigDTO, error) {
|
||||
dto := ConfigDTO{
|
||||
ID: item.ID,
|
||||
Name: item.Name,
|
||||
Provider: item.Provider,
|
||||
MerchantID: item.MerchantID,
|
||||
GatewayURL: item.GatewayURL,
|
||||
NotifyURL: item.NotifyURL,
|
||||
JumpURL: item.JumpURL,
|
||||
PayWay: item.PayWay,
|
||||
JSPayFlag: item.JSPayFlag,
|
||||
SignType: item.SignType,
|
||||
ExtraConfig: item.ExtraConfig,
|
||||
IsDefault: item.IsDefault,
|
||||
Status: item.Status,
|
||||
Environment: item.Environment,
|
||||
BusinessTags: item.BusinessTags,
|
||||
TotalTransactions: item.TotalTransactions,
|
||||
TotalAmountCent: item.TotalAmountCent,
|
||||
CreatedBy: item.CreatedBy,
|
||||
UpdatedBy: item.UpdatedBy,
|
||||
CreatedAt: item.CreatedAt.Format(time.RFC3339),
|
||||
UpdatedAt: item.UpdatedAt.Format(time.RFC3339),
|
||||
}
|
||||
|
||||
if item.LastUsedAt != nil {
|
||||
s := item.LastUsedAt.Format(time.RFC3339)
|
||||
dto.LastUsedAt = &s
|
||||
}
|
||||
|
||||
// 只有明确要求时才解密并返回密钥
|
||||
if includeSecret {
|
||||
signKey, err := r.encryptor.Decrypt(item.SignKey)
|
||||
if err != nil {
|
||||
return ConfigDTO{}, ErrDecryptionFailed
|
||||
}
|
||||
notifyKey, err := r.encryptor.Decrypt(item.NotifyKey)
|
||||
if err != nil {
|
||||
return ConfigDTO{}, ErrDecryptionFailed
|
||||
}
|
||||
dto.SignKey = signKey
|
||||
dto.NotifyKey = notifyKey
|
||||
}
|
||||
|
||||
return dto, nil
|
||||
}
|
||||
|
||||
// validateCreateRequest 验证创建请求
|
||||
|
||||
func firstNonEmpty(vals ...string) string {
|
||||
for _, v := range vals {
|
||||
if v != "" {
|
||||
return v
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func defaultSignType(provider string) string {
|
||||
if provider == "lakala" {
|
||||
return "SHA256withRSA"
|
||||
}
|
||||
return "MD5"
|
||||
}
|
||||
@@ -0,0 +1,353 @@
|
||||
package paymentconfig
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql/driver"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/model"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// List 获取配置列表
|
||||
func (r *Repository) List(ctx context.Context, query ListQuery) ([]ConfigDTO, int64, error) {
|
||||
var items []model.PaymentMerchantConfig
|
||||
var total int64
|
||||
|
||||
db := r.db.WithContext(ctx).Model(&model.PaymentMerchantConfig{})
|
||||
|
||||
// 过滤条件
|
||||
if query.Provider != "" {
|
||||
db = db.Where("provider = ?", query.Provider)
|
||||
}
|
||||
if query.PayWay != "" {
|
||||
db = db.Where("pay_way = ?", query.PayWay)
|
||||
}
|
||||
if query.Status != "" {
|
||||
db = db.Where("status = ?", query.Status)
|
||||
}
|
||||
if query.Environment != "" {
|
||||
db = db.Where("environment = ?", query.Environment)
|
||||
}
|
||||
|
||||
// 获取总数
|
||||
if err := db.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
// 分页
|
||||
page := query.Page
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
pageSize := query.PageSize
|
||||
if pageSize < 1 {
|
||||
pageSize = 20
|
||||
}
|
||||
if pageSize > 100 {
|
||||
pageSize = 100
|
||||
}
|
||||
|
||||
offset := (page - 1) * pageSize
|
||||
if err := db.Order("pay_way ASC, is_default DESC, id DESC").Offset(offset).Limit(pageSize).Find(&items).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
dtos := make([]ConfigDTO, 0, len(items))
|
||||
for _, item := range items {
|
||||
dto, err := r.toDTO(item, false)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
dtos = append(dtos, dto)
|
||||
}
|
||||
if err := r.applySuccessfulPaymentStats(ctx, dtos); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if err := r.applyReferenceCounts(ctx, dtos); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
return dtos, total, nil
|
||||
}
|
||||
|
||||
// FindByID 根据 ID 查询配置
|
||||
func (r *Repository) FindByID(ctx context.Context, id uint64, includeSecret bool, actorID uint64, meta AuditMeta) (*ConfigDTO, error) {
|
||||
var item model.PaymentMerchantConfig
|
||||
if err := r.db.WithContext(ctx).Where("id = ?", id).First(&item).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrConfigNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
dto, err := r.toDTO(item, includeSecret)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
statDTOs := []ConfigDTO{dto}
|
||||
if err := r.applySuccessfulPaymentStats(ctx, statDTOs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := r.applyReferenceCounts(ctx, statDTOs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dto = statDTOs[0]
|
||||
if includeSecret {
|
||||
if err := appendAuditLog(r.db.WithContext(ctx), actorID, "payment_config.view_secret", item.ID, meta, map[string]any{
|
||||
"name": item.Name,
|
||||
"provider": item.Provider,
|
||||
"merchant_id": item.MerchantID,
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return &dto, nil
|
||||
}
|
||||
|
||||
type paymentConfigSuccessStat struct {
|
||||
ConfigID uint64
|
||||
TotalTransactions int64
|
||||
TotalAmountCent int64
|
||||
LastPaidAt nullableTime
|
||||
}
|
||||
|
||||
// applySuccessfulPaymentStats 使用真实成功支付流水覆盖配置统计,避免仅打开二维码也被算作成交。
|
||||
func (r *Repository) applySuccessfulPaymentStats(ctx context.Context, dtos []ConfigDTO) error {
|
||||
if len(dtos) == 0 {
|
||||
return nil
|
||||
}
|
||||
ids := make([]uint64, 0, len(dtos))
|
||||
indexByID := make(map[uint64]int, len(dtos))
|
||||
for idx, dto := range dtos {
|
||||
ids = append(ids, dto.ID)
|
||||
indexByID[dto.ID] = idx
|
||||
dtos[idx].TotalTransactions = 0
|
||||
dtos[idx].TotalAmountCent = 0
|
||||
dtos[idx].LastUsedAt = nil
|
||||
}
|
||||
|
||||
var rows []paymentConfigSuccessStat
|
||||
if err := r.db.WithContext(ctx).Model(&model.PaymentOrder{}).
|
||||
Select("payment_config_id AS config_id, COUNT(*) AS total_transactions, COALESCE(SUM(amount_cent), 0) AS total_amount_cent, MAX(paid_at) AS last_paid_at").
|
||||
Where("payment_config_id IN ? AND biz_type = ? AND status = ?", ids, "order_pay", "paid").
|
||||
Group("payment_config_id").
|
||||
Scan(&rows).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
for _, row := range rows {
|
||||
idx, ok := indexByID[row.ConfigID]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
dtos[idx].TotalTransactions = row.TotalTransactions
|
||||
dtos[idx].TotalAmountCent = row.TotalAmountCent
|
||||
if row.LastPaidAt.Time != nil {
|
||||
value := row.LastPaidAt.Time.Format(time.RFC3339)
|
||||
dtos[idx].LastUsedAt = &value
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// applyReferenceCounts 使用删除保护的同一口径统计配置被支付记录引用的次数。
|
||||
func (r *Repository) applyReferenceCounts(ctx context.Context, dtos []ConfigDTO) error {
|
||||
for idx := range dtos {
|
||||
count, err := r.referenceCount(ctx, dtos[idx])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
dtos[idx].ReferenceCount = count
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Repository) referenceCount(ctx context.Context, dto ConfigDTO) (int64, error) {
|
||||
var count int64
|
||||
db := r.db.WithContext(ctx).Model(&model.PaymentOrder{}).
|
||||
Where("payment_config_id = ?", dto.ID).
|
||||
Or("(payment_config_id = ? OR payment_config_id IS NULL) AND provider = ? AND merchant_id = ? AND pay_way = ?", 0, dto.Provider, dto.MerchantID, dto.PayWay)
|
||||
if err := db.Count(&count).Error; err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return count, nil
|
||||
}
|
||||
|
||||
type nullableTime struct {
|
||||
Time *time.Time
|
||||
}
|
||||
|
||||
// Value 实现 driver.Valuer,让 GORM 能把 nullableTime 当作普通扫描字段处理。
|
||||
func (nt nullableTime) Value() (driver.Value, error) {
|
||||
if nt.Time == nil {
|
||||
return nil, nil
|
||||
}
|
||||
return *nt.Time, nil
|
||||
}
|
||||
|
||||
// Scan 兼容 MySQL 聚合函数可能返回的 time.Time 与字符串时间。
|
||||
func (nt *nullableTime) Scan(value any) error {
|
||||
switch v := value.(type) {
|
||||
case nil:
|
||||
nt.Time = nil
|
||||
case time.Time:
|
||||
nt.Time = &v
|
||||
case []byte:
|
||||
return nt.scanString(string(v))
|
||||
case string:
|
||||
return nt.scanString(v)
|
||||
default:
|
||||
nt.Time = nil
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (nt *nullableTime) scanString(value string) error {
|
||||
if value == "" {
|
||||
nt.Time = nil
|
||||
return nil
|
||||
}
|
||||
for _, layout := range []string{
|
||||
time.RFC3339Nano,
|
||||
time.RFC3339,
|
||||
"2006-01-02 15:04:05.999999999-07:00",
|
||||
"2006-01-02 15:04:05-07:00",
|
||||
"2006-01-02 15:04:05.999999999",
|
||||
"2006-01-02 15:04:05",
|
||||
} {
|
||||
parsed, err := time.Parse(layout, value)
|
||||
if err == nil {
|
||||
nt.Time = &parsed
|
||||
return nil
|
||||
}
|
||||
}
|
||||
nt.Time = nil
|
||||
return nil
|
||||
}
|
||||
|
||||
// FindRuntimeByID 根据配置 ID 查询运行时配置,不写审计日志,供支付单回溯原配置使用。
|
||||
func (r *Repository) FindRuntimeByID(ctx context.Context, id uint64, includeSecret bool) (*ConfigDTO, error) {
|
||||
var item model.PaymentMerchantConfig
|
||||
if err := r.db.WithContext(ctx).Where("id = ?", id).First(&item).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrConfigNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
dto, err := r.toDTO(item, includeSecret)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &dto, nil
|
||||
}
|
||||
|
||||
// FindDefault 查询指定服务商的默认启用配置,兼容旧调用路径。
|
||||
func (r *Repository) FindDefault(ctx context.Context, provider string) (*model.PaymentMerchantConfig, error) {
|
||||
var item model.PaymentMerchantConfig
|
||||
if err := r.db.WithContext(ctx).Where("provider = ? AND is_default = ? AND status = ?", provider, true, "active").First(&item).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrNoActiveConfigFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &item, nil
|
||||
}
|
||||
|
||||
// FindDefaultByPayWay 查询指定支付方式的默认启用配置。
|
||||
func (r *Repository) FindDefaultByPayWay(ctx context.Context, payWay string, includeSecret bool) (*ConfigDTO, error) {
|
||||
var item model.PaymentMerchantConfig
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("pay_way = ? AND status = ?", payWay, "active").
|
||||
Order("is_default DESC, id DESC").
|
||||
First(&item).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrNoActiveConfigFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
dto, err := r.toDTO(item, includeSecret)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &dto, nil
|
||||
}
|
||||
|
||||
// FindDefaultByProvider 查询指定服务商的默认启用配置。
|
||||
func (r *Repository) FindDefaultByProvider(ctx context.Context, provider string, includeSecret bool) (*ConfigDTO, error) {
|
||||
item, err := r.FindDefault(ctx, provider)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dto, err := r.toDTO(*item, includeSecret)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &dto, nil
|
||||
}
|
||||
|
||||
// FindDefaultByProviderPayWay 查询指定服务商和支付方式的默认启用配置。
|
||||
func (r *Repository) FindDefaultByProviderPayWay(ctx context.Context, provider string, payWay string, includeSecret bool) (*ConfigDTO, error) {
|
||||
var item model.PaymentMerchantConfig
|
||||
if err := r.db.WithContext(ctx).
|
||||
Where("provider = ? AND pay_way = ? AND status = ?", provider, payWay, "active").
|
||||
Order("is_default DESC, id DESC").
|
||||
First(&item).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrNoActiveConfigFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
dto, err := r.toDTO(item, includeSecret)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &dto, nil
|
||||
}
|
||||
|
||||
// FindByProviderMerchantPayWay 根据服务商、商户号和支付方式查配置,用于旧支付单回溯原商户密钥。
|
||||
func (r *Repository) FindByProviderMerchantPayWay(ctx context.Context, provider string, merchantID string, payWay string, includeSecret bool) (*ConfigDTO, error) {
|
||||
var item model.PaymentMerchantConfig
|
||||
if err := r.db.WithContext(ctx).Where("provider = ? AND merchant_id = ? AND pay_way = ?", provider, merchantID, payWay).
|
||||
Order("status = 'active' DESC, is_default DESC, id DESC").
|
||||
First(&item).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrConfigNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
dto, err := r.toDTO(item, includeSecret)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &dto, nil
|
||||
}
|
||||
|
||||
// FindByProviderMerchant 根据服务商和商户号查配置,保留给历史数据没有支付方式时兜底使用。
|
||||
func (r *Repository) FindByProviderMerchant(ctx context.Context, provider string, merchantID string, includeSecret bool) (*ConfigDTO, error) {
|
||||
var item model.PaymentMerchantConfig
|
||||
if err := r.db.WithContext(ctx).Where("provider = ? AND merchant_id = ?", provider, merchantID).
|
||||
Order("status = 'active' DESC, is_default DESC, id DESC").
|
||||
First(&item).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrConfigNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
dto, err := r.toDTO(item, includeSecret)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &dto, nil
|
||||
}
|
||||
|
||||
// FindActiveByProvider 查询提供商的所有激活配置
|
||||
func (r *Repository) FindActiveByProvider(ctx context.Context, provider string) ([]model.PaymentMerchantConfig, error) {
|
||||
var items []model.PaymentMerchantConfig
|
||||
if err := r.db.WithContext(ctx).Where("provider = ? AND status = ?", provider, "active").Order("is_default DESC, id DESC").Find(&items).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
// Create 创建配置
|
||||
@@ -0,0 +1,23 @@
|
||||
package paymentconfig
|
||||
|
||||
import (
|
||||
"hfb_sys/backend/internal/auditlog"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type Repository struct {
|
||||
db *gorm.DB
|
||||
encryptor Encryptor
|
||||
}
|
||||
|
||||
type AuditMeta = auditlog.Meta
|
||||
|
||||
func NewRepository(db *gorm.DB, encryptor Encryptor) *Repository {
|
||||
return &Repository{
|
||||
db: db,
|
||||
encryptor: encryptor,
|
||||
}
|
||||
}
|
||||
|
||||
// List 获取配置列表
|
||||
@@ -0,0 +1,154 @@
|
||||
package paymentconfig
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
)
|
||||
|
||||
func TestImportCreateRequestKeepsOneActiveConfigPerPayWay(t *testing.T) {
|
||||
configs := []ConfigDTO{
|
||||
{Provider: "lakala", MerchantID: "M1", PayWay: "ZFBZF", Status: "active", IsDefault: true},
|
||||
{Provider: "leshua", MerchantID: "M2", PayWay: "ZFBZF", Status: "active", IsDefault: false},
|
||||
{Provider: "leshua", MerchantID: "M3", PayWay: "WXZF", Status: "active", IsDefault: true},
|
||||
}
|
||||
activeKeys := backupActiveKeys(configs)
|
||||
|
||||
first := importCreateRequest(configs[0], activeKeys)
|
||||
second := importCreateRequest(configs[1], activeKeys)
|
||||
third := importCreateRequest(configs[2], activeKeys)
|
||||
|
||||
if first.Status != "active" || !first.IsDefault {
|
||||
t.Fatalf("first config status/default = %s/%v, want active/true", first.Status, first.IsDefault)
|
||||
}
|
||||
if second.Status != "disabled" || second.IsDefault {
|
||||
t.Fatalf("second config status/default = %s/%v, want disabled/false", second.Status, second.IsDefault)
|
||||
}
|
||||
if third.Status != "active" || !third.IsDefault {
|
||||
t.Fatalf("third config status/default = %s/%v, want active/true", third.Status, third.IsDefault)
|
||||
}
|
||||
}
|
||||
|
||||
func TestImportCreateRequestPreservesTestingConfig(t *testing.T) {
|
||||
cfg := ConfigDTO{
|
||||
Provider: "lakala",
|
||||
MerchantID: "M1",
|
||||
Status: "testing",
|
||||
}
|
||||
|
||||
req := importCreateRequest(cfg, nil)
|
||||
|
||||
if req.Status != "testing" || req.IsDefault {
|
||||
t.Fatalf("status/default = %s/%v, want testing/false", req.Status, req.IsDefault)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateCreateRequestRequiresShunchengSecretID(t *testing.T) {
|
||||
repo := &Repository{}
|
||||
req := CreateRequest{
|
||||
Name: "顺成生产商户",
|
||||
Provider: "shuncheng",
|
||||
MerchantID: "0000000038",
|
||||
GatewayURL: "http://jyzxapi.ydxnhb.com",
|
||||
SignKey: "secret-key",
|
||||
NotifyKey: "notify-key",
|
||||
NotifyURL: "https://example.com/api/payments/shuncheng/notify",
|
||||
PayWay: "ZFBZF",
|
||||
}
|
||||
if err := repo.validateCreateRequest(req); err != ErrSecretIDRequired {
|
||||
t.Fatalf("validateCreateRequest() error = %v, want ErrSecretIDRequired", err)
|
||||
}
|
||||
|
||||
req.ExtraConfig = map[string]any{"secret_id": "SEC-1"}
|
||||
if err := repo.validateCreateRequest(req); err != nil {
|
||||
t.Fatalf("validateCreateRequest() error = %v, want nil", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestListUsesSuccessfulPaymentStats 验证配置页只统计成功支付,不把打开二维码或取消订单算作成交。
|
||||
func TestListUsesSuccessfulPaymentStats(t *testing.T) {
|
||||
db := database.NewTestDB()
|
||||
if err := database.AutoMigrateIfMissing(db, &model.PaymentMerchantConfig{}, &model.PaymentOrder{}); err != nil {
|
||||
t.Fatalf("migrate failed: %v", err)
|
||||
}
|
||||
config := model.PaymentMerchantConfig{
|
||||
Name: "拉卡拉微信",
|
||||
Provider: "lakala",
|
||||
MerchantID: "M1",
|
||||
PayWay: "WXZF",
|
||||
Status: "active",
|
||||
Environment: "production",
|
||||
TotalTransactions: 99,
|
||||
TotalAmountCent: 999999,
|
||||
}
|
||||
if err := db.Create(&config).Error; err != nil {
|
||||
t.Fatalf("create config failed: %v", err)
|
||||
}
|
||||
paidAt := time.Date(2026, 6, 14, 23, 36, 7, 0, time.UTC)
|
||||
payments := []model.PaymentOrder{
|
||||
{
|
||||
PaymentNo: "PAY-SUCCESS",
|
||||
OrderID: 1,
|
||||
OrderNo: "ORD-SUCCESS",
|
||||
UserID: 2,
|
||||
PaymentConfigID: config.ID,
|
||||
Provider: "lakala",
|
||||
MerchantID: "M1",
|
||||
ThirdOrderID: "PAY-SUCCESS",
|
||||
AmountCent: 10130,
|
||||
BizType: "order_pay",
|
||||
Status: "paid",
|
||||
PaidAt: &paidAt,
|
||||
},
|
||||
{
|
||||
PaymentNo: "PAY-CANCELLED",
|
||||
OrderID: 2,
|
||||
OrderNo: "ORD-CANCELLED",
|
||||
UserID: 2,
|
||||
PaymentConfigID: config.ID,
|
||||
Provider: "lakala",
|
||||
MerchantID: "M1",
|
||||
ThirdOrderID: "PAY-CANCELLED",
|
||||
AmountCent: 10130,
|
||||
BizType: "order_pay",
|
||||
Status: "closed",
|
||||
},
|
||||
{
|
||||
PaymentNo: "PAY-LEGACY",
|
||||
OrderID: 3,
|
||||
OrderNo: "ORD-LEGACY",
|
||||
UserID: 2,
|
||||
PaymentConfigID: 0,
|
||||
Provider: "lakala",
|
||||
MerchantID: "M1",
|
||||
ThirdOrderID: "PAY-LEGACY",
|
||||
PayWay: "WXZF",
|
||||
AmountCent: 10130,
|
||||
BizType: "order_pay",
|
||||
Status: "failed",
|
||||
},
|
||||
}
|
||||
if err := db.Create(&payments).Error; err != nil {
|
||||
t.Fatalf("create payments failed: %v", err)
|
||||
}
|
||||
repo := NewRepository(db, nil)
|
||||
|
||||
items, total, err := repo.List(t.Context(), ListQuery{Page: 1, PageSize: 20})
|
||||
if err != nil {
|
||||
t.Fatalf("List() error = %v", err)
|
||||
}
|
||||
if total != 1 || len(items) != 1 {
|
||||
t.Fatalf("items/total = %d/%d, want 1/1", len(items), total)
|
||||
}
|
||||
if items[0].TotalTransactions != 1 || items[0].TotalAmountCent != 10130 {
|
||||
t.Fatalf("success stats = %d/%d, want 1/10130", items[0].TotalTransactions, items[0].TotalAmountCent)
|
||||
}
|
||||
if items[0].ReferenceCount != 3 {
|
||||
t.Fatalf("reference_count = %d, want 3", items[0].ReferenceCount)
|
||||
}
|
||||
if items[0].LastUsedAt == nil {
|
||||
t.Fatal("last success pay time should not be nil")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package paymentconfig
|
||||
|
||||
import "context"
|
||||
|
||||
type Service struct {
|
||||
repo *Repository
|
||||
}
|
||||
|
||||
func NewService(repo *Repository) *Service {
|
||||
return &Service{repo: repo}
|
||||
}
|
||||
|
||||
// List 获取配置列表
|
||||
func (s *Service) List(ctx context.Context, query ListQuery) (*ListResponse, error) {
|
||||
items, total, err := s.repo.List(ctx, query)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
page := query.Page
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
pageSize := query.PageSize
|
||||
if pageSize < 1 {
|
||||
pageSize = 20
|
||||
}
|
||||
|
||||
return &ListResponse{
|
||||
Items: items,
|
||||
Total: total,
|
||||
Page: page,
|
||||
PageSize: pageSize,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Get 获取单个配置
|
||||
func (s *Service) Get(ctx context.Context, id uint64, includeSecret bool, actorID uint64, meta AuditMeta) (*ConfigDTO, error) {
|
||||
return s.repo.FindByID(ctx, id, includeSecret, actorID, meta)
|
||||
}
|
||||
|
||||
// ExportBackup 导出支付配置备份。
|
||||
func (s *Service) ExportBackup(ctx context.Context, actorID uint64, meta AuditMeta) (*ExportBackup, error) {
|
||||
return s.repo.ExportBackup(ctx, actorID, meta)
|
||||
}
|
||||
|
||||
// ImportBackup 导入支付配置备份。
|
||||
func (s *Service) ImportBackup(ctx context.Context, backup ExportBackup, actorID uint64, meta AuditMeta) (*ImportBackupResult, error) {
|
||||
return s.repo.ImportBackup(ctx, backup, actorID, meta)
|
||||
}
|
||||
|
||||
// Create 创建配置
|
||||
func (s *Service) Create(ctx context.Context, req CreateRequest, actorID uint64, meta AuditMeta) (*ConfigDTO, error) {
|
||||
return s.repo.Create(ctx, req, actorID, meta)
|
||||
}
|
||||
|
||||
// Update 更新配置
|
||||
func (s *Service) Update(ctx context.Context, id uint64, req UpdateRequest, actorID uint64, meta AuditMeta) (*ConfigDTO, error) {
|
||||
return s.repo.Update(ctx, id, req, actorID, meta)
|
||||
}
|
||||
|
||||
// Delete 删除配置
|
||||
func (s *Service) Delete(ctx context.Context, id uint64, actorID uint64, meta AuditMeta) error {
|
||||
return s.repo.Delete(ctx, id, actorID, meta)
|
||||
}
|
||||
|
||||
// GetDefaultConfig 获取指定服务商的默认配置,保留给管理工具或兼容调用使用。
|
||||
func (s *Service) GetDefaultConfig(ctx context.Context, provider string) (*ConfigDTO, error) {
|
||||
config, err := s.repo.FindDefault(ctx, provider)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dto, err := s.repo.toDTO(*config, true) // 包含密钥
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &dto, nil
|
||||
}
|
||||
|
||||
// GetDefaultConfigByPayWay 获取指定支付方式的默认配置,供新支付链路按微信/支付宝选渠道。
|
||||
func (s *Service) GetDefaultConfigByPayWay(ctx context.Context, payWay string) (*ConfigDTO, error) {
|
||||
return s.repo.FindDefaultByPayWay(ctx, payWay, true)
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package paymentconfig
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/model"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// IncrementUsage 增加使用统计
|
||||
func (r *Repository) IncrementUsage(ctx context.Context, id uint64, amountCent int64) error {
|
||||
now := time.Now()
|
||||
return r.db.WithContext(ctx).Model(&model.PaymentMerchantConfig{}).Where("id = ?", id).Updates(map[string]any{
|
||||
"total_transactions": gorm.Expr("total_transactions + ?", 1),
|
||||
"total_amount_cent": gorm.Expr("total_amount_cent + ?", amountCent),
|
||||
"last_used_at": now,
|
||||
}).Error
|
||||
}
|
||||
|
||||
// RecordUsage 记录支付配置命中情况,同一个支付单只记录一次。
|
||||
|
||||
// RecordUsage 记录支付配置命中情况,同一个支付单只记录一次。
|
||||
func (r *Repository) RecordUsage(ctx context.Context, configID uint64, paymentOrderID uint64, provider string, merchantID string, amountCent int64, bizType string) error {
|
||||
if configID == 0 || paymentOrderID == 0 {
|
||||
return nil
|
||||
}
|
||||
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
var existing model.PaymentConfigUsageLog
|
||||
err := tx.Where("payment_order_id = ?", paymentOrderID).First(&existing).Error
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return err
|
||||
}
|
||||
log := model.PaymentConfigUsageLog{
|
||||
ConfigID: configID,
|
||||
PaymentOrderID: paymentOrderID,
|
||||
Provider: provider,
|
||||
MerchantID: merchantID,
|
||||
AmountCent: amountCent,
|
||||
BizType: bizType,
|
||||
}
|
||||
if err := tx.Create(&log).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
now := time.Now()
|
||||
return tx.Model(&model.PaymentMerchantConfig{}).Where("id = ?", configID).Updates(map[string]any{
|
||||
"total_transactions": gorm.Expr("total_transactions + ?", 1),
|
||||
"total_amount_cent": gorm.Expr("total_amount_cent + ?", amountCent),
|
||||
"last_used_at": now,
|
||||
}).Error
|
||||
})
|
||||
}
|
||||
|
||||
// deactivateOtherConfigs 保证全局同一时间只有一个启用配置。
|
||||
@@ -0,0 +1,115 @@
|
||||
package paymentconfig
|
||||
|
||||
// validateCreateRequest 验证创建请求
|
||||
func (r *Repository) validateCreateRequest(req CreateRequest) error {
|
||||
if req.Name == "" {
|
||||
return ErrNameRequired
|
||||
}
|
||||
if req.Provider == "" {
|
||||
return ErrInvalidProvider
|
||||
}
|
||||
if !isValidProvider(req.Provider) {
|
||||
return ErrInvalidProvider
|
||||
}
|
||||
if req.MerchantID == "" {
|
||||
return ErrMerchantIDRequired
|
||||
}
|
||||
if req.SignType != "" && !isValidSignType(req.SignType) {
|
||||
return ErrInvalidSignType
|
||||
}
|
||||
if req.PayWay != "" && !isValidPayWay(req.PayWay) {
|
||||
return ErrInvalidPayWay
|
||||
}
|
||||
if req.Status != "" && !isValidStatus(req.Status) {
|
||||
return ErrInvalidStatus
|
||||
}
|
||||
|
||||
// leshua 特定验证
|
||||
if req.Provider == "leshua" {
|
||||
if req.GatewayURL == "" {
|
||||
return ErrGatewayURLRequired
|
||||
}
|
||||
if req.SignKey == "" {
|
||||
return ErrSignKeyRequired
|
||||
}
|
||||
if req.NotifyKey == "" {
|
||||
return ErrNotifyKeyRequired
|
||||
}
|
||||
if req.NotifyURL == "" {
|
||||
return ErrNotifyURLRequired
|
||||
}
|
||||
}
|
||||
if req.Provider == "lakala" {
|
||||
if req.GatewayURL == "" {
|
||||
return ErrGatewayURLRequired
|
||||
}
|
||||
if req.SignKey == "" {
|
||||
return ErrSignKeyRequired
|
||||
}
|
||||
if req.NotifyKey == "" {
|
||||
return ErrNotifyKeyRequired
|
||||
}
|
||||
if req.NotifyURL == "" {
|
||||
return ErrNotifyURLRequired
|
||||
}
|
||||
if extraString(req.ExtraConfig, "app_id") == "" {
|
||||
return ErrAppIDRequired
|
||||
}
|
||||
if extraString(req.ExtraConfig, "serial_no") == "" {
|
||||
return ErrSerialNoRequired
|
||||
}
|
||||
if extraString(req.ExtraConfig, "term_no") == "" {
|
||||
return ErrTermNoRequired
|
||||
}
|
||||
}
|
||||
if req.Provider == "shuncheng" {
|
||||
if req.GatewayURL == "" {
|
||||
return ErrGatewayURLRequired
|
||||
}
|
||||
if req.SignKey == "" {
|
||||
return ErrSignKeyRequired
|
||||
}
|
||||
if req.NotifyKey == "" {
|
||||
return ErrNotifyKeyRequired
|
||||
}
|
||||
if req.NotifyURL == "" {
|
||||
return ErrNotifyURLRequired
|
||||
}
|
||||
if extraString(req.ExtraConfig, "secret_id") == "" {
|
||||
return ErrSecretIDRequired
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func isValidProvider(value string) bool {
|
||||
return value == "leshua" || value == "lakala" || value == "shuncheng" || value == "mock"
|
||||
}
|
||||
|
||||
func isValidSignType(value string) bool {
|
||||
return value == "MD5" || value == "SHA256withRSA"
|
||||
}
|
||||
|
||||
// isValidPayWay 校验支付方式是否属于系统支持的微信或支付宝编码。
|
||||
func isValidPayWay(value string) bool {
|
||||
return value == "ZFBZF" || value == "WXZF"
|
||||
}
|
||||
|
||||
func isValidStatus(value string) bool {
|
||||
return value == "active" || value == "disabled" || value == "testing"
|
||||
}
|
||||
|
||||
func extraString(config map[string]any, key string) string {
|
||||
if config == nil {
|
||||
return ""
|
||||
}
|
||||
value, ok := config[key]
|
||||
if !ok || value == nil {
|
||||
return ""
|
||||
}
|
||||
if s, ok := value.(string); ok {
|
||||
return s
|
||||
}
|
||||
return ""
|
||||
}
|
||||
Reference in New Issue
Block a user