You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
pay/wxpay.go

50 lines
1.6 KiB

3 years ago
package pay
import (
"base/app/lib/rsa"
"context"
"errors"
"github.com/wechatpay-apiv3/wechatpay-go/core"
"github.com/wechatpay-apiv3/wechatpay-go/core/auth/verifiers"
"github.com/wechatpay-apiv3/wechatpay-go/core/downloader"
"github.com/wechatpay-apiv3/wechatpay-go/core/notify"
"github.com/wechatpay-apiv3/wechatpay-go/core/option"
)
var Wxpay = wxpay{}
type wxpay struct {
Client *core.Client
Handler *notify.Handler
}
type WxpayConfig struct {
MchID string // 商户号
MchCertificateSerialNumber string // 商户证书序列号
MchAPIv3Key string // 商户APIv3密钥
PrivateKey string // 私钥
PrivateCert string // 私钥证书
}
// InitWxpay @Title 初始化微信支付
func InitWxpay(config WxpayConfig) error {
// 加载私钥证书
privateKey, err := rsa.ParsePrivateKey(config.PrivateKey, rsa.PKCS8)
if err != nil {
return errors.New("私钥错误")
}
// 使用商户私钥等初始化 client并使它具有自动定时获取微信支付平台证书的能力
opts := []core.ClientOption{
option.WithWechatPayAutoAuthCipher(config.MchID, config.MchCertificateSerialNumber, privateKey, config.MchAPIv3Key),
}
Wxpay.Client, err = core.NewClient(context.Background(), opts...)
if err != nil {
return errors.New("微信支付错误")
}
// 获取商户号对应的微信支付平台证书访问器
certVisitor := downloader.MgrInstance().GetCertificateVisitor(config.MchID)
// 使用证书访问器初始化 `notify.Handler`
Wxpay.Handler = notify.NewNotifyHandler(config.MchAPIv3Key, verifiers.NewSHA256WithRSAVerifier(certVisitor))
return nil
}