491 lines
17 KiB
Go
491 lines
17 KiB
Go
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
|
|
}
|