支持拉卡拉多渠道支付和测试充值

This commit is contained in:
yml
2026-06-06 21:46:41 +08:00
parent 4d40883da6
commit ba4c56c0cc
16 changed files with 1917 additions and 157 deletions
@@ -0,0 +1,447 @@
package payment
import (
"context"
"fmt"
"strconv"
"strings"
"hfb_sys/backend/internal/integrations/payment/lakala"
"hfb_sys/backend/internal/integrations/payment/leshua"
"hfb_sys/backend/internal/modules/paymentconfig"
)
type channelClient interface {
CreatePayment(ctx context.Context, req channelCreatePaymentRequest) (*channelCreatePaymentResponse, error)
QueryPayment(ctx context.Context, thirdOrderID string, providerOrderID string) (*channelQueryPaymentResponse, error)
CreateRefund(ctx context.Context, req channelCreateRefundRequest) (*channelCreateRefundResponse, error)
QueryRefund(ctx context.Context, req channelQueryRefundRequest) (*channelQueryRefundResponse, error)
VerifyNotify(params map[string]string, rawPayload string, contentType string, authorization string) (channelVerifyNotifyResult, error)
}
type channelCreatePaymentRequest struct {
ThirdOrderID string
AmountCent int64
PayWay string
JSPayFlag string
NotifyURL string
JumpURL string
ClientIP string
Body string
Attach string
}
type channelCreatePaymentResponse struct {
OK bool
ErrorMessage string
ProviderOrderID string
PayWay string
Status string
PayTime string
TDCode string
JSPayURL string
JSPayInfo string
RawRequest map[string]string
Raw map[string]string
}
type channelQueryPaymentResponse struct {
OK bool
ErrorMessage string
ProviderOrderID string
Status string
Amount string
PayWay string
PayTime string
Raw map[string]string
}
type channelCreateRefundRequest struct {
ThirdOrderID string
ProviderOrderID string
MerchantRefundID string
RefundAmountCent int64
NotifyURL string
Attach string
Remark string
ClientIP string
}
type channelCreateRefundResponse struct {
OK bool
ErrorMessage string
ProviderRefundID string
Status string
RefundAmount string
RawRequest map[string]string
Raw map[string]string
}
type channelQueryRefundRequest struct {
ThirdOrderID string
ProviderOrderID string
MerchantRefundID string
ProviderRefundID string
}
type channelQueryRefundResponse struct {
OK bool
ErrorMessage string
ProviderRefundID string
Status string
RefundAmount string
RefundTime string
Raw map[string]string
}
type channelVerifyNotifyResult struct {
OK bool
MatchedKey string
Got string
Expected map[string]string
BaseString map[string]string
ParamKeys []string
}
type leshuaChannel struct {
client *leshua.Client
}
func newLeshuaChannel(cfg leshua.Config) channelClient {
return leshuaChannel{client: leshua.NewClient(cfg)}
}
func (c leshuaChannel) CreatePayment(ctx context.Context, req channelCreatePaymentRequest) (*channelCreatePaymentResponse, error) {
resp, rawReq, err := c.client.CreatePayment(ctx, leshua.CreatePaymentRequest{
ThirdOrderID: req.ThirdOrderID,
AmountCent: req.AmountCent,
PayWay: req.PayWay,
JSPayFlag: req.JSPayFlag,
NotifyURL: req.NotifyURL,
JumpURL: req.JumpURL,
ClientIP: req.ClientIP,
Body: req.Body,
Attach: req.Attach,
})
if err != nil {
return nil, err
}
return &channelCreatePaymentResponse{
OK: resp.RespCode == "0" && resp.ResultCode == "0",
ErrorMessage: resp.ErrorMessage,
ProviderOrderID: resp.ProviderOrderID,
PayWay: resp.PayWay,
Status: normalizeLeshuaPaymentStatus(resp.Raw["status"]),
PayTime: resp.Raw["pay_time"],
TDCode: resp.TDCode,
JSPayURL: resp.JSPayURL,
JSPayInfo: resp.JSPayInfo,
RawRequest: rawReq,
Raw: resp.Raw,
}, nil
}
func (c leshuaChannel) QueryPayment(ctx context.Context, thirdOrderID string, providerOrderID string) (*channelQueryPaymentResponse, error) {
resp, err := c.client.QueryPayment(ctx, thirdOrderID, providerOrderID)
if err != nil {
return nil, err
}
return &channelQueryPaymentResponse{
OK: resp.RespCode == "0" && resp.ResultCode == "0",
ErrorMessage: resp.ErrorMessage,
ProviderOrderID: resp.ProviderOrderID,
Status: normalizeLeshuaPaymentStatus(resp.Status),
Amount: resp.Amount,
PayWay: resp.PayWay,
PayTime: resp.PayTime,
Raw: resp.Raw,
}, nil
}
func (c leshuaChannel) CreateRefund(ctx context.Context, req channelCreateRefundRequest) (*channelCreateRefundResponse, error) {
resp, rawReq, err := c.client.CreateRefund(ctx, leshua.CreateRefundRequest{
ThirdOrderID: req.ThirdOrderID,
LeshuaOrderID: req.ProviderOrderID,
MerchantRefundID: req.MerchantRefundID,
RefundAmountCent: req.RefundAmountCent,
NotifyURL: req.NotifyURL,
Attach: req.Attach,
})
if err != nil {
return nil, err
}
return &channelCreateRefundResponse{
OK: resp.RespCode == "0" && resp.ResultCode == "0",
ErrorMessage: resp.ErrorMessage,
ProviderRefundID: resp.LeshuaRefundID,
Status: normalizeLeshuaRefundStatus(resp.Status),
RefundAmount: resp.RefundAmount,
RawRequest: rawReq,
Raw: resp.Raw,
}, nil
}
func (c leshuaChannel) QueryRefund(ctx context.Context, req channelQueryRefundRequest) (*channelQueryRefundResponse, error) {
resp, err := c.client.QueryRefund(ctx, leshua.QueryRefundRequest{
ThirdOrderID: req.ThirdOrderID,
LeshuaOrderID: req.ProviderOrderID,
MerchantRefundID: req.MerchantRefundID,
LeshuaRefundID: req.ProviderRefundID,
})
if err != nil {
return nil, err
}
return &channelQueryRefundResponse{
OK: resp.RespCode == "0" && resp.ResultCode == "0",
ErrorMessage: resp.ErrorMessage,
ProviderRefundID: resp.LeshuaRefundID,
Status: normalizeLeshuaRefundStatus(resp.Status),
RefundAmount: resp.RefundAmount,
RefundTime: resp.RefundTime,
Raw: resp.Raw,
}, nil
}
func (c leshuaChannel) VerifyNotify(params map[string]string, rawPayload string, contentType string, authorization string) (channelVerifyNotifyResult, error) {
verify := c.client.VerifyNotifyDetail(params)
result := channelVerifyNotifyResult{
OK: verify.OK,
MatchedKey: verify.MatchedKey,
Got: verify.Got,
Expected: verify.Expected,
BaseString: verify.BaseString,
ParamKeys: verify.ParamKeys,
}
if !result.OK {
return result, ErrPaymentVerifyFailed
}
return result, nil
}
type lakalaChannel struct {
client *lakala.Client
}
func newLakalaChannel(cfg lakala.Config) channelClient {
return lakalaChannel{client: lakala.NewClient(cfg)}
}
func (c lakalaChannel) CreatePayment(ctx context.Context, req channelCreatePaymentRequest) (*channelCreatePaymentResponse, error) {
resp, err := c.client.CreatePayment(ctx, lakala.CreatePaymentRequest{
ThirdOrderID: req.ThirdOrderID,
AmountCent: req.AmountCent,
PayWay: req.PayWay,
JSPayFlag: req.JSPayFlag,
NotifyURL: req.NotifyURL,
JumpURL: req.JumpURL,
ClientIP: req.ClientIP,
Body: req.Body,
Attach: req.Attach,
})
if err != nil {
return nil, err
}
return &channelCreatePaymentResponse{
OK: resp.OK,
ErrorMessage: resp.ErrorMessage,
ProviderOrderID: resp.ProviderOrderID,
PayWay: resp.PayWay,
Status: resp.Status,
PayTime: resp.PayTime,
TDCode: resp.TDCode,
JSPayURL: resp.JSPayURL,
JSPayInfo: resp.JSPayInfo,
RawRequest: resp.RawRequest,
Raw: resp.Raw,
}, nil
}
func (c lakalaChannel) QueryPayment(ctx context.Context, thirdOrderID string, providerOrderID string) (*channelQueryPaymentResponse, error) {
resp, err := c.client.QueryPayment(ctx, thirdOrderID, providerOrderID)
if err != nil {
return nil, err
}
return &channelQueryPaymentResponse{
OK: resp.OK,
ErrorMessage: resp.ErrorMessage,
ProviderOrderID: resp.ProviderOrderID,
Status: resp.Status,
Amount: resp.Amount,
PayWay: resp.PayWay,
PayTime: resp.PayTime,
Raw: resp.Raw,
}, nil
}
func (c lakalaChannel) CreateRefund(ctx context.Context, req channelCreateRefundRequest) (*channelCreateRefundResponse, error) {
resp, err := c.client.CreateRefund(ctx, lakala.CreateRefundRequest{
ThirdOrderID: req.ThirdOrderID,
ProviderOrderID: req.ProviderOrderID,
MerchantRefundID: req.MerchantRefundID,
RefundAmountCent: req.RefundAmountCent,
NotifyURL: req.NotifyURL,
Attach: req.Attach,
RefundReason: req.Remark,
ClientIP: req.ClientIP,
})
if err != nil {
return nil, err
}
return &channelCreateRefundResponse{
OK: resp.OK,
ErrorMessage: resp.ErrorMessage,
ProviderRefundID: resp.ProviderRefundID,
Status: resp.Status,
RefundAmount: resp.RefundAmount,
RawRequest: resp.RawRequest,
Raw: resp.Raw,
}, nil
}
func (c lakalaChannel) QueryRefund(ctx context.Context, req channelQueryRefundRequest) (*channelQueryRefundResponse, error) {
resp, err := c.client.QueryRefund(ctx, lakala.QueryRefundRequest{
ThirdOrderID: req.ThirdOrderID,
ProviderOrderID: req.ProviderOrderID,
MerchantRefundID: req.MerchantRefundID,
ProviderRefundID: req.ProviderRefundID,
})
if err != nil {
return nil, err
}
return &channelQueryRefundResponse{
OK: resp.OK,
ErrorMessage: resp.ErrorMessage,
ProviderRefundID: resp.ProviderRefundID,
Status: resp.Status,
RefundAmount: resp.RefundAmount,
RefundTime: resp.RefundTime,
Raw: resp.Raw,
}, nil
}
func (c lakalaChannel) VerifyNotify(params map[string]string, rawPayload string, contentType string, authorization string) (channelVerifyNotifyResult, error) {
verify := c.client.VerifyNotifyDetail(rawPayload, authorization)
result := channelVerifyNotifyResult{
OK: verify.OK,
MatchedKey: verify.MatchedKey,
Got: verify.Got,
Expected: verify.Expected,
BaseString: verify.BaseString,
ParamKeys: verify.ParamKeys,
}
if !result.OK {
return result, ErrPaymentVerifyFailed
}
return result, nil
}
func buildChannelClient(dto *paymentconfig.ConfigDTO) (channelClient, error) {
switch strings.ToLower(strings.TrimSpace(dto.Provider)) {
case "leshua":
return newLeshuaChannel(leshua.Config{
GatewayURL: dto.GatewayURL,
MerchantID: dto.MerchantID,
SignKey: dto.SignKey,
NotifyKey: dto.NotifyKey,
NotifyURL: dto.NotifyURL,
JumpURL: dto.JumpURL,
PayWay: firstNonEmpty(dto.PayWay, "ZFBZF"),
JSPayFlag: firstNonEmpty(dto.JSPayFlag, "2"),
SignType: firstNonEmpty(dto.SignType, "MD5"),
}), nil
case "lakala":
return newLakalaChannel(lakala.Config{
GatewayURL: dto.GatewayURL,
AppID: extraString(dto.ExtraConfig, "app_id"),
SerialNo: extraString(dto.ExtraConfig, "serial_no"),
MerchantID: dto.MerchantID,
TermNo: extraString(dto.ExtraConfig, "term_no"),
PrivateKey: dto.SignKey,
LakalaCert: extraString(dto.ExtraConfig, "lakala_cert"),
NotifyCert: dto.NotifyKey,
NotifyURL: dto.NotifyURL,
JumpURL: dto.JumpURL,
PayWay: firstNonEmpty(dto.PayWay, "ZFBZF"),
JSPayFlag: firstNonEmpty(dto.JSPayFlag, "2"),
PayMode: extraString(dto.ExtraConfig, "pay_mode"),
OrderExpireMinutes: extraInt(dto.ExtraConfig, "order_expire_minutes"),
}), nil
case "mock":
return nil, nil
default:
return nil, fmt.Errorf("unsupported payment provider: %s", dto.Provider)
}
}
func normalizeLeshuaPaymentStatus(status string) string {
switch status {
case "2", "30":
return "paid"
case "6":
return "closed"
case "8":
return "failed"
default:
return "paying"
}
}
func normalizeLeshuaRefundStatus(status string) string {
switch status {
case "11":
return "refunded"
case "12":
return "failed"
default:
return "refunding"
}
}
func normalizeNotifyPaymentStatus(provider string, status string) string {
if provider == "leshua" {
return normalizeLeshuaPaymentStatus(status)
}
switch status {
case "paid", "closed", "failed", "paying":
return status
default:
return "paying"
}
}
func normalizeNotifyRefundStatus(provider string, status string) string {
if provider == "leshua" {
return normalizeLeshuaRefundStatus(status)
}
switch status {
case "refunded", "failed", "refunding":
return status
default:
return "refunding"
}
}
func extraString(config map[string]any, key string) string {
if config == nil {
return ""
}
value, ok := config[key]
if !ok || value == nil {
return ""
}
switch typed := value.(type) {
case string:
return strings.TrimSpace(typed)
default:
return strings.TrimSpace(fmt.Sprint(typed))
}
}
func extraInt(config map[string]any, key string) int {
value := extraString(config, key)
if value == "" {
return 0
}
n, _ := strconv.Atoi(value)
return n
}
@@ -7,6 +7,7 @@ import (
"net/http"
"strconv"
"hfb_sys/backend/internal/integrations/payment/lakala"
"hfb_sys/backend/internal/integrations/payment/leshua"
"hfb_sys/backend/internal/middleware"
"hfb_sys/backend/internal/modules/order"
@@ -144,6 +145,39 @@ func (h *Handler) LeshuaNotify(c *gin.Context) {
c.String(http.StatusOK, result.Message)
}
func (h *Handler) LakalaNotify(c *gin.Context) {
body, err := io.ReadAll(io.LimitReader(c.Request.Body, 1<<20))
if err != nil {
c.JSON(http.StatusOK, gin.H{"code": "FAIL", "message": "读取失败"})
return
}
params, err := lakala.ParsePayload(body)
if err != nil {
c.JSON(http.StatusOK, gin.H{"code": "FAIL", "message": "解析失败"})
return
}
rawPayload := string(body)
contentType := c.GetHeader("Content-Type")
authorization := c.GetHeader("Authorization")
log.Printf(
"[payment] lakala notify received third_order_id=%s provider_order_id=%s status=%s amount=%s content_type=%s raw_payload=%s",
params["third_order_id"],
params["provider_order_id"],
params["status"],
params["amount"],
contentType,
rawPayload,
)
result, err := h.service.HandleNotify("lakala", params, rawPayload, contentType, authorization)
if err != nil || result == nil || !result.OK {
log.Printf("[payment] lakala notify failed third_order_id=%s err=%v", params["third_order_id"], err)
c.JSON(http.StatusOK, gin.H{"code": "FAIL", "message": "失败"})
return
}
log.Printf("[payment] lakala notify processed third_order_id=%s status=%s", params["third_order_id"], params["status"])
c.JSON(http.StatusOK, gin.H{"code": "SUCCESS", "message": "执行成功"})
}
func currentUserID(c *gin.Context) (uint64, bool) {
value, ok := c.Get(middleware.ContextUserID)
if !ok {
+115 -84
View File
@@ -10,7 +10,6 @@ import (
"math"
"time"
"hfb_sys/backend/internal/integrations/payment/leshua"
"hfb_sys/backend/internal/model"
"hfb_sys/backend/internal/modules/order"
"hfb_sys/backend/internal/modules/paymentconfig"
@@ -32,7 +31,11 @@ type runtimePaymentConfig struct {
ID uint64
Provider string
MerchantID string
Leshua leshua.Config
PayWay string
JSPayFlag string
NotifyURL string
JumpURL string
Channel channelClient
}
const (
@@ -61,11 +64,7 @@ func NewRepository(db *gorm.DB, configRepo *paymentconfig.Repository, orderRepo
}
func (c runtimePaymentConfig) isMockMode() bool {
return c.Provider != "leshua"
}
func (c runtimePaymentConfig) client() *leshua.Client {
return leshua.NewClient(c.Leshua)
return c.Provider == "mock"
}
func (r *Repository) defaultRuntimeConfig() (*runtimePaymentConfig, error) {
@@ -92,6 +91,13 @@ func (r *Repository) runtimeConfigForPayment(payment *model.PaymentOrder) (*runt
}
}
if provider != "leshua" {
if provider == "lakala" && r.configRepo != nil {
dto, err := r.configRepo.FindDefaultByProvider(provider, true)
if err != nil {
return nil, err
}
return runtimeConfigFromDTO(dto), nil
}
return &runtimePaymentConfig{
Provider: provider,
MerchantID: merchantID,
@@ -111,22 +117,19 @@ func runtimeConfigFromDTO(dto *paymentconfig.ConfigDTO) *runtimePaymentConfig {
provider := firstNonEmpty(dto.Provider, "mock")
payWay := firstNonEmpty(dto.PayWay, "ZFBZF")
jsPayFlag := firstNonEmpty(dto.JSPayFlag, "2")
signType := firstNonEmpty(dto.SignType, "MD5")
client, err := buildChannelClient(dto)
if err != nil {
client = nil
}
return &runtimePaymentConfig{
ID: dto.ID,
Provider: provider,
MerchantID: dto.MerchantID,
Leshua: leshua.Config{
GatewayURL: dto.GatewayURL,
MerchantID: dto.MerchantID,
SignKey: dto.SignKey,
NotifyKey: dto.NotifyKey,
NotifyURL: dto.NotifyURL,
JumpURL: dto.JumpURL,
PayWay: payWay,
JSPayFlag: jsPayFlag,
SignType: signType,
},
PayWay: payWay,
JSPayFlag: jsPayFlag,
NotifyURL: dto.NotifyURL,
JumpURL: dto.JumpURL,
Channel: client,
}
}
@@ -170,15 +173,18 @@ func (r *Repository) Start(userID uint64, orderID uint64, req StartPaymentReques
dto := toDTO(*payment)
return &dto, nil
}
if runtimeConfig.Channel == nil {
_ = r.markPaymentFailed(payment.ID, nil, "payment channel unavailable")
return nil, ErrPaymentUnavailable
}
client := runtimeConfig.client()
resp, rawReq, err := client.CreatePayment(context.Background(), leshua.CreatePaymentRequest{
resp, err := runtimeConfig.Channel.CreatePayment(context.Background(), channelCreatePaymentRequest{
ThirdOrderID: payment.ThirdOrderID,
AmountCent: payment.AmountCent,
PayWay: payment.PayWay,
JSPayFlag: payment.JSPayFlag,
NotifyURL: runtimeConfig.Leshua.NotifyURL,
JumpURL: runtimeConfig.Leshua.JumpURL,
NotifyURL: runtimeConfig.NotifyURL,
JumpURL: runtimeConfig.JumpURL,
ClientIP: clientIP,
Body: "租号订单 " + orderRow.OrderNo,
Attach: orderRow.OrderNo,
@@ -187,7 +193,7 @@ func (r *Repository) Start(userID uint64, orderID uint64, req StartPaymentReques
_ = r.markPaymentFailed(payment.ID, nil, err.Error())
return nil, err
}
if resp.RespCode != "0" || resp.ResultCode != "0" {
if !resp.OK {
_ = r.markPaymentFailed(payment.ID, resp.Raw, resp.ErrorMessage)
return nil, ErrPaymentUnavailable
}
@@ -198,7 +204,7 @@ func (r *Repository) Start(userID uint64, orderID uint64, req StartPaymentReques
"td_code": resp.TDCode,
"jspay_url": resp.JSPayURL,
"jspay_info": resp.JSPayInfo,
"raw_request": jsonMap(rawReq),
"raw_request": jsonMap(resp.RawRequest),
"raw_response": jsonMap(withRawSource(resp.Raw, channelSourceCreate)),
}).Error; err != nil {
return nil, err
@@ -242,14 +248,17 @@ func (r *Repository) StartWalletRecharge(userID uint64, req WalletRechargePaymen
dto := toDTO(*latest)
return &dto, nil
}
client := runtimeConfig.client()
resp, rawReq, err := client.CreatePayment(context.Background(), leshua.CreatePaymentRequest{
if runtimeConfig.Channel == nil {
_ = r.markPaymentFailed(payment.ID, nil, "payment channel unavailable")
return nil, ErrPaymentUnavailable
}
resp, err := runtimeConfig.Channel.CreatePayment(context.Background(), channelCreatePaymentRequest{
ThirdOrderID: payment.ThirdOrderID,
AmountCent: payment.AmountCent,
PayWay: payment.PayWay,
JSPayFlag: payment.JSPayFlag,
NotifyURL: runtimeConfig.Leshua.NotifyURL,
JumpURL: runtimeConfig.Leshua.JumpURL,
NotifyURL: runtimeConfig.NotifyURL,
JumpURL: runtimeConfig.JumpURL,
ClientIP: clientIP,
Body: "钱包充值 " + payment.PaymentNo,
Attach: payment.PaymentNo,
@@ -258,7 +267,7 @@ func (r *Repository) StartWalletRecharge(userID uint64, req WalletRechargePaymen
_ = r.markPaymentFailed(payment.ID, nil, err.Error())
return nil, err
}
if resp.RespCode != "0" || resp.ResultCode != "0" {
if !resp.OK {
_ = r.markPaymentFailed(payment.ID, resp.Raw, resp.ErrorMessage)
return nil, ErrPaymentUnavailable
}
@@ -269,7 +278,7 @@ func (r *Repository) StartWalletRecharge(userID uint64, req WalletRechargePaymen
"td_code": resp.TDCode,
"jspay_url": resp.JSPayURL,
"jspay_info": resp.JSPayInfo,
"raw_request": jsonMap(rawReq),
"raw_request": jsonMap(resp.RawRequest),
"raw_response": jsonMap(withRawSource(resp.Raw, channelSourceCreate)),
}).Error; err != nil {
return nil, err
@@ -299,7 +308,10 @@ func (r *Repository) QueryWalletRecharge(userID uint64, paymentID uint64) (*Paym
dto := toDTO(payment)
return &dto, nil
}
resp, err := runtimeConfig.client().QueryPayment(context.Background(), payment.ThirdOrderID, payment.ProviderOrderID)
if runtimeConfig.Channel == nil {
return nil, ErrPaymentUnavailable
}
resp, err := runtimeConfig.Channel.QueryPayment(context.Background(), payment.ThirdOrderID, payment.ProviderOrderID)
if err != nil {
return nil, err
}
@@ -330,7 +342,10 @@ func (r *Repository) Query(userID uint64, orderID uint64) (*PaymentDTO, error) {
dto := toDTO(payment)
return &dto, nil
}
resp, err := runtimeConfig.client().QueryPayment(context.Background(), payment.ThirdOrderID, payment.ProviderOrderID)
if runtimeConfig.Channel == nil {
return nil, ErrPaymentUnavailable
}
resp, err := runtimeConfig.Channel.QueryPayment(context.Background(), payment.ThirdOrderID, payment.ProviderOrderID)
if err != nil {
return nil, err
}
@@ -346,9 +361,13 @@ func (r *Repository) Query(userID uint64, orderID uint64) (*PaymentDTO, error) {
}
func (r *Repository) HandleLeshuaNotify(params map[string]string, rawPayload string, contentType string) (*NotifyResult, error) {
return r.HandleNotify("leshua", params, rawPayload, contentType, "")
}
func (r *Repository) HandleNotify(provider string, params map[string]string, rawPayload string, contentType string, authorization string) (*NotifyResult, error) {
// 退款通知会携带 merchant_refund_id 或 leshua_refund_id。
if params["merchant_refund_id"] != "" || params["leshua_refund_id"] != "" {
return r.HandleRefundNotify(params, rawPayload, contentType)
if params["merchant_refund_id"] != "" || params["leshua_refund_id"] != "" || params["provider_refund_id"] != "" {
return r.HandleRefundNotify(provider, params, rawPayload, contentType, authorization)
}
payment, err := r.findPaymentForNotify(params)
@@ -359,19 +378,19 @@ func (r *Repository) HandleLeshuaNotify(params map[string]string, rawPayload str
if err != nil {
return nil, ErrPaymentUnavailable
}
verify, err := r.verifyNotify(payment, runtimeConfig, params, rawPayload, contentType)
verify, err := r.verifyNotify(payment, runtimeConfig, params, rawPayload, contentType, authorization)
if err != nil {
return nil, err
}
if amount := parseCent(params["amount"]); amount > 0 && amount != payment.AmountCent {
if err := r.recordNotifyDiagnostic(payment.ID, params, rawPayload, contentType, verify, "amount_mismatch"); err != nil {
log.Printf("[payment] leshua notify diagnostic save failed third_order_id=%s err=%v", params["third_order_id"], err)
log.Printf("[payment] %s notify diagnostic save failed third_order_id=%s err=%v", runtimeConfig.Provider, params["third_order_id"], err)
}
return nil, ErrPaymentVerifyFailed
}
raw := withNotifyDiagnostic(params, rawPayload, contentType, verify, "verified")
if err := r.applyChannelStatus(payment, params["status"], params["pay_time"], raw, channelSourceNotify); err != nil {
if err := r.applyChannelStatus(payment, normalizeNotifyPaymentStatus(runtimeConfig.Provider, params["status"]), params["pay_time"], raw, channelSourceNotify); err != nil {
return nil, err
}
return &NotifyResult{OK: true, Message: "000000"}, nil
@@ -450,36 +469,41 @@ func (r *Repository) StartRefund(orderID uint64, refundAmountCent int64, bizType
log.Printf("[payment] mark order refunding failed order_id=%d err=%v", orderID, err)
}
resp, rawReq, err := runtimeConfig.client().CreateRefund(context.Background(), leshua.CreateRefundRequest{
if runtimeConfig.Channel == nil {
_ = r.markRefundFailed(refundOrder.ID, orderID, refundAmountCent, map[string]string{"error": "payment channel unavailable"})
return nil, ErrPaymentUnavailable
}
resp, err := runtimeConfig.Channel.CreateRefund(context.Background(), channelCreateRefundRequest{
ThirdOrderID: originalPayment.ThirdOrderID,
LeshuaOrderID: originalPayment.ProviderOrderID,
ProviderOrderID: originalPayment.ProviderOrderID,
MerchantRefundID: merchantRefundID,
RefundAmountCent: refundAmountCent,
NotifyURL: runtimeConfig.Leshua.NotifyURL,
NotifyURL: runtimeConfig.NotifyURL,
Attach: originalPayment.OrderNo,
Remark: remark,
})
if err != nil {
_ = r.markRefundFailed(refundOrder.ID, orderID, refundAmountCent, map[string]string{"error": err.Error()})
return nil, err
}
if resp.RespCode != "0" || resp.ResultCode != "0" {
if !resp.OK {
_ = r.markRefundFailed(refundOrder.ID, orderID, refundAmountCent, resp.Raw)
return nil, ErrPaymentUnavailable
}
refundStatus := "refunding"
var paidAt *time.Time
if resp.Status == "11" {
if resp.Status == "refunded" {
refundStatus = "refunded"
now := time.Now()
paidAt = &now
} else if resp.Status == "12" {
} else if resp.Status == "failed" {
refundStatus = "failed"
}
if err := r.db.Model(&model.PaymentOrder{}).Where("id = ?", refundOrder.ID).Updates(map[string]any{
"status": refundStatus,
"provider_order_id": resp.LeshuaRefundID,
"raw_request": jsonMap(rawReq),
"provider_order_id": resp.ProviderRefundID,
"raw_request": jsonMap(resp.RawRequest),
"raw_response": jsonMap(withRawSource(resp.Raw, channelSourceCreate)),
"paid_at": paidAt,
}).Error; err != nil {
@@ -495,7 +519,7 @@ func (r *Repository) StartRefund(orderID uint64, refundAmountCent int64, bizType
_ = r.markOrderRefunding(orderID, refundAmountCent)
}
refundOrder.Status = refundStatus
refundOrder.ProviderOrderID = resp.LeshuaRefundID
refundOrder.ProviderOrderID = resp.ProviderRefundID
dto := toRefundDTO(refundOrder)
return &dto, nil
@@ -518,15 +542,18 @@ func (r *Repository) QueryRefundStatus(orderID uint64) (*RefundDTO, error) {
dto := toRefundDTO(payment)
return &dto, nil
}
resp, err := runtimeConfig.client().QueryRefund(context.Background(), leshua.QueryRefundRequest{
if runtimeConfig.Channel == nil {
return nil, ErrPaymentUnavailable
}
resp, err := runtimeConfig.Channel.QueryRefund(context.Background(), channelQueryRefundRequest{
ThirdOrderID: payment.ThirdOrderID,
MerchantRefundID: payment.ThirdOrderID,
LeshuaRefundID: payment.ProviderOrderID,
ProviderRefundID: payment.ProviderOrderID,
})
if err != nil {
return nil, err
}
if resp.Status == "11" {
if resp.Status == "refunded" {
now := time.Now()
if err := r.db.Model(&model.PaymentOrder{}).Where("id = ?", payment.ID).Updates(map[string]any{
"status": "refunded",
@@ -538,7 +565,7 @@ func (r *Repository) QueryRefundStatus(orderID uint64) (*RefundDTO, error) {
payment.Status = "refunded"
payment.PaidAt = &now
_ = r.updateOrderRefundStatus(orderID, payment.AmountCent)
} else if resp.Status == "12" {
} else if resp.Status == "failed" {
if err := r.db.Model(&model.PaymentOrder{}).Where("id = ?", payment.ID).Updates(map[string]any{
"status": "failed",
"raw_response": jsonMap(withRawSource(resp.Raw, channelSourceQuery)),
@@ -552,8 +579,8 @@ func (r *Repository) QueryRefundStatus(orderID uint64) (*RefundDTO, error) {
return &dto, nil
}
// HandleRefundNotify 处理乐刷退款通知。
func (r *Repository) HandleRefundNotify(params map[string]string, rawPayload string, contentType string) (*NotifyResult, error) {
// HandleRefundNotify 处理渠道退款通知。
func (r *Repository) HandleRefundNotify(provider string, params map[string]string, rawPayload string, contentType string, authorization string) (*NotifyResult, error) {
payment, err := r.findRefundPaymentForNotify(params)
if err != nil {
return nil, err
@@ -562,15 +589,15 @@ func (r *Repository) HandleRefundNotify(params map[string]string, rawPayload str
if err != nil {
return nil, ErrPaymentUnavailable
}
verify, err := r.verifyNotify(payment, runtimeConfig, params, rawPayload, contentType)
verify, err := r.verifyNotify(payment, runtimeConfig, params, rawPayload, contentType, authorization)
if err != nil {
return nil, err
}
raw := withNotifyDiagnostic(params, rawPayload, contentType, verify, "verified")
status := params["status"]
status := normalizeNotifyRefundStatus(provider, params["status"])
switch status {
case "11":
case "refunded":
now := time.Now()
if err := r.db.Model(&model.PaymentOrder{}).Where("id = ?", payment.ID).Updates(map[string]any{
"status": "refunded",
@@ -581,7 +608,7 @@ func (r *Repository) HandleRefundNotify(params map[string]string, rawPayload str
return nil, err
}
_ = r.updateOrderRefundStatus(payment.OrderID, payment.AmountCent)
case "12":
case "failed":
r.db.Model(&model.PaymentOrder{}).Where("id = ?", payment.ID).Updates(map[string]any{
"status": "failed",
"notified_at": time.Now(),
@@ -676,12 +703,12 @@ func (r *Repository) preparePayment(userID uint64, orderID uint64, req StartPaym
Order("id DESC").
First(&existing).Error
if err == nil {
existing.PayWay = firstNonEmpty(req.PayWay, existing.PayWay, runtimeConfig.Leshua.PayWay, "ZFBZF")
existing.JSPayFlag = firstNonEmpty(req.JSPayFlag, existing.JSPayFlag, runtimeConfig.Leshua.JSPayFlag, "2")
existing.PayWay = firstNonEmpty(req.PayWay, existing.PayWay, runtimeConfig.PayWay, "ZFBZF")
existing.JSPayFlag = firstNonEmpty(req.JSPayFlag, existing.JSPayFlag, runtimeConfig.JSPayFlag, "2")
existing.AmountCent = amountCent
existing.Provider = firstNonEmpty(existing.Provider, runtimeConfig.Provider)
existing.MerchantID = firstNonEmpty(existing.MerchantID, runtimeConfig.MerchantID)
if existing.Provider != "leshua" && existing.ProviderOrderID == "" {
if existing.Provider == "mock" && existing.ProviderOrderID == "" {
existing.ProviderOrderID = "MOCK" + existing.ThirdOrderID
}
if err := tx.Save(&existing).Error; err != nil {
@@ -707,15 +734,15 @@ func (r *Repository) preparePayment(userID uint64, orderID uint64, req StartPaym
MerchantID: runtimeConfig.MerchantID,
ThirdOrderID: row.OrderNo,
ProviderOrderID: "",
PayWay: firstNonEmpty(req.PayWay, runtimeConfig.Leshua.PayWay, "ZFBZF"),
JSPayFlag: firstNonEmpty(req.JSPayFlag, runtimeConfig.Leshua.JSPayFlag, "2"),
PayWay: firstNonEmpty(req.PayWay, runtimeConfig.PayWay, "ZFBZF"),
JSPayFlag: firstNonEmpty(req.JSPayFlag, runtimeConfig.JSPayFlag, "2"),
AmountCent: amountCent,
BizType: "order_pay",
Status: "created",
}
if runtimeConfig.isMockMode() {
payment.ProviderOrderID = "MOCK" + row.OrderNo
payment.TDCode = "mock://leshua/pay/" + row.OrderNo
payment.TDCode = "mock://payment/pay/" + row.OrderNo
}
if err := tx.Create(&payment).Error; err != nil {
return err
@@ -748,15 +775,15 @@ func (r *Repository) createWalletRechargePayment(userID uint64, amountCent int64
MerchantID: runtimeConfig.MerchantID,
ThirdOrderID: paymentNo,
ProviderOrderID: "",
PayWay: firstNonEmpty(req.PayWay, runtimeConfig.Leshua.PayWay, "ZFBZF"),
JSPayFlag: firstNonEmpty(req.JSPayFlag, runtimeConfig.Leshua.JSPayFlag, "2"),
PayWay: firstNonEmpty(req.PayWay, runtimeConfig.PayWay, "ZFBZF"),
JSPayFlag: firstNonEmpty(req.JSPayFlag, runtimeConfig.JSPayFlag, "2"),
AmountCent: amountCent,
BizType: "wallet_recharge",
Status: "created",
}
if runtimeConfig.isMockMode() {
payment.ProviderOrderID = "MOCK" + paymentNo
payment.TDCode = "mock://leshua/recharge/" + paymentNo
payment.TDCode = "mock://payment/recharge/" + paymentNo
}
if err := r.db.Create(&payment).Error; err != nil {
return nil, err
@@ -766,16 +793,16 @@ func (r *Repository) createWalletRechargePayment(userID uint64, amountCent int64
func (r *Repository) applyChannelStatus(payment *model.PaymentOrder, status string, payTime string, raw map[string]string, source string) error {
switch status {
case "2", "30":
paidAt := parseLeshuaTime(payTime)
case "paid":
paidAt := parseChannelTime(payTime)
if paidAt == nil {
now := time.Now()
paidAt = &now
}
return r.confirmPaid(payment, status, *paidAt, raw, source)
case "6":
case "closed":
return r.updateChannelStatus(payment.ID, "closed", raw, source)
case "8":
case "failed":
return r.updateChannelStatus(payment.ID, "failed", raw, source)
default:
return r.updateChannelStatus(payment.ID, "paying", raw, source)
@@ -813,7 +840,7 @@ func (r *Repository) confirmPaid(payment *model.PaymentOrder, status string, pai
}
updates := map[string]any{
"status": "paid",
"provider_order_id": firstNonEmpty(raw["leshua_order_id"], payment.ProviderOrderID),
"provider_order_id": firstNonEmpty(raw["provider_order_id"], raw["leshua_order_id"], raw["pay_order_no"], raw["trade_no"], payment.ProviderOrderID),
"raw_response": jsonMap(withRawSource(raw, source)),
"paid_at": paidAt,
}
@@ -871,28 +898,32 @@ func (r *Repository) findRefundPaymentForNotify(params map[string]string) (*mode
return &payment, nil
}
func (r *Repository) verifyNotify(payment *model.PaymentOrder, runtimeConfig *runtimePaymentConfig, params map[string]string, rawPayload string, contentType string) (leshua.VerifyNotifyResult, error) {
var verify leshua.VerifyNotifyResult
func (r *Repository) verifyNotify(payment *model.PaymentOrder, runtimeConfig *runtimePaymentConfig, params map[string]string, rawPayload string, contentType string, authorization string) (channelVerifyNotifyResult, error) {
var verify channelVerifyNotifyResult
if runtimeConfig.isMockMode() {
return verify, nil
}
verify = runtimeConfig.client().VerifyNotifyDetail(params)
if !verify.OK {
if runtimeConfig.Channel == nil {
return verify, ErrPaymentUnavailable
}
verify, err := runtimeConfig.Channel.VerifyNotify(params, rawPayload, contentType, authorization)
if err != nil || !verify.OK {
log.Printf(
"[payment] leshua notify verify failed payment_id=%d third_order_id=%s got=%s expected=%s keys=%v base_string=%s",
"[payment] %s notify verify failed payment_id=%d third_order_id=%s got=%s expected=%s keys=%v base_string=%s",
runtimeConfig.Provider,
payment.ID,
params["third_order_id"],
verify.Got,
verify.Expected["notify_key"],
firstNonEmpty(verify.Expected["notify_key"], verify.Expected["notify_cert"], verify.Expected["error"]),
verify.ParamKeys,
verify.BaseString["notify_key"],
firstNonEmpty(verify.BaseString["notify_key"], verify.BaseString["notify_cert"]),
)
if err := r.recordNotifyDiagnostic(payment.ID, params, rawPayload, contentType, verify, "verify_failed"); err != nil {
log.Printf("[payment] leshua notify diagnostic save failed payment_id=%d err=%v", payment.ID, err)
log.Printf("[payment] %s notify diagnostic save failed payment_id=%d err=%v", runtimeConfig.Provider, payment.ID, err)
}
return verify, ErrPaymentVerifyFailed
}
log.Printf("[payment] leshua notify verified payment_id=%d third_order_id=%s matched_key=%s", payment.ID, params["third_order_id"], verify.MatchedKey)
log.Printf("[payment] %s notify verified payment_id=%d third_order_id=%s matched_key=%s", runtimeConfig.Provider, payment.ID, params["third_order_id"], verify.MatchedKey)
return verify, nil
}
@@ -938,11 +969,11 @@ func parseCent(value string) int64 {
return amount
}
func parseLeshuaTime(value string) *time.Time {
func parseChannelTime(value string) *time.Time {
if value == "" {
return nil
}
for _, layout := range []string{"2006-01-02 15:04:05", time.RFC3339} {
for _, layout := range []string{"2006-01-02 15:04:05", "20060102150405", time.RFC3339} {
parsed, err := time.ParseInLocation(layout, value, time.Local)
if err == nil {
return &parsed
@@ -974,7 +1005,7 @@ func withRawSource(raw map[string]string, source string) map[string]string {
return out
}
func (r *Repository) recordNotifyDiagnostic(paymentID uint64, params map[string]string, rawPayload string, contentType string, verify leshua.VerifyNotifyResult, status string) error {
func (r *Repository) recordNotifyDiagnostic(paymentID uint64, params map[string]string, rawPayload string, contentType string, verify channelVerifyNotifyResult, status string) error {
if paymentID == 0 {
return nil
}
@@ -984,7 +1015,7 @@ func (r *Repository) recordNotifyDiagnostic(paymentID uint64, params map[string]
Update("raw_response", jsonMap(raw)).Error
}
func withNotifyDiagnostic(params map[string]string, rawPayload string, contentType string, verify leshua.VerifyNotifyResult, status string) map[string]string {
func withNotifyDiagnostic(params map[string]string, rawPayload string, contentType string, verify channelVerifyNotifyResult, status string) map[string]string {
raw := withRawSource(params, channelSourceNotify)
raw["_notify_diagnostic_status"] = status
raw["_raw_payload"] = rawPayload
+26 -5
View File
@@ -1,6 +1,9 @@
package payment
import "errors"
import (
"errors"
"strings"
)
var (
ErrDependencyUnavailable = errors.New("dependency unavailable")
@@ -15,11 +18,19 @@ var (
const MinWalletRechargeAmount = 0.01
type Service struct {
repo *Repository
repo *Repository
walletRechargeEnabled bool
}
func NewService(repo *Repository) *Service {
return &Service{repo: repo}
func NewService(repo *Repository, appEnv ...string) *Service {
env := "production"
if len(appEnv) > 0 {
env = strings.ToLower(strings.TrimSpace(appEnv[0]))
}
return &Service{
repo: repo,
walletRechargeEnabled: env != "production",
}
}
func (s *Service) Start(userID uint64, orderID uint64, req StartPaymentRequest, clientIP string) (*PaymentDTO, error) {
@@ -46,7 +57,10 @@ func (s *Service) StartWalletRecharge(userID uint64, req WalletRechargePaymentRe
if s.repo == nil {
return nil, ErrDependencyUnavailable
}
return nil, ErrWalletRechargeDisabled
if !s.walletRechargeEnabled {
return nil, ErrWalletRechargeDisabled
}
return s.repo.StartWalletRecharge(userID, req, clientIP)
}
func (s *Service) QueryWalletRecharge(userID uint64, paymentID uint64) (*PaymentDTO, error) {
@@ -66,6 +80,13 @@ func (s *Service) HandleLeshuaNotify(params map[string]string, rawPayload string
return s.repo.HandleLeshuaNotify(params, rawPayload, contentType)
}
func (s *Service) HandleNotify(provider string, params map[string]string, rawPayload string, contentType string, authorization string) (*NotifyResult, error) {
if s.repo == nil {
return nil, ErrDependencyUnavailable
}
return s.repo.HandleNotify(provider, params, rawPayload, contentType, authorization)
}
func (s *Service) StartRefund(orderID uint64, refundAmountCent int64, bizType string, remark string) (*RefundDTO, error) {
if s.repo == nil {
return nil, ErrDependencyUnavailable
@@ -18,6 +18,9 @@ var (
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")
)
// DTO 数据传输对象
@@ -51,7 +54,7 @@ type ConfigDTO struct {
// CreateRequest 创建支付配置请求
type CreateRequest struct {
Name string `json:"name" binding:"required"`
Provider string `json:"provider" binding:"required,oneof=leshua mock"`
Provider string `json:"provider" binding:"required,oneof=leshua lakala mock"`
MerchantID string `json:"merchant_id" binding:"required"`
GatewayURL string `json:"gateway_url"`
SignKey string `json:"sign_key"`
@@ -95,7 +95,8 @@ func (h *Handler) Create(c *gin.Context) {
config, err := h.service.Create(req, adminID, auditMeta(c))
if err == ErrNameRequired || err == ErrMerchantIDRequired || err == ErrGatewayURLRequired ||
err == ErrSignKeyRequired || err == ErrNotifyKeyRequired || err == ErrInvalidProvider ||
err == ErrNotifyURLRequired || err == ErrInvalidSignType {
err == ErrNotifyURLRequired || err == ErrInvalidSignType || err == ErrAppIDRequired ||
err == ErrSerialNoRequired || err == ErrTermNoRequired {
response.BadRequest(c, err.Error())
return
}
@@ -210,7 +210,7 @@ func (r *Repository) Create(req CreateRequest, actorID uint64, meta AuditMeta) (
JumpURL: req.JumpURL,
PayWay: firstNonEmpty(req.PayWay, "ZFBZF"),
JSPayFlag: firstNonEmpty(req.JSPayFlag, "2"),
SignType: firstNonEmpty(req.SignType, "MD5"),
SignType: firstNonEmpty(req.SignType, defaultSignType(req.Provider)),
ExtraConfig: req.ExtraConfig,
IsDefault: req.IsDefault,
Status: status,
@@ -244,7 +244,7 @@ func (r *Repository) Create(req CreateRequest, actorID uint64, meta AuditMeta) (
// Update 更新配置
func (r *Repository) Update(id uint64, req UpdateRequest, actorID uint64, meta AuditMeta) (*ConfigDTO, error) {
if req.SignType != nil && *req.SignType != "" && *req.SignType != "MD5" {
if req.SignType != nil && *req.SignType != "" && !isValidSignType(*req.SignType) {
return nil, ErrInvalidSignType
}
if req.NotifyURL != nil && *req.NotifyURL == "" {
@@ -310,7 +310,7 @@ func (r *Repository) Update(id uint64, req UpdateRequest, actorID uint64, meta A
updates["sign_type"] = *req.SignType
}
if req.ExtraConfig != nil {
updates["extra_config"] = req.ExtraConfig
updates["extra_config"] = model.JSONMap(req.ExtraConfig)
}
if req.IsDefault != nil {
updates["is_default"] = *req.IsDefault
@@ -322,7 +322,7 @@ func (r *Repository) Update(id uint64, req UpdateRequest, actorID uint64, meta A
updates["environment"] = *req.Environment
}
if req.BusinessTags != nil {
updates["business_tags"] = req.BusinessTags
updates["business_tags"] = model.JSONArray(req.BusinessTags)
}
updates["updated_by"] = actorID
@@ -489,7 +489,7 @@ func (r *Repository) validateCreateRequest(req CreateRequest) error {
if req.MerchantID == "" {
return ErrMerchantIDRequired
}
if req.SignType != "" && req.SignType != "MD5" {
if req.SignType != "" && !isValidSignType(req.SignType) {
return ErrInvalidSignType
}
@@ -508,6 +508,29 @@ func (r *Repository) validateCreateRequest(req CreateRequest) error {
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
}
}
return nil
}
@@ -521,6 +544,31 @@ func firstNonEmpty(vals ...string) string {
return ""
}
func defaultSignType(provider string) string {
if provider == "lakala" {
return "SHA256withRSA"
}
return "MD5"
}
func isValidSignType(value string) bool {
return value == "MD5" || value == "SHA256withRSA"
}
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 ""
}
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 {