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 替換即可
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章