|
|
|
|
package pay
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
|
|
|
|
"errors"
|
|
|
|
|
"git.oa00.com/go/rsa"
|
|
|
|
|
"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 // 私钥证书
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// InitWxpay @Title 初始化微信支付
|
|
|
|
|
func InitWxpay(config WxpayConfig) error {
|
|
|
|
|
// 加载私钥
|
|
|
|
|
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("证书错误")
|
|
|
|
|
}
|
|
|
|
|
// 使用商户私钥等初始化 client,并使它具有自动定时获取微信支付平台证书的能力
|
|
|
|
|
opts := []core.ClientOption{
|
|
|
|
|
option.WithWechatPayAutoAuthCipher(config.MchID, certificate.SerialNumber.String(), 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
|
|
|
|
|
}
|