hotime/dri/wechat/pay.go

95 lines
2.6 KiB
Go
Raw Normal View History

2022-05-03 14:40:02 +00:00
package wechat
import (
"context"
"github.com/go-pay/gopay"
"github.com/go-pay/gopay/pkg/xlog"
"github.com/go-pay/gopay/wechat/v3"
"time"
)
//基于此文档开发
//https://github.com/silenceper/wechat/blob/v2/doc/api/officialaccount.md
type wxpay struct {
client *wechat.ClientV3
ctx context.Context
}
var WxPay = wxpay{}
// Init 初始化
func (that *wxpay) Init(MchId, SerialNo, APIv3Key, PrivateKey string) {
client, err := wechat.NewClientV3(MchId, SerialNo, APIv3Key, PrivateKey)
if err != nil {
xlog.Error(err)
return
}
that.client = client
// 设置微信平台API证书和序列号如开启自动验签请忽略此步骤
//client.SetPlatformCert([]byte(""), "")
that.ctx = context.Background()
// 启用自动同步返回验签并定时更新微信平台API证书开启自动验签时无需单独设置微信平台API证书和序列号
err = client.AutoVerifySign()
if err != nil {
xlog.Error(err)
return
}
// 打开Debug开关输出日志默认是关闭的
client.DebugSwitch = gopay.DebugOn
}
// GetUserInfo 获取用户信息
func (that *wxpay) GetJsOrder(money int64, appid, name, tradeNo, notifyUrl string) (jsApiParams *wechat.JSAPIPayParams, err error) {
PrepayId, err := that.getPrepayId(money, name, tradeNo, notifyUrl)
if err != nil {
return nil, err
}
//小程序
jsapi, err := that.client.PaySignOfJSAPI(appid, PrepayId)
return jsapi, err
}
// GetUserInfo 获取用户信息
func (that *wxpay) GetMiniOrder(money int64, appid, name, tradeNo, notifyUrl string) (jsApiParams *wechat.AppletParams, err error) {
PrepayId, err := that.getPrepayId(money, name, tradeNo, notifyUrl)
if err != nil {
return nil, err
}
//小程序
applet, err := that.client.PaySignOfApplet(appid, PrepayId)
return applet, err
}
func (that *wxpay) getPrepayId(money int64, name, tradeNo, notifyUrl string) (prepayid string, err error) {
expire := time.Now().Add(10 * time.Minute).Format(time.RFC3339)
// 初始化 BodyMap
bm := make(gopay.BodyMap)
bm.Set("sp_appid", "sp_appid").
Set("sp_mchid", "sp_mchid").
Set("sub_mchid", "sub_mchid").
Set("description", name).
Set("out_trade_no", tradeNo).
Set("time_expire", expire).
Set("notify_url", notifyUrl).
SetBodyMap("amount", func(bm gopay.BodyMap) {
bm.Set("total", money).
Set("currency", "CNY")
}).
SetBodyMap("payer", func(bm gopay.BodyMap) {
bm.Set("sp_openid", "asdas")
})
//ctx:=context.Context()
wxRsp, err := that.client.V3TransactionJsapi(that.ctx, bm)
if err != nil {
xlog.Error(err)
return "", err
}
return wxRsp.Response.PrepayId, nil
}