wechatpay-apiv3 / wechatpay-go

微信支付 APIv3 的官方 Go Library
https://pay.weixin.qq.com/wiki/doc/apiv3/wxpay/pages/index.shtml
Apache License 2.0
1.05k stars 142 forks source link

使用示例的demo无法初始化client #68

Closed colemanpeng closed 3 years ago

colemanpeng commented 3 years ago

使用例子中的代码无法初始化client {"file":"/Users/apple/business/kuzi-app/common/weixinPay/weixin_pay_client.go:64","func":"kuzi/app/common/weixinPay.NewWeixinPayClient","level":"error","msg":"new wechat pay client err:init client setting err:generate authorization err:you must set privatekey to use SHA256WithRSASigner","time":"2021-09-02T09:09:29+08:00"}

`import ( "context" "crypto/rsa" "net/http"

//"kuzi/app/app/common"
"kuzi/app/configs"

"github.com/sirupsen/logrus"
"github.com/wechatpay-apiv3/wechatpay-go/core"
"github.com/wechatpay-apiv3/wechatpay-go/core/option"
"github.com/wechatpay-apiv3/wechatpay-go/utils"

)

var weixinPayClient *core.Client

// 示例参数,实际使用时请自行初始化 var ( mchID string // 商户号 mchCertificateSerialNumber string // 商户证书序列号 mchPrivateKey rsa.PrivateKey // 商户私钥 mchAPIv3Key string // 商户APIv3密钥 customHTTPClient http.Client // 可选,自定义客户端实例 )

func InitWeixinPayClient() { mchID = configs.AppConfig.Weixin.MchId mchCertificateSerialNumber = configs.AppConfig.Weixin.MchCertificateSerialNumber mchPrivateKey = GetPrivateKey() mchAPIv3Key = configs.AppConfig.Weixin.MchAPIv3Key weixinPayClient = NewWeixinPayClient()

}

//获取商户私钥 func GetPrivateKey() *rsa.PrivateKey { // 加载商户私钥 privateKeyPath := configs.AppConfig.Weixin.MchPrivateKeyPath privateKey, err := utils.LoadPrivateKeyWithPath(privateKeyPath)

if err != nil {
    logrus.Errorf("load private err:%s", err.Error())
    return nil
}

return privateKey

}

func NewWeixinPayClient() *core.Client { ctx := context.Background() opts := []core.ClientOption{ // 一次性设置 签名/验签/敏感字段加解密,并注册 平台证书下载器,自动定时获取最新的平台证书 option.WithWechatPayAutoAuthCipher(mchID, mchCertificateSerialNumber, mchPrivateKey, mchAPIv3Key), // 设置自定义 HTTPClient 实例,不设置时默认使用 http.Client{},并设置超时时间为 30s //option.WithHTTPClient(customHTTPClient), } client, err := core.NewClient(ctx, opts...) if err != nil { logrus.Errorf("new wechat pay client err:%s", err.Error()) return nil } return client }`

EmmetZC commented 3 years ago

请确认下是不是 GetPrivateKey 失败了?

colemanpeng commented 3 years ago

确实是这个问题,多谢