更新密码找回uniapp
This commit is contained in:
1 parent
7f9a66da0f
commit
3fdda89833
1304 files changed
+3503
-26132
No files matched your search
@@ -8,24 +8,8 @@ import (
|
||||
beego "github.com/beego/beego/v2/server/web"
|
||||
)
|
||||
|
||||
// =============================================================
|
||||
// 渠道证书落盘路径解析
|
||||
//
|
||||
// 历史实现把证书存成相对路径(certs/payment/<渠道>/xxx.pem),
|
||||
// 该相对路径在「上传时」与「读取时」分别相对各自的进程工作目录解析。
|
||||
// 一旦服务的工作目录发生变化(例如从 /www/wwwroot/api.yunzer.cn 换到 /app),
|
||||
// 库里记的路径就指向不存在的文件,报 “The system cannot find the file specified”。
|
||||
//
|
||||
// 因此读取时统一做一次解析:
|
||||
// - 落盘:写入 payment_cert_dir(未配置时退回工作目录下的 certs/payment),入库仍存相对路径
|
||||
// (本地开发与线上可能共用同一个库,存绝对路径会互相覆盖对方环境);
|
||||
// - 读取:先按当前工作目录解析,再按配置的 payment_cert_dir 根目录兜底解析。
|
||||
// =============================================================
|
||||
|
||||
// legacyCertPrefix 历史相对路径前缀,用于把 certs/payment/<渠道>/xxx.pem 剥成 <渠道>/xxx.pem
|
||||
const legacyCertPrefix = "certs/payment/"
|
||||
|
||||
// CertBaseDir 渠道证书落盘根目录(各渠道目录的父目录)
|
||||
func CertBaseDir() string {
|
||||
dir, _ := beego.AppConfig.String("payment_cert_dir")
|
||||
dir = strings.TrimSpace(dir)
|
||||
@@ -35,14 +19,10 @@ func CertBaseDir() string {
|
||||
return dir
|
||||
}
|
||||
|
||||
// CertDir 某渠道的证书目录
|
||||
func CertDir(channel string) string {
|
||||
return filepath.Join(CertBaseDir(), filepath.Base(channel))
|
||||
}
|
||||
|
||||
// ResolveCertPath 把库中可能存的相对路径解析为当前可读的路径。
|
||||
// 依次尝试:绝对路径 -> 相对当前工作目录 -> 相对 payment_cert_dir 根目录(兼容历史相对路径)。
|
||||
// 都读不到时原样返回,让上层的 os.ReadFile 报出原始路径便于排查。
|
||||
func ResolveCertPath(p string) string {
|
||||
p = strings.TrimSpace(p)
|
||||
if p == "" {
|
||||
@@ -51,22 +31,18 @@ func ResolveCertPath(p string) string {
|
||||
if filepath.IsAbs(p) {
|
||||
return p
|
||||
}
|
||||
// 相对当前工作目录(历史行为,能读到就不动)
|
||||
if certPathExists(p) {
|
||||
return p
|
||||
}
|
||||
// 兼容历史相对路径:剥掉 certs/payment 前缀后挂到配置的根目录下
|
||||
if cand := filepath.Join(CertBaseDir(), certRelative(p)); certPathExists(cand) {
|
||||
return cand
|
||||
}
|
||||
// 兜底:按文件名在根目录下找
|
||||
if cand := filepath.Join(CertBaseDir(), filepath.Base(p)); certPathExists(cand) {
|
||||
return cand
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
// certRelative 从历史相对路径中剥掉 certs/payment 前缀
|
||||
func certRelative(p string) string {
|
||||
norm := filepath.ToSlash(filepath.Clean(p))
|
||||
if i := strings.Index(norm, legacyCertPrefix); i >= 0 {
|
||||
|
||||
@@ -15,14 +15,6 @@ import (
|
||||
beego "github.com/beego/beego/v2/server/web"
|
||||
)
|
||||
|
||||
// =============================================================
|
||||
// 渠道适配器接口与运行时配置
|
||||
//
|
||||
// 五个渠道的差异全部收敛在各 Channel 实现里(wechat/alipay/unionpay/cloudpay/paypal),
|
||||
// 支付服务(service.go)只面向本接口编程,业务页面不出现渠道 if-else。
|
||||
// =============================================================
|
||||
|
||||
// 渠道标识(与 yz_platform_payment_channel.channel、前端页面一一对应)
|
||||
const (
|
||||
ChannelWechat = "wechat"
|
||||
ChannelAlipay = "alipay"
|
||||
@@ -31,7 +23,6 @@ const (
|
||||
ChannelPayPal = "paypal"
|
||||
)
|
||||
|
||||
// 归一化交易状态(各渠道状态统一映射到这几个值)
|
||||
const (
|
||||
StateSuccess = "success"
|
||||
StatePending = "pending"
|
||||
@@ -40,12 +31,11 @@ const (
|
||||
StateRefunded = "refunded"
|
||||
)
|
||||
|
||||
// 预下单方式
|
||||
const (
|
||||
PayTypeQR = "qr" // 扫码(微信 Native)
|
||||
PayTypeWeb = "web" // PC 网页跳转(支付宝电脑网站支付 / 银联网关 / PayPal)
|
||||
PayTypeH5 = "h5" // 手机网页跳转
|
||||
PayTypeJSAPI = "jsapi" // 公众号内支付(需要 OpenID)
|
||||
PayTypeQR = "qr"
|
||||
PayTypeWeb = "web"
|
||||
PayTypeH5 = "h5"
|
||||
PayTypeJSAPI = "jsapi"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -54,47 +44,42 @@ var (
|
||||
ErrChannelNotFound = errors.New("渠道不存在")
|
||||
)
|
||||
|
||||
// PayParams 渠道下单后返回给前端的拉起支付参数
|
||||
type PayParams struct {
|
||||
Channel string `json:"channel"`
|
||||
PayType string `json:"pay_type"`
|
||||
CodeURL string `json:"code_url,omitempty"` // 扫码:二维码内容
|
||||
RedirectURL string `json:"redirect_url,omitempty"` // 跳转:直接 302 或前端 window.open
|
||||
Form string `json:"form,omitempty"` // 表单:写入页面后自动提交(银联前台跳转等)
|
||||
JSAPI map[string]string `json:"jsapi,omitempty"` // 公众号内:WeixinJSBridge 调用参数
|
||||
ChannelTradeNo string `json:"channel_trade_no,omitempty"` // 渠道侧单号(如有)
|
||||
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"`
|
||||
}
|
||||
|
||||
// ChannelState 渠道侧交易状态(已归一化)
|
||||
type ChannelState struct {
|
||||
ChannelTradeNo string
|
||||
TradeState string // StateSuccess / StatePending / StateFailed / StateClosed
|
||||
Amount int64 // 分
|
||||
PaidAt *time.Time // 渠道侧支付完成时间
|
||||
Raw string // 渠道原始响应(排查用)
|
||||
TradeState string
|
||||
Amount int64
|
||||
PaidAt *time.Time
|
||||
Raw string
|
||||
}
|
||||
|
||||
// NotifyResult 渠道异步通知解析结果(已验签、已解密)
|
||||
type NotifyResult struct {
|
||||
PayNo string
|
||||
OutTradeNo string
|
||||
ChannelTradeNo string
|
||||
EventType string // 渠道事件类型原文
|
||||
EventID string // 渠道事件/通知 ID(用于幂等去重)
|
||||
TradeState string // 归一化状态
|
||||
Amount int64 // 分
|
||||
Paid bool // 是否支付成功事件
|
||||
AckBody string // 需要原样返回给渠道的响应体(SUCCESS / success / ok / "")
|
||||
Raw string // 通知报文(脱敏后入库)
|
||||
EventType string
|
||||
EventID string
|
||||
TradeState string
|
||||
Amount int64
|
||||
Paid bool
|
||||
AckBody string
|
||||
Raw string
|
||||
}
|
||||
|
||||
// PrepayOption 预下单附加参数
|
||||
type PrepayOption struct {
|
||||
PayType string // PayTypeQR / PayTypeWeb / PayTypeH5 / PayTypeJSAPI;空值由适配器给默认
|
||||
OpenID string // JSAPI 支付必填
|
||||
PayType string
|
||||
OpenID string
|
||||
}
|
||||
|
||||
// ChannelConfig 渠道运行时配置(敏感参数已解密)
|
||||
type ChannelConfig struct {
|
||||
ID uint64
|
||||
Channel string
|
||||
@@ -102,12 +87,11 @@ type ChannelConfig struct {
|
||||
MerchantNo string
|
||||
Enabled bool
|
||||
CallbackURL string
|
||||
Params map[string]string // 解密后的渠道参数
|
||||
Extra map[string]any // 渠道扩展开关(云闪付标识、PayPal 环境等)
|
||||
CertPaths map[string]string // 证书文件路径(cert_json)
|
||||
Params map[string]string
|
||||
Extra map[string]any
|
||||
CertPaths map[string]string
|
||||
}
|
||||
|
||||
// Get 读取渠道参数
|
||||
func (c *ChannelConfig) Get(key string) string {
|
||||
if c == nil || c.Params == nil {
|
||||
return ""
|
||||
@@ -115,7 +99,6 @@ func (c *ChannelConfig) Get(key string) string {
|
||||
return strings.TrimSpace(c.Params[key])
|
||||
}
|
||||
|
||||
// ExtraBool 读取扩展开关
|
||||
func (c *ChannelConfig) ExtraBool(key string, def bool) bool {
|
||||
if c == nil || c.Extra == nil {
|
||||
return def
|
||||
@@ -126,7 +109,6 @@ func (c *ChannelConfig) ExtraBool(key string, def bool) bool {
|
||||
return def
|
||||
}
|
||||
|
||||
// EnsureUsable 校验配置可用(已启用且参数非空)
|
||||
func (c *ChannelConfig) EnsureUsable() error {
|
||||
if c == nil || len(c.Params) == 0 {
|
||||
return ErrChannelNotConfigured
|
||||
@@ -137,19 +119,13 @@ func (c *ChannelConfig) EnsureUsable() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Channel 渠道适配器接口
|
||||
type Channel interface {
|
||||
Code() string
|
||||
Name() string
|
||||
// Prepay 预下单,返回拉起支付参数
|
||||
Prepay(ctx context.Context, order *models.PlatformPaymentOrder, cfg *ChannelConfig, opt PrepayOption) (*PayParams, error)
|
||||
// Query 主动查询渠道侧交易状态
|
||||
Query(ctx context.Context, order *models.PlatformPaymentOrder, cfg *ChannelConfig) (*ChannelState, error)
|
||||
// ParseNotify 解析并验签渠道异步通知
|
||||
ParseNotify(ctx context.Context, r *http.Request, cfg *ChannelConfig) (*NotifyResult, error)
|
||||
// Refund 原路退回(兜底能力),返回渠道退回流水号
|
||||
Refund(ctx context.Context, order *models.PlatformPaymentOrder, refundNo string, amount int64, reason string, cfg *ChannelConfig) (string, error)
|
||||
// TestConnect 连通性/凭证校验,返回人类可读的结果说明
|
||||
TestConnect(ctx context.Context, cfg *ChannelConfig) (string, error)
|
||||
}
|
||||
|
||||
@@ -158,14 +134,12 @@ var (
|
||||
registry = map[string]Channel{}
|
||||
)
|
||||
|
||||
// Register 注册渠道适配器
|
||||
func Register(ch Channel) {
|
||||
registryMu.Lock()
|
||||
defer registryMu.Unlock()
|
||||
registry[ch.Code()] = ch
|
||||
}
|
||||
|
||||
// GetChannelAdapter 取渠道适配器
|
||||
func GetChannelAdapter(code string) (Channel, error) {
|
||||
registryMu.RLock()
|
||||
defer registryMu.RUnlock()
|
||||
@@ -176,7 +150,6 @@ func GetChannelAdapter(code string) (Channel, error) {
|
||||
return ch, nil
|
||||
}
|
||||
|
||||
// Channels 返回全部已注册适配器
|
||||
func Channels() []Channel {
|
||||
registryMu.RLock()
|
||||
defer registryMu.RUnlock()
|
||||
@@ -187,7 +160,6 @@ func Channels() []Channel {
|
||||
return list
|
||||
}
|
||||
|
||||
// LoadChannelConfig 从库加载渠道配置(敏感参数解密)
|
||||
func LoadChannelConfig(channel string) (*ChannelConfig, error) {
|
||||
row := &models.PlatformPaymentChannel{}
|
||||
err := models.Orm.QueryTable(new(models.PlatformPaymentChannel)).
|
||||
@@ -221,7 +193,6 @@ func LoadChannelConfig(channel string) (*ChannelConfig, error) {
|
||||
}
|
||||
if row.CertJSON != nil && *row.CertJSON != "" {
|
||||
_ = json.Unmarshal([]byte(*row.CertJSON), &cfg.CertPaths)
|
||||
// 历史数据存的是相对路径,这里统一解析为当前可读路径,避免依赖进程工作目录
|
||||
for key, val := range cfg.CertPaths {
|
||||
cfg.CertPaths[key] = ResolveCertPath(val)
|
||||
}
|
||||
@@ -229,7 +200,6 @@ func LoadChannelConfig(channel string) (*ChannelConfig, error) {
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// LoadEnabledChannelConfig 加载「已启用且参数完整」的渠道配置
|
||||
func LoadEnabledChannelConfig(channel string) (*ChannelConfig, error) {
|
||||
cfg, err := LoadChannelConfig(channel)
|
||||
if err != nil {
|
||||
@@ -241,14 +211,11 @@ func LoadEnabledChannelConfig(channel string) (*ChannelConfig, error) {
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// PublicBaseURL 对外域名基址:app.conf 的 payment_callback_base(如 https://pay.example.com)
|
||||
// 未配置时返回空串,回调地址形如 /api/payment/callback/wechat(由网关补齐域名)。
|
||||
func PublicBaseURL() string {
|
||||
v, _ := beego.AppConfig.String("payment_callback_base")
|
||||
return strings.TrimRight(strings.TrimSpace(v), "/")
|
||||
}
|
||||
|
||||
// CallbackURL 渠道回调地址(与渠道配置表 callback_url 保持一致)
|
||||
func CallbackURL(channel string) string {
|
||||
if cfg, err := LoadChannelConfig(channel); err == nil && cfg.CallbackURL != "" {
|
||||
return cfg.CallbackURL
|
||||
|
||||
@@ -12,14 +12,6 @@ import (
|
||||
"github.com/smartwalle/alipay/v3"
|
||||
)
|
||||
|
||||
// AlipayChannel 支付宝(电脑网站支付 / 手机网站支付,RSA2)
|
||||
//
|
||||
// 渠道参数(config_json):
|
||||
//
|
||||
// appid 开放平台应用 APPID
|
||||
// app_private_key 应用私钥(RSA2,PKCS8)
|
||||
// alipay_public_key 支付宝公钥(回显公钥,用于验签)
|
||||
// is_production "1" 正式环境 / 其他为沙箱
|
||||
type AlipayChannel struct{}
|
||||
|
||||
func (c *AlipayChannel) Code() string { return ChannelAlipay }
|
||||
@@ -64,7 +56,6 @@ func (c *AlipayChannel) Prepay(ctx context.Context, order *models.PlatformPaymen
|
||||
}
|
||||
|
||||
if strings.EqualFold(opt.PayType, PayTypeH5) {
|
||||
// 手机网站支付
|
||||
trade.ProductCode = "QUICK_WAP_WAY"
|
||||
u, err := client.TradeWapPay(alipay.TradeWapPay{Trade: trade})
|
||||
if err != nil {
|
||||
@@ -73,7 +64,6 @@ func (c *AlipayChannel) Prepay(ctx context.Context, order *models.PlatformPaymen
|
||||
return &PayParams{Channel: ChannelAlipay, PayType: PayTypeH5, RedirectURL: u.String()}, nil
|
||||
}
|
||||
|
||||
// 默认:电脑网站支付(PC 收银台)
|
||||
trade.ProductCode = "FAST_INSTANT_TRADE_PAY"
|
||||
u, err := client.TradePagePay(alipay.TradePagePay{Trade: trade})
|
||||
if err != nil {
|
||||
@@ -82,7 +72,6 @@ func (c *AlipayChannel) Prepay(ctx context.Context, order *models.PlatformPaymen
|
||||
return &PayParams{Channel: ChannelAlipay, PayType: PayTypeWeb, RedirectURL: u.String()}, nil
|
||||
}
|
||||
|
||||
// normalizeAlipayStatus 支付宝交易状态 -> 归一化状态
|
||||
func normalizeAlipayStatus(status alipay.TradeStatus) string {
|
||||
switch status {
|
||||
case alipay.TradeStatusSuccess, alipay.TradeStatusFinished:
|
||||
@@ -105,7 +94,6 @@ func (c *AlipayChannel) Query(ctx context.Context, order *models.PlatformPayment
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("支付宝查询订单失败: %w", err)
|
||||
}
|
||||
// 交易不存在(如超时未付被渠道关闭):不视为失败,返回待支付以便走关闭逻辑
|
||||
if rsp.Code != "10000" {
|
||||
if rsp.SubCode == "ACQ.TRADE_NOT_EXIST" {
|
||||
return &ChannelState{TradeState: StatePending, Raw: rsp.SubMsg}, nil
|
||||
@@ -182,7 +170,6 @@ func (c *AlipayChannel) TestConnect(ctx context.Context, cfg *ChannelConfig) (st
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
// 查询一笔必然不存在的交易:能返回「交易不存在」即说明 APPID 与签名配置正确
|
||||
rsp, err := client.TradeQuery(ctx, alipay.TradeQuery{OutTradeNo: "__connect_test__"})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("支付宝凭证校验失败: %w", err)
|
||||
|
||||
@@ -15,18 +15,6 @@ import (
|
||||
"github.com/plutov/paypal/v4"
|
||||
)
|
||||
|
||||
// PayPalChannel PayPal(Checkout v2 + Webhook)
|
||||
//
|
||||
// 渠道参数(config_json):
|
||||
//
|
||||
// client_id REST App Client ID
|
||||
// client_secret REST App Secret
|
||||
// webhook_id Webhook ID(用于验签)
|
||||
// currency 币种,默认 USD
|
||||
//
|
||||
// 扩展(extra_json):
|
||||
//
|
||||
// env sandbox / live
|
||||
type PayPalChannel struct{}
|
||||
|
||||
func (c *PayPalChannel) Code() string { return ChannelPayPal }
|
||||
@@ -81,7 +69,6 @@ func (c *PayPalChannel) Prepay(ctx context.Context, order *models.PlatformPaymen
|
||||
return nil, fmt.Errorf("PayPal 下单失败: %w", err)
|
||||
}
|
||||
|
||||
// v2 的跳转链接 rel 为 payer-action(旧版为 approve)
|
||||
approve := ""
|
||||
for _, l := range payOrder.Links {
|
||||
if l.Rel == "approve" || l.Rel == "payer-action" {
|
||||
@@ -96,7 +83,7 @@ func (c *PayPalChannel) Prepay(ctx context.Context, order *models.PlatformPaymen
|
||||
Channel: ChannelPayPal,
|
||||
PayType: PayTypeWeb,
|
||||
RedirectURL: approve,
|
||||
ChannelTradeNo: payOrder.ID, // PayPal 订单号,回调后替换为 capture id
|
||||
ChannelTradeNo: payOrder.ID,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -121,7 +108,6 @@ func (c *PayPalChannel) Query(ctx context.Context, order *models.PlatformPayment
|
||||
case "VOIDED":
|
||||
state.TradeState = StateClosed
|
||||
case "APPROVED":
|
||||
// 用户已批准但未捕获,等待 webhook 或人工捕获
|
||||
state.TradeState = StatePending
|
||||
default:
|
||||
state.TradeState = StatePending
|
||||
@@ -161,7 +147,6 @@ func (c *PayPalChannel) ParseNotify(ctx context.Context, r *http.Request, cfg *C
|
||||
return nil, fmt.Errorf("PayPal 参数不完整:需要 webhook_id")
|
||||
}
|
||||
|
||||
// VerifyWebhookSignature 会读取请求体,先读出来再回填,供后面解析事件内容
|
||||
raw, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("读取 PayPal 通知失败: %w", err)
|
||||
|
||||
@@ -24,24 +24,6 @@ import (
|
||||
pkcs12 "software.sslmate.com/src/go-pkcs12"
|
||||
)
|
||||
|
||||
// UnionPayChannel 银联全渠道(PC 网关支付 / 手机控件支付)
|
||||
//
|
||||
// 银联没有官方 Go SDK,这里按「全渠道支付平台产品接口规范」实现签名与请求:
|
||||
// - 签名:SHA256withRSA,字段按 key ASCII 升序拼 key=value&... 后私钥签名,base64 放入 signature;
|
||||
// - 下单:POST /gateway/api/frontTransReq.do(前台跳转,返回自动提交表单);
|
||||
// - 查询:POST /gateway/api/queryTrans.do(txnType=00);
|
||||
// - 退货:POST /gateway/api/backTransReq.do(txnType=04)。
|
||||
//
|
||||
// 渠道参数(config_json):
|
||||
//
|
||||
// mer_id 商户号
|
||||
// acq_ins_code 收单机构代码
|
||||
// cert_password 商户证书密码
|
||||
// is_production "1" 生产网关 / 其他为测试网关
|
||||
//
|
||||
// 证书(cert_json):
|
||||
//
|
||||
// cert_path 商户证书(.pfx / .p12,或 .cer + .pem 私钥组合)
|
||||
type UnionPayChannel struct{}
|
||||
|
||||
func (c *UnionPayChannel) Code() string { return ChannelUnionPay }
|
||||
@@ -52,7 +34,7 @@ const (
|
||||
unionPayGatewayTest = "https://gateway.test.95516.com"
|
||||
unionPayVersion = "5.1.0"
|
||||
unionPayCurrencyCNY = "156"
|
||||
unionPayDefaultBizType = "000201" // B2C 网关支付
|
||||
unionPayDefaultBizType = "000201"
|
||||
)
|
||||
|
||||
func unionPayGateway(cfg *ChannelConfig) string {
|
||||
@@ -62,7 +44,6 @@ func unionPayGateway(cfg *ChannelConfig) string {
|
||||
return unionPayGatewayTest
|
||||
}
|
||||
|
||||
// unionPayKey 加载商户私钥与证书(支持 .pfx/.p12 与 .pem+.cer 两种形式)
|
||||
func unionPayKey(cfg *ChannelConfig) (*rsa.PrivateKey, *x509.Certificate, error) {
|
||||
certPath := cfg.CertPaths["cert_path"]
|
||||
if certPath == "" {
|
||||
@@ -133,12 +114,10 @@ func loadCertFile(path string) (*x509.Certificate, error) {
|
||||
return x509.ParseCertificate(block.Bytes)
|
||||
}
|
||||
|
||||
// unionPayCertID 银联证书序列号(SerialNumber 十六进制大写)
|
||||
func unionPayCertID(cert *x509.Certificate) string {
|
||||
return strings.ToUpper(fmt.Sprintf("%x", cert.SerialNumber))
|
||||
}
|
||||
|
||||
// unionPaySign 银联签名:key 升序拼 key=value&... 后 SHA256withRSA
|
||||
func unionPaySign(params map[string]string, key *rsa.PrivateKey) (string, error) {
|
||||
keys := make([]string, 0, len(params))
|
||||
for k, v := range params {
|
||||
@@ -160,7 +139,6 @@ func unionPaySign(params map[string]string, key *rsa.PrivateKey) (string, error)
|
||||
return base64.StdEncoding.EncodeToString(sig), nil
|
||||
}
|
||||
|
||||
// unionPaySigned 组装带签名与 certId 的请求参数
|
||||
func unionPaySigned(cfg *ChannelConfig, priv *rsa.PrivateKey, cert *x509.Certificate, extra map[string]string) (map[string]string, error) {
|
||||
params := map[string]string{
|
||||
"version": unionPayVersion,
|
||||
@@ -183,7 +161,6 @@ func unionPaySigned(cfg *ChannelConfig, priv *rsa.PrivateKey, cert *x509.Certifi
|
||||
return params, nil
|
||||
}
|
||||
|
||||
// unionPayPostRaw 提交表单并返回原始响应
|
||||
func unionPayPostRaw(ctx context.Context, endpoint string, params map[string]string) (string, error) {
|
||||
form := url.Values{}
|
||||
for k, v := range params {
|
||||
@@ -209,7 +186,6 @@ func unionPayPostRaw(ctx context.Context, endpoint string, params map[string]str
|
||||
return string(body), nil
|
||||
}
|
||||
|
||||
// unionPayPostForm 解析 form-urlencoded 响应(queryTrans / backTransReq.do)
|
||||
func unionPayPostForm(ctx context.Context, endpoint string, params map[string]string) (url.Values, error) {
|
||||
body, err := unionPayPostRaw(ctx, endpoint, params)
|
||||
if err != nil {
|
||||
@@ -249,7 +225,6 @@ func (c *UnionPayChannel) Prepay(ctx context.Context, order *models.PlatformPaym
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// 前台跳转:银联返回自动提交表单,前端写入页面即可拉起收银台
|
||||
html, err := unionPayPostRaw(ctx, unionPayGateway(cfg)+"/gateway/api/frontTransReq.do", params)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("银联下单失败: %w", err)
|
||||
@@ -384,8 +359,6 @@ func (c *UnionPayChannel) TestConnect(ctx context.Context, cfg *ChannelConfig) (
|
||||
return fmt.Sprintf("连接成功:证书加载与签名校验通过(证书序列号 %s,网关 %s)", unionPayCertID(cert), unionPayGateway(cfg)), nil
|
||||
}
|
||||
|
||||
// CloudPayChannel 云闪付:走银联通道,商户参数与证书完全复用银联配置;
|
||||
// 收银台是否展示云闪付标识由 extra_json.show_logo 控制(由前端收银台读取),适配器层面与银联一致。
|
||||
type CloudPayChannel struct {
|
||||
UnionPayChannel
|
||||
}
|
||||
|
||||
@@ -29,34 +29,13 @@ import (
|
||||
"github.com/wechatpay-apiv3/wechatpay-go/utils"
|
||||
)
|
||||
|
||||
// WechatChannel 微信支付(JSAPI / Native 扫码)
|
||||
//
|
||||
// 渠道参数(config_json):
|
||||
//
|
||||
// mch_id 商户号
|
||||
// appid 公众号 / 小程序 APPID
|
||||
// cert_serial_no 商户 API 证书序列号
|
||||
// api_v3_key APIv3 密钥
|
||||
// pub_key_id 微信支付公钥 ID(PUB_KEY_ID_ 开头;公钥模式必填,与 pub_key 成对)
|
||||
// pub_key 微信支付公钥 PEM 内容(公钥模式必填)
|
||||
//
|
||||
// 证书(cert_json):
|
||||
//
|
||||
// key_path apiclient_key.pem 上传后的服务端路径(不入库内容,见渠道证书上传接口)
|
||||
type WechatChannel struct{}
|
||||
|
||||
// connectTestOutTradeNo 测试连接用的探测单号:查询不存在的订单,返回 404 即视为鉴权链路通过
|
||||
const connectTestOutTradeNo = "CONNECT_TEST_NO_0000000000000001"
|
||||
|
||||
func (c *WechatChannel) Code() string { return ChannelWechat }
|
||||
func (c *WechatChannel) Name() string { return "微信支付" }
|
||||
|
||||
// buildClient 创建微信支付 APIv3 客户端(带自动证书更新与加解密能力)
|
||||
//
|
||||
// 初始化模式自动选择:
|
||||
// - 配置了「微信支付公钥」(pub_key_id + pub_key)时走公钥模式:
|
||||
// 2024 年后新开通商户默认使用公钥,平台证书下载接口对其停用(403 NOT_ENOUGH);
|
||||
// - 否则回退平台证书模式(自动下载并轮换平台证书,老商户适用)。
|
||||
func (c *WechatChannel) buildClient(cfg *ChannelConfig) (*core.Client, string, error) {
|
||||
mchID := cfg.Get("mch_id")
|
||||
serial := cfg.Get("cert_serial_no")
|
||||
@@ -117,7 +96,6 @@ func (c *WechatChannel) Prepay(ctx context.Context, order *models.PlatformPaymen
|
||||
notifyURL := cfg.CallbackURL
|
||||
amount := &native.Amount{Total: core.Int64(order.Amount), Currency: core.String("CNY")}
|
||||
|
||||
// 公众号内支付
|
||||
if strings.EqualFold(opt.PayType, PayTypeJSAPI) {
|
||||
if opt.OpenID == "" {
|
||||
return nil, fmt.Errorf("微信 JSAPI 支付需要 OpenID")
|
||||
@@ -139,7 +117,6 @@ func (c *WechatChannel) Prepay(ctx context.Context, order *models.PlatformPaymen
|
||||
return nil, fmt.Errorf("微信 JSAPI 下单未返回 prepay_id")
|
||||
}
|
||||
|
||||
// 按微信规范自行生成 JSAPI 调起参数(timeStamp/nonceStr/paySign)
|
||||
ts := strconv.FormatInt(time.Now().Unix(), 10)
|
||||
nonce, _ := randomNonce(16)
|
||||
message := appID + "\n" + ts + "\n" + nonce + "\n" + "prepay_id=" + *resp.PrepayId + "\n"
|
||||
@@ -161,7 +138,6 @@ func (c *WechatChannel) Prepay(ctx context.Context, order *models.PlatformPaymen
|
||||
}, nil
|
||||
}
|
||||
|
||||
// 默认:Native 扫码(PC 收银台)
|
||||
req := native.PrepayRequest{
|
||||
Appid: core.String(appID),
|
||||
Mchid: core.String(mchID),
|
||||
@@ -184,7 +160,6 @@ func (c *WechatChannel) Prepay(ctx context.Context, order *models.PlatformPaymen
|
||||
return &PayParams{Channel: ChannelWechat, PayType: PayTypeQR, CodeURL: *resp.CodeUrl}, nil
|
||||
}
|
||||
|
||||
// normalizeWechatState 微信交易状态 -> 归一化状态
|
||||
func normalizeWechatState(state string) string {
|
||||
switch state {
|
||||
case "SUCCESS":
|
||||
@@ -241,7 +216,6 @@ func (c *WechatChannel) ParseNotify(ctx context.Context, r *http.Request, cfg *C
|
||||
mchID := cfg.Get("mch_id")
|
||||
apiV3Key := cfg.Get("api_v3_key")
|
||||
|
||||
// 验签器按初始化模式选择:公钥模式用微信支付公钥,平台证书模式用下载器维护的证书访问器
|
||||
var verifier auth.Verifier
|
||||
pubKeyID := cfg.Get("pub_key_id")
|
||||
pubKeyPEM := cfg.Get("pub_key")
|
||||
@@ -301,7 +275,7 @@ func (c *WechatChannel) Refund(ctx context.Context, order *models.PlatformPaymen
|
||||
"out_trade_no": order.PayNo,
|
||||
"out_refund_no": refundNo,
|
||||
"reason": reason,
|
||||
"notify_url": "", // 退回结果以主动查询为准;如需退回回调,配置后填入
|
||||
"notify_url": "",
|
||||
"amount": map[string]any{
|
||||
"refund": amount,
|
||||
"total": order.Amount,
|
||||
@@ -329,7 +303,6 @@ func (c *WechatChannel) TestConnect(ctx context.Context, cfg *ChannelConfig) (st
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
// 公钥模式:/v3/certificates 已对其停用,改查一笔不存在的订单验证鉴权(纯读,不产生交易)
|
||||
if cfg.Get("pub_key_id") != "" && cfg.Get("pub_key") != "" {
|
||||
_, qerr := client.Get(ctx,
|
||||
consts.WechatPayAPIServer+"/v3/pay/transactions/out-trade-no/"+connectTestOutTradeNo+"?mchid="+mchID)
|
||||
@@ -338,12 +311,10 @@ func (c *WechatChannel) TestConnect(ctx context.Context, cfg *ChannelConfig) (st
|
||||
}
|
||||
var apiErr *core.APIError
|
||||
if errors.As(qerr, &apiErr) && apiErr.StatusCode == http.StatusNotFound {
|
||||
// 订单不存在属预期结果:说明请求签名与应答验签链路均已通过
|
||||
return "连接成功:商户私钥签名与微信支付公钥验签均通过(公钥模式)", nil
|
||||
}
|
||||
return "", fmt.Errorf("微信凭证校验失败: %w", qerr)
|
||||
}
|
||||
// 平台证书模式:平台证书接口只做签名校验,不产生任何交易
|
||||
result, err := client.Get(ctx, consts.WechatPayAPIServer+"/v3/certificates")
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("微信凭证校验失败: %w", err)
|
||||
@@ -352,8 +323,6 @@ func (c *WechatChannel) TestConnect(ctx context.Context, cfg *ChannelConfig) (st
|
||||
return fmt.Sprintf("连接成功:商户证书与 APIv3 密钥校验通过(平台证书响应 %d 字节)", len(body)), nil
|
||||
}
|
||||
|
||||
/* ---------------- 小工具 ---------------- */
|
||||
|
||||
func valueOrEmpty(v *string) string {
|
||||
if v == nil {
|
||||
return ""
|
||||
@@ -361,7 +330,6 @@ func valueOrEmpty(v *string) string {
|
||||
return *v
|
||||
}
|
||||
|
||||
// randomNonce 生成 n 字节随机数的十六进制串
|
||||
func randomNonce(n int) (string, error) {
|
||||
buf := make([]byte, n)
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
|
||||
@@ -14,19 +14,11 @@ import (
|
||||
beelog "github.com/beego/beego/v2/core/logs"
|
||||
)
|
||||
|
||||
/* =============================================================
|
||||
* 推广佣金:规则匹配 -> 金额计算 -> 佣金单生成(幂等)-> 发放登记
|
||||
* 佣金是平台自有资金支出,与租户收款资金流解耦。
|
||||
* ============================================================= */
|
||||
|
||||
// OnOrderPaid 支付成功后生成佣金单(幂等:同一支付单 + 同一推广方只生成一张)
|
||||
// 无推广方 / 无匹配规则 / 佣金金额为 0 时返回 (nil, nil)。
|
||||
func OnOrderPaid(ctx context.Context, order *models.PlatformPaymentOrder) (*models.PlatformCommissionOrder, error) {
|
||||
if order == nil || order.PromoterID == "" {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// 幂等查重
|
||||
exist := &models.PlatformCommissionOrder{}
|
||||
err := models.Orm.QueryTable(new(models.PlatformCommissionOrder)).
|
||||
Filter("pay_no", order.PayNo).
|
||||
@@ -69,7 +61,6 @@ func OnOrderPaid(ctx context.Context, order *models.PlatformPaymentOrder) (*mode
|
||||
}
|
||||
if _, err := models.Orm.Insert(row); err != nil {
|
||||
if strings.Contains(err.Error(), "Duplicate") || strings.Contains(err.Error(), "1062") {
|
||||
// 并发生成命中唯一键:查回已有记录
|
||||
return exist, nil
|
||||
}
|
||||
return nil, fmt.Errorf("创建佣金单失败: %w", err)
|
||||
@@ -78,7 +69,6 @@ func OnOrderPaid(ctx context.Context, order *models.PlatformPaymentOrder) (*mode
|
||||
return row, nil
|
||||
}
|
||||
|
||||
// matchCommissionRule 匹配启用中的佣金规则(同类型规则取最新一条)
|
||||
func matchCommissionRule(orderType string) (*models.PlatformCommissionRule, error) {
|
||||
var rules []models.PlatformCommissionRule
|
||||
_, err := models.Orm.QueryTable(new(models.PlatformCommissionRule)).
|
||||
@@ -97,14 +87,13 @@ func matchCommissionRule(orderType string) (*models.PlatformCommissionRule, erro
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// calcCommissionAmount 按规则计算佣金(分),向下取整
|
||||
func calcCommissionAmount(rule *models.PlatformCommissionRule, baseAmount int64) int64 {
|
||||
if rule == nil || baseAmount <= 0 {
|
||||
return 0
|
||||
}
|
||||
switch rule.CalcType {
|
||||
case models.CommissionCalcPercent:
|
||||
return baseAmount * rule.Value / 10000 // value = 百分比 × 100
|
||||
return baseAmount * rule.Value / 10000
|
||||
case models.CommissionCalcFixed:
|
||||
return rule.Value
|
||||
case models.CommissionCalcTiered:
|
||||
@@ -132,19 +121,15 @@ func parseTiers(raw *string) []models.CommissionTier {
|
||||
return tiers
|
||||
}
|
||||
|
||||
/* ---------------- 佣金台账查询与发放 ---------------- */
|
||||
|
||||
// CommissionListInput 台账查询条件
|
||||
type CommissionListInput struct {
|
||||
Promoter string
|
||||
Status string
|
||||
StartTime string // YYYY-MM-DD
|
||||
StartTime string
|
||||
EndTime string
|
||||
Page int
|
||||
PageSize int
|
||||
}
|
||||
|
||||
// ListCommissions 佣金台账分页
|
||||
func ListCommissions(in CommissionListInput) ([]models.PlatformCommissionOrder, int64, error) {
|
||||
qs := models.Orm.QueryTable(new(models.PlatformCommissionOrder)).Filter("delete_time__isnull", true)
|
||||
if in.Promoter != "" {
|
||||
@@ -178,16 +163,12 @@ func ListCommissions(in CommissionListInput) ([]models.PlatformCommissionOrder,
|
||||
return rows, total, err
|
||||
}
|
||||
|
||||
// CommissionStats 台账统计(应付 / 已付 / 待处理笔数)
|
||||
type CommissionStats struct {
|
||||
PayableAmount int64 `json:"payable_amount"`
|
||||
PaidAmount int64 `json:"paid_amount"`
|
||||
PendingCount int64 `json:"pending_count"`
|
||||
}
|
||||
|
||||
// GetCommissionStats 统计口径:
|
||||
//
|
||||
// 应付总额 = status=payable 的金额合计;已付总额 = status=settled;待处理笔数 = payable + tax_processing。
|
||||
func GetCommissionStats() (*CommissionStats, error) {
|
||||
type row struct {
|
||||
Total int64 `orm:"column(total)"`
|
||||
@@ -221,7 +202,6 @@ func GetCommissionStats() (*CommissionStats, error) {
|
||||
return stats, nil
|
||||
}
|
||||
|
||||
// MarkCommissionPaidInput 标记已付入参
|
||||
type MarkCommissionPaidInput struct {
|
||||
ID uint64
|
||||
PayMethod string
|
||||
@@ -231,7 +211,6 @@ type MarkCommissionPaidInput struct {
|
||||
OperatorName string
|
||||
}
|
||||
|
||||
// MarkCommissionPaid 发放登记:应付/税务处理中 -> 已付
|
||||
func MarkCommissionPaid(ctx context.Context, in MarkCommissionPaidInput) (*models.PlatformCommissionOrder, error) {
|
||||
row := &models.PlatformCommissionOrder{}
|
||||
if err := models.Orm.QueryTable(new(models.PlatformCommissionOrder)).
|
||||
@@ -262,7 +241,6 @@ func MarkCommissionPaid(ctx context.Context, in MarkCommissionPaidInput) (*model
|
||||
return GetCommissionByID(in.ID)
|
||||
}
|
||||
|
||||
// GetCommissionByID 按 ID 查询佣金单
|
||||
func GetCommissionByID(id uint64) (*models.PlatformCommissionOrder, error) {
|
||||
row := &models.PlatformCommissionOrder{}
|
||||
err := models.Orm.QueryTable(new(models.PlatformCommissionOrder)).
|
||||
|
||||
@@ -13,19 +13,8 @@ import (
|
||||
beego "github.com/beego/beego/v2/server/web"
|
||||
)
|
||||
|
||||
// =============================================================
|
||||
// 渠道敏感参数的对称加密与掩码
|
||||
//
|
||||
// yz_platform_payment_channel.config_json 中的密钥/私钥/Secret 以 AES-256-GCM 加密后存储,
|
||||
// 格式:base64( "YZP1:" + nonce + ciphertext )。
|
||||
// 密钥来源:app.conf 的 payment_secret_key(任意长度字符串,内部做 SHA-256 派生);
|
||||
// 未配置时退回内置兜底密钥(保证开箱可用),上线前务必在 app.conf 配置该值,
|
||||
// 且注意:更换密钥后,历史密文将无法解密,需要重新保存各渠道配置。
|
||||
// =============================================================
|
||||
|
||||
const configCipherPrefix = "YZP1:"
|
||||
|
||||
// fallbackSecretKey 内置兜底密钥,仅用于开发/未配置场景
|
||||
const fallbackSecretKey = "yunzer_payment_default_secret_key_v1"
|
||||
|
||||
func configKey() []byte {
|
||||
@@ -37,7 +26,6 @@ func configKey() []byte {
|
||||
return sum[:]
|
||||
}
|
||||
|
||||
// EncryptConfig 加密渠道参数 JSON
|
||||
func EncryptConfig(plain string) (string, error) {
|
||||
if plain == "" {
|
||||
return "", nil
|
||||
@@ -60,7 +48,6 @@ func EncryptConfig(plain string) (string, error) {
|
||||
return base64.StdEncoding.EncodeToString(buf), nil
|
||||
}
|
||||
|
||||
// DecryptConfig 解密渠道参数 JSON;空串原样返回
|
||||
func DecryptConfig(encoded string) (string, error) {
|
||||
if encoded == "" {
|
||||
return "", nil
|
||||
@@ -89,7 +76,6 @@ func DecryptConfig(encoded string) (string, error) {
|
||||
return string(plain), nil
|
||||
}
|
||||
|
||||
// MaskSecret 生成掩码:保留末 4 位
|
||||
func MaskSecret(v string) string {
|
||||
if v == "" {
|
||||
return ""
|
||||
@@ -100,7 +86,6 @@ func MaskSecret(v string) string {
|
||||
return "******" + v[len(v)-4:]
|
||||
}
|
||||
|
||||
// IsMasked 判断前端回传的值是否仍是掩码(表示「不修改原值」)
|
||||
func IsMasked(v string) bool {
|
||||
return strings.HasPrefix(v, "******")
|
||||
}
|
||||
@@ -10,9 +10,6 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
/* ---------------- 金额工具 ---------------- */
|
||||
|
||||
// FenToYuan 分 -> 元(两位小数字符串),供渠道下单参数使用
|
||||
func FenToYuan(fen int64) string {
|
||||
if fen < 0 {
|
||||
fen = 0
|
||||
@@ -20,7 +17,6 @@ func FenToYuan(fen int64) string {
|
||||
return strconv.FormatInt(fen/100, 10) + "." + fmt.Sprintf("%02d", fen%100)
|
||||
}
|
||||
|
||||
// YuanToFen 元(字符串)-> 分
|
||||
func YuanToFen(yuan string) (int64, error) {
|
||||
yuan = strings.TrimSpace(yuan)
|
||||
if yuan == "" {
|
||||
@@ -36,16 +32,6 @@ func YuanToFen(yuan string) (int64, error) {
|
||||
return int64(f*100 + 0.5), nil
|
||||
}
|
||||
|
||||
/* ---------------- 单号生成 ----------------
|
||||
|
||||
规则:前缀 + yyyyMMddHHmmss + 4 位随机数字(进程内串行生成,避免同秒碰撞;
|
||||
落库仍有唯一键兜底,撞号时由调用方重试一次)。
|
||||
支付单 P202609151024310001
|
||||
退回单 R202609151024310001
|
||||
佣金单 CM202609151024310001
|
||||
对账批次 RC202609151024310001
|
||||
---------------------------------------- */
|
||||
|
||||
var (
|
||||
noMu sync.Mutex
|
||||
lastNoTime int64
|
||||
@@ -68,14 +54,10 @@ func nextSerial(prefix string) string {
|
||||
return fmt.Sprintf("%s%s%04d%04d", prefix, time.Now().Format("20060102150405"), seq, n.Int64())
|
||||
}
|
||||
|
||||
// NextPayNo 生成支付单号
|
||||
func NextPayNo() string { return nextSerial("P") }
|
||||
|
||||
// NextRefundNo 生成退回单号
|
||||
func NextRefundNo() string { return nextSerial("R") }
|
||||
|
||||
// NextCommissionNo 生成佣金单号
|
||||
func NextCommissionNo() string { return nextSerial("CM") }
|
||||
|
||||
// NextBatchNo 生成对账批次号
|
||||
func NextBatchNo() string { return nextSerial("RC") }
|
||||
@@ -13,22 +13,15 @@ import (
|
||||
beelog "github.com/beego/beego/v2/core/logs"
|
||||
)
|
||||
|
||||
/* =============================================================
|
||||
* 日终对账:渠道账单导入 -> 与本地支付流水比对 -> 产出差异 -> 人工标记处理
|
||||
* 差异类型:long 长款(渠道有本地无)/ short 短款(本地有渠道无)/ status_mismatch 状态不一致
|
||||
* ============================================================= */
|
||||
|
||||
// BillRow 渠道账单明细行(导入用)
|
||||
type BillRow struct {
|
||||
ChannelTradeNo string // 渠道流水号
|
||||
OutTradeNo string // 渠道侧商户订单号(下单时传的 pay_no)
|
||||
Amount int64 // 渠道金额(分)
|
||||
Fee int64 // 渠道手续费(分)
|
||||
TradeState string // 渠道侧交易状态
|
||||
TradeTime *time.Time // 渠道交易时间
|
||||
ChannelTradeNo string
|
||||
OutTradeNo string
|
||||
Amount int64
|
||||
Fee int64
|
||||
TradeState string
|
||||
TradeTime *time.Time
|
||||
}
|
||||
|
||||
// ImportChannelBill 导入某渠道某日的账单明细(幂等:按 channel + channel_trade_no 更新或插入)
|
||||
func ImportChannelBill(ctx context.Context, channel, billDate string, rows []BillRow) (int, error) {
|
||||
day, err := time.ParseInLocation("2006-01-02", billDate, time.Local)
|
||||
if err != nil {
|
||||
@@ -72,10 +65,7 @@ func ImportChannelBill(ctx context.Context, channel, billDate string, rows []Bil
|
||||
return imported, nil
|
||||
}
|
||||
|
||||
// ParseChannelBillCSV 解析账单 CSV。
|
||||
// 约定列:channel_trade_no, out_trade_no, amount(元), fee(元), trade_state, trade_time
|
||||
// TODO(渠道): 各渠道账单文件列名/编码不同(微信为制表符分隔、支付宝为 GBK CSV),
|
||||
// 对接时按渠道导出文件写各自的解析器,统一转成 BillRow。
|
||||
func ParseChannelBillCSV(data []byte) ([]BillRow, error) {
|
||||
reader := csv.NewReader(strings.NewReader(string(data)))
|
||||
reader.TrimLeadingSpace = true
|
||||
@@ -121,7 +111,6 @@ func ParseChannelBillCSV(data []byte) ([]BillRow, error) {
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
// ReconcileSummary 一次对账的执行结果
|
||||
type ReconcileSummary struct {
|
||||
BatchNo string `json:"batch_no"`
|
||||
Channel string `json:"channel"`
|
||||
@@ -133,9 +122,6 @@ type ReconcileSummary struct {
|
||||
MismatchCount int `json:"mismatch_count"`
|
||||
}
|
||||
|
||||
// RunReconcile 对某渠道某日的账单与本地支付流水做比对,产出差异(幂等:按唯一键更新已有差异)。
|
||||
// 匹配策略:渠道账单的商户订单号即本地下单时传的 pay_no,优先按 pay_no 匹配,其次按 out_trade_no;
|
||||
// 本地侧只统计支付成功日(paid_at)落在对账日内的支付单。
|
||||
func RunReconcile(ctx context.Context, channel, billDate string) (*ReconcileSummary, error) {
|
||||
day, err := time.ParseInLocation("2006-01-02", billDate, time.Local)
|
||||
if err != nil {
|
||||
@@ -222,7 +208,6 @@ func RunReconcile(ctx context.Context, channel, billDate string) (*ReconcileSumm
|
||||
return summary, nil
|
||||
}
|
||||
|
||||
// upsertDiff 写入/更新差异记录(幂等:唯一键 channel+bill_date+diff_type+channel_trade_no+local_trade_no)
|
||||
func upsertDiff(channel string, day time.Time, batchNo, localTradeNo, channelTradeNo, diffType string, localAmount, channelAmount *int64, remark string) error {
|
||||
exist := &models.PlatformPaymentReconcileDiff{}
|
||||
err := models.Orm.QueryTable(new(models.PlatformPaymentReconcileDiff)).
|
||||
@@ -274,7 +259,6 @@ func upsertDiff(channel string, day time.Time, batchNo, localTradeNo, channelTra
|
||||
return err
|
||||
}
|
||||
|
||||
// ReconcileListInput 差异列表查询条件
|
||||
type ReconcileListInput struct {
|
||||
Channel string
|
||||
BillDate string
|
||||
@@ -284,7 +268,6 @@ type ReconcileListInput struct {
|
||||
PageSize int
|
||||
}
|
||||
|
||||
// ListReconcileDiffs 对账差异分页
|
||||
func ListReconcileDiffs(in ReconcileListInput) ([]models.PlatformPaymentReconcileDiff, int64, error) {
|
||||
qs := models.Orm.QueryTable(new(models.PlatformPaymentReconcileDiff)).Filter("delete_time__isnull", true)
|
||||
if in.Channel != "" {
|
||||
@@ -316,16 +299,14 @@ func ListReconcileDiffs(in ReconcileListInput) ([]models.PlatformPaymentReconcil
|
||||
return rows, total, err
|
||||
}
|
||||
|
||||
// MarkDiffHandledInput 标记差异处理入参
|
||||
type MarkDiffHandledInput struct {
|
||||
ID uint64
|
||||
HandleStatus string // handled / handling / ignored
|
||||
HandleStatus string
|
||||
Remark string
|
||||
OperatorID string
|
||||
OperatorName string
|
||||
}
|
||||
|
||||
// MarkDiffHandled 标记对账差异处理状态
|
||||
func MarkDiffHandled(ctx context.Context, in MarkDiffHandledInput) (*models.PlatformPaymentReconcileDiff, error) {
|
||||
row := &models.PlatformPaymentReconcileDiff{}
|
||||
if err := models.Orm.QueryTable(new(models.PlatformPaymentReconcileDiff)).
|
||||
@@ -356,7 +337,6 @@ func MarkDiffHandled(ctx context.Context, in MarkDiffHandledInput) (*models.Plat
|
||||
return GetReconcileDiffByID(in.ID)
|
||||
}
|
||||
|
||||
// GetReconcileDiffByID 按 ID 查询差异记录
|
||||
func GetReconcileDiffByID(id uint64) (*models.PlatformPaymentReconcileDiff, error) {
|
||||
row := &models.PlatformPaymentReconcileDiff{}
|
||||
err := models.Orm.QueryTable(new(models.PlatformPaymentReconcileDiff)).
|
||||
|
||||
@@ -14,38 +14,21 @@ import (
|
||||
beelog "github.com/beego/beego/v2/core/logs"
|
||||
)
|
||||
|
||||
/* =============================================================
|
||||
* 支付服务核心:创建支付单 / 查询 / 状态机 / 回调幂等 / 兜底退回 / 补偿任务
|
||||
*
|
||||
* 与业务模块的解耦点:
|
||||
* 1. 业务订单的「已支付」同步通过 RegisterOrderSyncHook 注册钩子完成;
|
||||
* 未注册钩子时视为无需同步(order_synced 直接置 1)。
|
||||
* 2. 佣金推广方:下单入参可携带(快照到支付单),未携带时由
|
||||
* RegisterPromoterResolver 注册的钩子推导(如按租户归属的渠道伙伴)。
|
||||
* ============================================================= */
|
||||
|
||||
// OrderSyncFunc 业务订单状态同步钩子
|
||||
type OrderSyncFunc func(ctx context.Context, order *models.PlatformPaymentOrder) error
|
||||
|
||||
// PromoterResolveFunc 推广方解析钩子
|
||||
type PromoterResolveFunc func(ctx context.Context, order *models.PlatformPaymentOrder) (promoterID, promoterName, promoterType string, ok bool)
|
||||
|
||||
var (
|
||||
// 业务订单同步钩子可以有多个(产品订单、附件空间订单等),
|
||||
// 逐个执行;任何一个失败都会保留 order_synced=0 由补偿任务重试。
|
||||
orderSyncHooks []OrderSyncFunc
|
||||
promoterResolve PromoterResolveFunc
|
||||
)
|
||||
|
||||
// RegisterOrderSyncHook 注册业务订单同步钩子(在业务模块 init 时调用)
|
||||
// 支持多个模块分别注册,互不覆盖。
|
||||
func RegisterOrderSyncHook(fn OrderSyncFunc) {
|
||||
if fn != nil {
|
||||
orderSyncHooks = append(orderSyncHooks, fn)
|
||||
}
|
||||
}
|
||||
|
||||
// runOrderSyncHooks 依次执行所有业务同步钩子,返回第一个错误(便于补偿重试)
|
||||
func runOrderSyncHooks(ctx context.Context, order *models.PlatformPaymentOrder) error {
|
||||
var firstErr error
|
||||
for _, fn := range orderSyncHooks {
|
||||
@@ -59,31 +42,28 @@ func runOrderSyncHooks(ctx context.Context, order *models.PlatformPaymentOrder)
|
||||
return firstErr
|
||||
}
|
||||
|
||||
// RegisterPromoterResolver 注册推广方解析钩子
|
||||
func RegisterPromoterResolver(fn PromoterResolveFunc) { promoterResolve = fn }
|
||||
|
||||
// CreateInput 创建支付单入参(租户端下单页 -> POST /backend/payment/create)
|
||||
type CreateInput struct {
|
||||
OutTradeNo string // 业务订单号(必填)
|
||||
OrderType string // platform_usage / module_shop / service_fee
|
||||
OutTradeNo string
|
||||
OrderType string
|
||||
TenantID string
|
||||
TenantName string
|
||||
Amount int64 // 分
|
||||
Channel string // 渠道标识(必填)
|
||||
Amount int64
|
||||
Channel string
|
||||
Subject string
|
||||
ReturnURL string // 支付完成同步跳回地址
|
||||
ReturnURL string
|
||||
ClientIP string
|
||||
PayType string // qr / web / h5 / jsapi;空值由适配器给默认
|
||||
OpenID string // JSAPI 必填
|
||||
PayType string
|
||||
OpenID string
|
||||
PromoterID string
|
||||
PromoterName string
|
||||
PromoterType string
|
||||
ExpireMinutes int // 支付有效期(分钟),默认 30
|
||||
ExpireMinutes int
|
||||
}
|
||||
|
||||
const defaultExpireMinutes = 30
|
||||
|
||||
// GetOrderByPayNo 按支付单号查询
|
||||
func GetOrderByPayNo(payNo string) (*models.PlatformPaymentOrder, error) {
|
||||
row := &models.PlatformPaymentOrder{}
|
||||
err := models.Orm.QueryTable(new(models.PlatformPaymentOrder)).
|
||||
@@ -96,7 +76,6 @@ func GetOrderByPayNo(payNo string) (*models.PlatformPaymentOrder, error) {
|
||||
return row, nil
|
||||
}
|
||||
|
||||
// LogStateChange 记录状态流转流水
|
||||
func LogStateChange(payNo, fromStatus, toStatus, operator, remark string) {
|
||||
row := &models.PlatformPaymentOrderLog{
|
||||
PayNo: payNo,
|
||||
@@ -110,8 +89,6 @@ func LogStateChange(payNo, fromStatus, toStatus, operator, remark string) {
|
||||
}
|
||||
}
|
||||
|
||||
// CreatePayment 创建支付单并调用渠道下单
|
||||
// 幂等:同一 out_trade_no + channel 存在未终态支付单时,直接复用并重新拉起支付参数。
|
||||
func CreatePayment(ctx context.Context, in CreateInput) (*models.PlatformPaymentOrder, *PayParams, error) {
|
||||
if strings.TrimSpace(in.OutTradeNo) == "" {
|
||||
return nil, nil, errors.New("业务订单号不能为空")
|
||||
@@ -128,7 +105,6 @@ func CreatePayment(ctx context.Context, in CreateInput) (*models.PlatformPayment
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
// 幂等:复用未终态支付单
|
||||
var exist models.PlatformPaymentOrder
|
||||
err = models.Orm.QueryTable(new(models.PlatformPaymentOrder)).
|
||||
Filter("out_trade_no", in.OutTradeNo).
|
||||
@@ -175,7 +151,6 @@ func CreatePayment(ctx context.Context, in CreateInput) (*models.PlatformPayment
|
||||
PromoterName: in.PromoterName,
|
||||
PromoterType: in.PromoterType,
|
||||
}
|
||||
// 下单未携带推广方时,交给业务模块推导(如租户的签约渠道伙伴)
|
||||
if order.PromoterID == "" && promoterResolve != nil {
|
||||
if pid, pname, ptype, ok := promoterResolve(ctx, order); ok {
|
||||
order.PromoterID, order.PromoterName, order.PromoterType = pid, pname, ptype
|
||||
@@ -188,7 +163,6 @@ func CreatePayment(ctx context.Context, in CreateInput) (*models.PlatformPayment
|
||||
|
||||
params, err := adapter.Prepay(ctx, order, cfg, PrepayOption{PayType: in.PayType, OpenID: in.OpenID})
|
||||
if err != nil {
|
||||
// 渠道下单失败:保留支付单并置为 failed,便于排查与重下
|
||||
_, _ = models.Orm.QueryTable(new(models.PlatformPaymentOrder)).
|
||||
Filter("id", order.ID).
|
||||
Update(orm.Params{"status": models.PayStatusFailed, "update_time": now})
|
||||
@@ -205,7 +179,6 @@ func CreatePayment(ctx context.Context, in CreateInput) (*models.PlatformPayment
|
||||
return order, params, nil
|
||||
}
|
||||
|
||||
// QueryPayment 查询支付单;syncChannel=true 时主动向渠道查询并同步状态(兜底回调丢失)
|
||||
func QueryPayment(ctx context.Context, payNo string, syncChannel bool) (*models.PlatformPaymentOrder, error) {
|
||||
order, err := GetOrderByPayNo(payNo)
|
||||
if err != nil {
|
||||
@@ -236,13 +209,12 @@ func QueryPayment(ctx context.Context, payNo string, syncChannel bool) (*models.
|
||||
return GetOrderByPayNo(payNo)
|
||||
}
|
||||
|
||||
// HandleNotify 渠道异步通知统一入口:验签 -> 幂等 -> 状态机 -> 佣金,返回需回给渠道的响应体
|
||||
func HandleNotify(ctx context.Context, channel string, r *http.Request, ip string) (string, error) {
|
||||
adapter, err := GetChannelAdapter(channel)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
cfg, err := LoadChannelConfig(channel) // 停用渠道的历史回调仍需处理
|
||||
cfg, err := LoadChannelConfig(channel)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -253,7 +225,6 @@ func HandleNotify(ctx context.Context, channel string, r *http.Request, ip strin
|
||||
return "", err
|
||||
}
|
||||
|
||||
// 幂等:同一事件(channel + event_id)已成功处理过则直接命中
|
||||
duplicate := existsCallbackHandled(channel, result.EventID, result.ChannelTradeNo, result.EventType)
|
||||
insertCallbackLog(channel, result.PayNo, result.OutTradeNo, result.ChannelTradeNo, result.Amount, 1, duplicate, false, "", result.Raw, ip)
|
||||
if duplicate {
|
||||
@@ -262,7 +233,6 @@ func HandleNotify(ctx context.Context, channel string, r *http.Request, ip strin
|
||||
|
||||
order, oerr := GetOrderByPayNo(result.PayNo)
|
||||
if oerr != nil {
|
||||
// 再尝试按业务订单号找最近一笔(回调里可能只回传 out_trade_no)
|
||||
order, oerr = findLatestOrderByOutTradeNo(result.OutTradeNo)
|
||||
}
|
||||
if oerr != nil {
|
||||
@@ -270,7 +240,6 @@ func HandleNotify(ctx context.Context, channel string, r *http.Request, ip strin
|
||||
return "", fmt.Errorf("支付单不存在: %s", result.PayNo)
|
||||
}
|
||||
|
||||
// 非成功/失败/关闭事件只记录日志
|
||||
if result.TradeState != StateSuccess && result.TradeState != StateFailed && result.TradeState != StateClosed {
|
||||
insertCallbackLog(channel, result.PayNo, result.OutTradeNo, result.ChannelTradeNo, result.Amount, 1, false, true, "事件无需变更状态: "+result.EventType, result.Raw, ip)
|
||||
return result.AckBody, nil
|
||||
@@ -293,7 +262,6 @@ func HandleNotify(ctx context.Context, channel string, r *http.Request, ip strin
|
||||
return result.AckBody, nil
|
||||
}
|
||||
|
||||
// existsCallbackHandled 是否已存在处理成功的同事件回调
|
||||
func existsCallbackHandled(channel, eventID, channelTradeNo, eventType string) bool {
|
||||
qs := models.Orm.QueryTable(new(models.PlatformPaymentCallbackLog)).
|
||||
Filter("channel", channel).
|
||||
@@ -344,8 +312,6 @@ func findLatestOrderByOutTradeNo(outTradeNo string) (*models.PlatformPaymentOrde
|
||||
return row, err
|
||||
}
|
||||
|
||||
// applyChannelState 把渠道状态落到本地(回调与主动查询共用),返回是否发生状态变更。
|
||||
// 支付成功采用条件更新(仅 created/pending/paying 可置为 paid)保证并发幂等。
|
||||
func applyChannelState(ctx context.Context, order *models.PlatformPaymentOrder, st *ChannelState, operator, remark string) (bool, error) {
|
||||
if st == nil {
|
||||
return false, nil
|
||||
@@ -385,7 +351,7 @@ func applyChannelState(ctx context.Context, order *models.PlatformPaymentOrder,
|
||||
return false, err
|
||||
}
|
||||
if n == 0 {
|
||||
return false, nil // 并发下已被其他通知处理
|
||||
return false, nil
|
||||
}
|
||||
order.Status = models.PayStatusPaid
|
||||
order.PaidAt = &now
|
||||
@@ -394,7 +360,6 @@ func applyChannelState(ctx context.Context, order *models.PlatformPaymentOrder,
|
||||
}
|
||||
LogStateChange(order.PayNo, models.PayStatusPaying, models.PayStatusPaid, operator, note)
|
||||
|
||||
// 1. 同步业务订单状态(钩子;失败保留 order_synced=0 由补偿任务重试)
|
||||
if len(orderSyncHooks) == 0 {
|
||||
_, _ = models.Orm.QueryTable(new(models.PlatformPaymentOrder)).
|
||||
Filter("id", order.ID).
|
||||
@@ -407,7 +372,6 @@ func applyChannelState(ctx context.Context, order *models.PlatformPaymentOrder,
|
||||
Update(orm.Params{"order_synced": 1, "update_time": time.Now()})
|
||||
}
|
||||
|
||||
// 2. 生成推广佣金(平台自有资金支出,失败不影响收款状态)
|
||||
if _, cerr := OnOrderPaid(ctx, order); cerr != nil {
|
||||
beelog.Warn("支付单 %s 佣金生成失败: %v", order.PayNo, cerr)
|
||||
}
|
||||
@@ -462,16 +426,14 @@ func applyChannelState(ctx context.Context, order *models.PlatformPaymentOrder,
|
||||
}
|
||||
}
|
||||
|
||||
// RefundInput 手动原路退回入参(兜底能力)
|
||||
type RefundInput struct {
|
||||
PayNo string
|
||||
Amount int64 // 分;<=0 表示全额退回
|
||||
Reason string // 必填
|
||||
Amount int64
|
||||
Reason string
|
||||
OperatorID string
|
||||
OperatorName string
|
||||
}
|
||||
|
||||
// ManualRefund 手动原路退回(不做业务层退款流程)
|
||||
func ManualRefund(ctx context.Context, in RefundInput) (*models.PlatformPaymentRefund, error) {
|
||||
if strings.TrimSpace(in.Reason) == "" {
|
||||
return nil, errors.New("退回原因不能为空")
|
||||
@@ -551,7 +513,6 @@ func failRefund(refund *models.PlatformPaymentRefund, msg string) {
|
||||
refund.FailReason = msg
|
||||
}
|
||||
|
||||
// CloseExpiredOrders 关闭超时未支付订单(补偿任务),返回关闭数量
|
||||
func CloseExpiredOrders(ctx context.Context) (int, error) {
|
||||
var orders []models.PlatformPaymentOrder
|
||||
_, err := models.Orm.QueryTable(new(models.PlatformPaymentOrder)).
|
||||
@@ -578,7 +539,6 @@ func CloseExpiredOrders(ctx context.Context) (int, error) {
|
||||
return closed, nil
|
||||
}
|
||||
|
||||
// SyncPendingOrders 重试同步「已支付但业务订单未更新」的支付单(补偿任务),返回处理数量
|
||||
func SyncPendingOrders(ctx context.Context) (int, error) {
|
||||
if len(orderSyncHooks) == 0 {
|
||||
return 0, nil
|
||||
@@ -607,7 +567,6 @@ func SyncPendingOrders(ctx context.Context) (int, error) {
|
||||
return done, nil
|
||||
}
|
||||
|
||||
// StartPaymentScheduler 支付补偿任务:关闭超时订单 + 重试业务订单同步(5 分钟一轮)
|
||||
func StartPaymentScheduler(stop <-chan struct{}) {
|
||||
go func() {
|
||||
ticker := time.NewTicker(5 * time.Minute)
|
||||
|
||||
Reference in new issue
Block a user