233 lines
5.4 KiB
Go
233 lines
5.4 KiB
Go
package payment
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"server/models"
|
|
|
|
beego "github.com/beego/beego/v2/server/web"
|
|
)
|
|
|
|
const (
|
|
ChannelWechat = "wechat"
|
|
ChannelAlipay = "alipay"
|
|
ChannelUnionPay = "unionpay"
|
|
ChannelCloudPay = "cloudpay"
|
|
ChannelPayPal = "paypal"
|
|
)
|
|
|
|
const (
|
|
StateSuccess = "success"
|
|
StatePending = "pending"
|
|
StateFailed = "failed"
|
|
StateClosed = "closed"
|
|
StateRefunded = "refunded"
|
|
)
|
|
|
|
const (
|
|
PayTypeQR = "qr"
|
|
PayTypeWeb = "web"
|
|
PayTypeH5 = "h5"
|
|
PayTypeJSAPI = "jsapi"
|
|
)
|
|
|
|
var (
|
|
ErrChannelNotConfigured = errors.New("渠道未配置或参数不完整")
|
|
ErrChannelDisabled = errors.New("渠道已停用")
|
|
ErrChannelNotFound = errors.New("渠道不存在")
|
|
)
|
|
|
|
type PayParams struct {
|
|
Channel string `json:"channel"`
|
|
PayType string `json:"pay_type"`
|
|
CodeURL string `json:"code_url,omitempty"`
|
|
RedirectURL string `json:"redirect_url,omitempty"`
|
|
Form string `json:"form,omitempty"`
|
|
JSAPI map[string]string `json:"jsapi,omitempty"`
|
|
ChannelTradeNo string `json:"channel_trade_no,omitempty"`
|
|
}
|
|
|
|
type ChannelState struct {
|
|
ChannelTradeNo string
|
|
TradeState string
|
|
Amount int64
|
|
PaidAt *time.Time
|
|
Raw string
|
|
}
|
|
|
|
type NotifyResult struct {
|
|
PayNo string
|
|
OutTradeNo string
|
|
ChannelTradeNo string
|
|
EventType string
|
|
EventID string
|
|
TradeState string
|
|
Amount int64
|
|
Paid bool
|
|
AckBody string
|
|
Raw string
|
|
}
|
|
|
|
type PrepayOption struct {
|
|
PayType string
|
|
OpenID string
|
|
}
|
|
|
|
type ChannelConfig struct {
|
|
ID uint64
|
|
Channel string
|
|
Name string
|
|
MerchantNo string
|
|
Enabled bool
|
|
CallbackURL string
|
|
Params map[string]string
|
|
Extra map[string]any
|
|
CertPaths map[string]string
|
|
}
|
|
|
|
func (c *ChannelConfig) Get(key string) string {
|
|
if c == nil || c.Params == nil {
|
|
return ""
|
|
}
|
|
return strings.TrimSpace(c.Params[key])
|
|
}
|
|
|
|
func (c *ChannelConfig) ExtraBool(key string, def bool) bool {
|
|
if c == nil || c.Extra == nil {
|
|
return def
|
|
}
|
|
if v, ok := c.Extra[key].(bool); ok {
|
|
return v
|
|
}
|
|
return def
|
|
}
|
|
|
|
func (c *ChannelConfig) EnsureUsable() error {
|
|
if c == nil || len(c.Params) == 0 {
|
|
return ErrChannelNotConfigured
|
|
}
|
|
if !c.Enabled {
|
|
return ErrChannelDisabled
|
|
}
|
|
return nil
|
|
}
|
|
|
|
type Channel interface {
|
|
Code() string
|
|
Name() string
|
|
Prepay(ctx context.Context, order *models.PlatformPaymentOrder, cfg *ChannelConfig, opt PrepayOption) (*PayParams, error)
|
|
Query(ctx context.Context, order *models.PlatformPaymentOrder, cfg *ChannelConfig) (*ChannelState, error)
|
|
ParseNotify(ctx context.Context, r *http.Request, cfg *ChannelConfig) (*NotifyResult, error)
|
|
Refund(ctx context.Context, order *models.PlatformPaymentOrder, refundNo string, amount int64, reason string, cfg *ChannelConfig) (string, error)
|
|
TestConnect(ctx context.Context, cfg *ChannelConfig) (string, error)
|
|
}
|
|
|
|
var (
|
|
registryMu sync.RWMutex
|
|
registry = map[string]Channel{}
|
|
)
|
|
|
|
func Register(ch Channel) {
|
|
registryMu.Lock()
|
|
defer registryMu.Unlock()
|
|
registry[ch.Code()] = ch
|
|
}
|
|
|
|
func GetChannelAdapter(code string) (Channel, error) {
|
|
registryMu.RLock()
|
|
defer registryMu.RUnlock()
|
|
ch, ok := registry[code]
|
|
if !ok {
|
|
return nil, ErrChannelNotFound
|
|
}
|
|
return ch, nil
|
|
}
|
|
|
|
func Channels() []Channel {
|
|
registryMu.RLock()
|
|
defer registryMu.RUnlock()
|
|
list := make([]Channel, 0, len(registry))
|
|
for _, ch := range registry {
|
|
list = append(list, ch)
|
|
}
|
|
return list
|
|
}
|
|
|
|
func LoadChannelConfig(channel string) (*ChannelConfig, error) {
|
|
row := &models.PlatformPaymentChannel{}
|
|
err := models.Orm.QueryTable(new(models.PlatformPaymentChannel)).
|
|
Filter("channel", channel).
|
|
Filter("delete_time__isnull", true).
|
|
One(row)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("渠道 %s 配置不存在", channel)
|
|
}
|
|
|
|
cfg := &ChannelConfig{
|
|
ID: row.ID,
|
|
Channel: row.Channel,
|
|
Name: row.Name,
|
|
MerchantNo: row.MerchantNo,
|
|
Enabled: row.Enabled == 1,
|
|
CallbackURL: row.CallbackURL,
|
|
Params: map[string]string{},
|
|
Extra: map[string]any{},
|
|
CertPaths: map[string]string{},
|
|
}
|
|
if row.ConfigJSON != nil && *row.ConfigJSON != "" {
|
|
plain, derr := DecryptConfig(*row.ConfigJSON)
|
|
if derr != nil {
|
|
return nil, fmt.Errorf("渠道 %s 参数解密失败: %w", channel, derr)
|
|
}
|
|
_ = json.Unmarshal([]byte(plain), &cfg.Params)
|
|
}
|
|
if row.ExtraJSON != nil && *row.ExtraJSON != "" {
|
|
_ = json.Unmarshal([]byte(*row.ExtraJSON), &cfg.Extra)
|
|
}
|
|
if row.CertJSON != nil && *row.CertJSON != "" {
|
|
_ = json.Unmarshal([]byte(*row.CertJSON), &cfg.CertPaths)
|
|
for key, val := range cfg.CertPaths {
|
|
cfg.CertPaths[key] = ResolveCertPath(val)
|
|
}
|
|
}
|
|
return cfg, nil
|
|
}
|
|
|
|
func LoadEnabledChannelConfig(channel string) (*ChannelConfig, error) {
|
|
cfg, err := LoadChannelConfig(channel)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if err := cfg.EnsureUsable(); err != nil {
|
|
return nil, err
|
|
}
|
|
return cfg, nil
|
|
}
|
|
|
|
func PublicBaseURL() string {
|
|
v, _ := beego.AppConfig.String("payment_callback_base")
|
|
return strings.TrimRight(strings.TrimSpace(v), "/")
|
|
}
|
|
|
|
func CallbackURL(channel string) string {
|
|
if cfg, err := LoadChannelConfig(channel); err == nil && cfg.CallbackURL != "" {
|
|
return cfg.CallbackURL
|
|
}
|
|
return PublicBaseURL() + "/api/payment/callback/" + channel
|
|
}
|
|
|
|
func init() {
|
|
Register(&WechatChannel{})
|
|
Register(&AlipayChannel{})
|
|
Register(&UnionPayChannel{})
|
|
Register(&CloudPayChannel{})
|
|
Register(&PayPalChannel{})
|
|
}
|