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

55 lines
1.7 KiB

3 years ago
package pay
import (
"context"
"errors"
3 years ago
"fmt"
3 years ago
"git.oa00.com/go/rsa"
3 years ago
"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 // 商户号
MchAPIv3Key string // 商户APIv3密钥
PrivateKey string // 私钥
PrivateCert string // 私钥证书
3 years ago
}
// InitWxpay @Title 初始化微信支付
func InitWxpay(config WxpayConfig) error {
// 加载私钥
3 years ago
privateKey, err := rsa.ParsePrivateKey(config.PrivateKey, rsa.PKCS8)
if err != nil {
return errors.New("私钥错误")
}
// 加载私钥证书
certificate, err := rsa.ParseCertificate(config.PrivateCert)
if err != nil {
return errors.New("证书错误")
}
3 years ago
// 使用商户私钥等初始化 client并使它具有自动定时获取微信支付平台证书的能力
opts := []core.ClientOption{
3 years ago
option.WithWechatPayAutoAuthCipher(config.MchID, fmt.Sprintf("%x", certificate.SerialNumber), privateKey, config.MchAPIv3Key),
3 years ago
}
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
}