Last active
December 3, 2020 03:28
-
-
Save jinuljt/507812b130a139611dde to your computer and use it in GitHub Desktop.
微信退款接口使用商户证书请求golang实现
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
mark