diff --git a/wechat/v3/cert.go b/wechat/v3/cert.go index 1cd4d68e..2e319dcf 100644 --- a/wechat/v3/cert.go +++ b/wechat/v3/cert.go @@ -8,6 +8,7 @@ import ( "crypto/sha256" "encoding/base64" "encoding/json" + "errors" "fmt" "net/http" "runtime" @@ -131,16 +132,17 @@ func GetPlatformSM2Certs(ctx context.Context, mchid, apiV3Key, serialNo, private // 注意1:如已开启自动验签功能 client.AutoVerifySign(),无需再调用此方法设置 // 注意2:请预先通过 wechat.GetPlatformCerts() 获取 微信平台公钥证书 和 证书序列号 // 部分接口请求参数中敏感信息加密,使用此 微信支付平台公钥 和 证书序列号 -func (c *ClientV3) SetPlatformCert(wxPublicKeyContent []byte, wxSerialNo string) (client *ClientV3) { +func (c *ClientV3) SetPlatformCert(wxPublicKeyContent []byte, wxSerialNo string) (err error) { pubKey, err := xpem.DecodePublicKey(wxPublicKeyContent) if err != nil { - c.logger.Errorf("SetPlatformCert(%s),err:%+v", wxPublicKeyContent, err) + return err } - if pubKey != nil { - c.wxPublicKey = pubKey + if pubKey == nil { + return errors.New("xpem.DecodePublicKey() failed, pubKey is nil") } + c.wxPublicKey = pubKey c.WxSerialNo = wxSerialNo - return c + return nil } // 获取最新的 微信平台证书 diff --git a/wechat/v3/client.go b/wechat/v3/client.go index 6f417b0c..93908d62 100644 --- a/wechat/v3/client.go +++ b/wechat/v3/client.go @@ -3,6 +3,7 @@ package wechat import ( "context" "crypto/rsa" + "errors" "sync" "github.com/go-pay/crypto/xpem" @@ -85,11 +86,31 @@ func (c *ClientV3) AutoVerifySign(autoRefresh ...bool) (err error) { c.WxSerialNo = wxSerialNo c.wxPublicKey = c.SnCertMap[wxSerialNo] if len(autoRefresh) == 1 && !autoRefresh[0] { - return + return nil } c.autoSign = true go c.autoCheckCertProc() - return + return nil +} + +// wxPublicKeyContent:微信公钥证书文件内容[]byte +// wxPublicKeyID:微信公钥证书ID +func (c *ClientV3) AutoVerifySignByCert(wxPublicKeyContent []byte, wxPublicKeyID string) (err error) { + pubKey, err := xpem.DecodePublicKey(wxPublicKeyContent) + if err != nil { + return err + } + if pubKey == nil { + return errors.New("xpem.DecodePublicKey() failed, pubKey is nil") + } + if len(c.SnCertMap) <= 0 { + c.SnCertMap = make(map[string]*rsa.PublicKey) + } + c.SnCertMap[wxPublicKeyID] = pubKey + c.wxPublicKey = pubKey + c.WxSerialNo = wxPublicKeyID + c.autoSign = true + return nil } // SetBodySize 设置http response body size(MB)