golang 微信支付如何在http request中带上cert.pem和key.pem

前言

对接微信零钱支付时,需要带上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 替换即可
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值