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.

55 lines
1.7 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package wxpay
import (
"context"
"errors"
"fmt"
"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 Config struct {
MchID string // 商户号
MchAPIv3Key string // 商户APIv3密钥
PrivateKey string // 私钥
PrivateCert string // 私钥证书
}
// InitWxpay @Title 初始化微信支付
func InitWxpay(config Config) 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, fmt.Sprintf("%x", certificate.SerialNumber), 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
}