service/library/payclients/wxpaycli/client.go

82 lines
1.9 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package wxpaycli
import (
"context"
"time"
"github.com/go-pay/gopay"
wxpay "github.com/go-pay/gopay/wechat/v3"
"service/bizcommon/util"
"service/library/configcenter"
"service/library/logger"
)
const (
DefaultOrderTimeoutSeconds = 900 // 默认订单超时时间,单位: s
)
var defaultWxpayClient *WxpayClient
type WxpayClient struct {
*wxpay.ClientV3
AppId string `json:"app_id"`
NotifyUrl string `json:"notify_url"`
}
func GetDefaultWxpayClient() *WxpayClient {
return defaultWxpayClient
}
func Init(cfg *configcenter.WxpayClientConfig) (err error) {
wxpayCli, err := wxpay.NewClientV3(cfg.MchId, cfg.SerialNo, cfg.ApiV3Key, cfg.PrivateKey)
if err != nil {
logger.Error("NewClientV3 fail, cfg: %v, err: %v", util.ToJson(cfg), err)
return
}
defaultWxpayClient = &WxpayClient{
ClientV3: wxpayCli,
AppId: cfg.AppId,
NotifyUrl: cfg.NotifyUrl,
}
return
}
// 验签
// 微信支付 native支付
type NativePayParam struct {
Description string
OutTradeNo string // 商家订单id我们自己的订单id
TotalAmount int64 // 金额,单位:分
TimeOutSeconds int // 订单有效时间,单位:秒
}
func (c *WxpayClient) NativePay(ctx context.Context, param *NativePayParam) (resp *wxpay.NativeRsp, err error) {
if param.TimeOutSeconds <= 0 {
param.TimeOutSeconds = DefaultOrderTimeoutSeconds
}
bm := gopay.BodyMap{
"appid": c.AppId,
"description": param.Description,
"out_trade_no": param.OutTradeNo,
"time_expire": time.Now().Add(time.Second * time.Duration(param.TimeOutSeconds)).Format(time.RFC3339),
"notify_url": c.NotifyUrl,
"amount": gopay.BodyMap{
"total": param.TotalAmount,
"currency": "CNY",
},
}
resp, err = c.V3TransactionNative(ctx, bm)
if err != nil {
return
}
if resp.Code != wxpay.Success {
logger.Info("wxpay NativePay resp, fail: %v", util.ToJson(resp))
return
}
logger.Info("wxpay NativePay resp, success: %v", util.ToJson(resp))
return
}