前言

对接微信零钱支付时,需要带上api证书。在已经下载了证书后,具备下述文件:

  • apiclient_cert.p12
  • apiclient_cert.pem
  • apiclient_key.pem

因为go目前不支持解析p12(博主没找到示例代码), 所以只能使用下面两个。

getClient := func() *http.Client {
var wechatPayCert = "C:\\Users\\DELL\\Desktop\\LINUX-CERT\\apiclient_cert.pem"
var wechatPayKey = "C:\\Users\\DELL\\Desktop\\LINUX-CERT\\apiclient_key.pem"
var rootC = "C:\\Users\\DELL\\Desktop\\LINUX-CERT\\cacert.pem"

certs, e := tls.LoadX509KeyPair(wechatPayCert, wechatPayKey)
if e != nil {
fmt.Println(errorx.Wrap(e).Error())
return nil
}

rootCa, e := ioutil.ReadFile(rootC)
if e != nil {
fmt.Println(errorx.Wrap(e))
return nil
}
pool := x509.NewCertPool()
fmt.Println(pool.AppendCertsFromPEM(rootCa))

c := &http.Client{
Timeout: 30 * time.Second,
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
RootCAs: pool,
Certificates: []tls.Certificate{certs},
},
},
}
return c
}

使用时

req:= http.NewRequest(method, url, bytesReader)
c:= getClient()
c.Do(req)

值得一提的是,官方打包的证书文件夹里,不再提供rootca.pem, 去网上随便找了一个rootca.pem,竟然报了证书权限错误。

最后在官方文档中找到解决方案,需要更新rootca.pem

  • 更新rootca.pem。用libcurl官网最新的https://curl.haxx.se/ca/cacert.pem 替换即可