运行环境
操作系统:win平台
Python版本:3.9.6
请求示例
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA256
import base64
import http.client
import time
def RSA_sign(data):
privateKey = open("私钥文件地址").read()
priKey = RSA.importKey(privateKey)
signer = PKCS1_v1_5.new(priKey)
hash_obj = SHA256.new(data.encode('utf-8'))
signature = base64.b64encode(signer.sign(hash_obj)).decode('utf8')
return signature
if __name__ == '__main__':
method = "请求方法,例如GET、POST"
url = "请求接口地址,例如/v3/certificates"
non_str = "随机字符串"
t = str(int(time.time()))
body = "请求body内容,取决业务接口是否需要传入,不需要的情况下,使用空字符"
data = method+"\n"+url+"\n"+t+"\n"+non_str+"\n"+body+"\n"
signature = RSA_sign(data)
serial_no = "证书序列号,可以登录商户平台自行查看"
mch_id = "商户号"
Authorization = 'WECHATPAY2-SHA256-RSA2048 mchid="'+mch_id+'",nonce_str="'+non_str+'",signature="'+signature+'",timestamp="'+t+'",serial_no="'+serial_no+'"'
conn = http.client.HTTPSConnection("api.mch.weixin.qq.com")
headers = {
'Authorization': Authorization,
'Accept': 'application/json',
'User-Agent': '请求UA',
'Content-Type': 'application/json'
}
conn.request(method, url, body, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
基于http.client请求图片上传示例
def upload():
method = "POST"
url = "/v3/merchant/media/upload"
filePath = '文件地址'
file = open(filePath, 'rb').read()
fileName = os.path.basename(filePath)
fileType = mimetypes.guess_type(filePath)[0] or 'application/octet-stream'
fileSha256 = hashlib.sha256()
fileSha256.update(file)
metaRaw = {
'filename': fileName,
'sha256': fileSha256.hexdigest()
}
info = json.dumps(metaRaw)
dataList = []
boundary = '自定义边界信息'
dataList.append(encode('--' + boundary))
dataList.append(encode('Content-Disposition: form-data; name="meta";'))
dataList.append(encode('Content-Type: application/json;'))
dataList.append(encode(''))
dataList.append(encode(info))
dataList.append(encode('--' + boundary))
dataList.append(encode('Content-Disposition: form-data; name="file"; filename="' + fileName + '"'))
dataList.append(encode('Content-Type: ' + fileType))
dataList.append(encode(''))
dataList.append(file)
dataList.append(encode('--' + boundary + '--'))
dataList.append(encode(''))
body = b'\r\n'.join(dataList)
#后面的就不写了,注意的点就是header头里面'Content-Type': 'application/json'改成'Content-type': 'multipart/form-data; boundary=' + boundary
其他事项
1、图片上传也可以使用request库来实现,而且更加的方便、简洁,只需要注意'Content-Type': 'application/json'修改成'Content-Type': 'multipart/form-data'
2、如果出现请求图片提示"输入源“/body/file”映射到字段“图片文件”必填性规则校验失败,此字段为必填项"这样的信息,建议看下边界设置是否有问题,顺带记得看下file、filename是否有加双引号
3、签名失败的,通常是边界设置问题,或者就是请求头中的content-type设置成错误的格式
python开发者可以使用已经封装好的“微信支付 V3 API Python SDK”
https://github.com/minibear2021/wechatpayv3