Skip to content

Instantly share code, notes, and snippets.

@jinuljt
Last active December 3, 2020 03:28
Show Gist options
  • Save jinuljt/507812b130a139611dde to your computer and use it in GitHub Desktop.
Save jinuljt/507812b130a139611dde to your computer and use it in GitHub Desktop.
微信退款接口使用商户证书请求golang实现
import (
"bytes"
"crypto/tls"
"crypto/x509"
"io/ioutil"
"net/http"
)
wechatCertPath = "/path/to/wechat/cert.pem"
wechatKeyPath = "/path/to/wechat/key.pem"
wechatCAPath = "/path/to/wechat/ca.pem"
wechatRefundURL = "https://wechat/refund/url"
var _tlsConfig *tls.Config
func getTLSConfig() (*tls.Config, error) {
if _tlsConfig != nil {
return _tlsConfig, nil
}
// load cert
cert, err := tls.LoadX509KeyPair(wechatCertPath, wechatKeyPath)
if err != nil {
glog.Errorln("load wechat keys fail", err)
return nil, err
}
// load root ca
caData, err := ioutil.ReadFile(wechatCAPath)
if err != nil {
glog.Errorln("read wechat ca fail", err)
return nil, err
}
pool := x509.NewCertPool()
pool.AppendCertsFromPEM(caData)
_tlsConfig = &tls.Config{
Certificates: []tls.Certificate{cert},
RootCAs: pool,
}
return _tlsConfig, nil
}
func SecurePost(url string, xmlContent []byte) (*http.Response, error) {
tlsConfig, err := getTLSConfig()
if err != nil {
return nil, err
}
tr := &http.Transport{TLSClientConfig: tlsConfig}
client := &http.Client{Transport: tr}
return client.Post(
wechatRefundURL,
"text/xml",
bytes.NewBuffer(xmlContent))
}
@xinst
Copy link

xinst commented Sep 30, 2017

mark

@rxda
Copy link

rxda commented Aug 29, 2019

很有用,谢谢~,自签的ca就是把公私钥放在一个pem里

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment