使用tornado的httpclient做微信支付开发时,如果需要调用退款等需要证书验证的api时,可以使用下面的函数做证书验证:
(微信提供下载的证书文件有: apiclient_cert.p12, apiclient_cert.pem,apiclient_key.pem,rootca.pem)
from tornado import httpclient
def get_response_httpclient_withcert(url,body,method, header = None, client_key=None, client_cert=None, ca_certs=None):
http_client = httpclient.HTTPClient()
request = httpclient.HTTPRequest(url, headers = header, body=body, method=method, client_key=client_key, client_cert=client_cert, connect_timeout=20.0, request_timeout=20.0)
#如果出现类似“xxxxxx/tornado/iostream.py[line:1276] WARNING :SSL Error on 14 (‘x.x.x.x.’, 443): [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:590)”这样的错误,可以将ca_certs的参数也带上(即带上rootca.pem),使用下面的语句:
#request = httpclient.HTTPRequest(url, headers = header, body=body, method=method, client_key=client_key, client_cert=client_cert, ca_certs=ca_certs, connect_timeout=20.0, request_timeout=20.0)
response = http_client.fetch(request)
return response.body
调用举例:
module_path = os.path.dirname(__file__)
client_cert_path = os.path.abspath(os.path.join(module_path, “../keys/apiclient_cert.pem”))
client_key_path = os.path.abspath(os.path.join(module_path, “../keys/apiclient_key.pem”))
ca_certs_path = os.path.abspath(os.path.join(module_path, “../keys/rootca_wx.pem”))
resp = webRequrestUtil.get_response_httpclient_withcert(‘https://api.mch.weixin.qq.com/secapi/pay/refund’, “<xml> xxxxxxxxx</xml>”, “POST”, client_key=client_key_path, client_cert=client_cert_path, ca_certs=ca_certs_path)