欢迎来到银盒子的世界~
微信的参数,只要xml的,那把json转成xml的过程记录一下
首先安装一个库 xmltodict==0.12.0
pip install xmltidict==0.12.0
然后文件中引入,进行一些参数拼接和转换
import xmltodict
import requests
# 生成订单号
trade_no = str(time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))) + str(time.time()).replace('.', '')[-7:]
# 从a-zA-Z0-9生成指定数量的随机字符:
ran_str = ''.join(random.sample(string.ascii_letters + string.digits, 32))
url = settings.wechat_unifiedorder_url
ip = request.headers.getlist("X-Forwarded-For")[0].rpartition(' ')[-1]
# 鉴权和MD5加密
sign = '&'.join(('app_id=' + settings.wechat_app_id,
'body=MOJIGO-XXX盲盒隐藏款',
'mch_id=' + settings.wechat_mch_id,
'nonce_str=' + ran_str,
'notify_url' + settings.wechat_notify_url,
'out_trade_no=' + trade_no,
'spbill_create_ip=' + ip,
'total_fee=' + money,
'trade_type=APP',
'key=aSvhCoD4FrK2cmdNZLxLggeU7u6YZWmC'))
sign_encode = sign.encode('utf-8')
sign_md5 = hashlib.md5().update(sign_encode).hexdigest()
form = dict(
appid=settings.wechat_app_id,
mch_id=settings.wechat_mch_id,
nonce_str=ran_str,
body=name,
out_trade_no=trade_no,
total_fee=money,
notify_url=settings.wechat_notify_url,
trade_type="APP",
spbill_create_ip=ip,
sign=sign_md5,
)
now_form = {
"xml":form
}
xml_form = xmltodict.unparse(now_form) # 这里就把json转成xml了
"""
注意,这里必须用xml(或其他的,root也行)再把字典包一层,不然就报错 ValueError: Document must have exactly one root.
"""
发送post请求,xml格式的参数
response = requests.post(url, data=xml.encode('utf-8'), headers={'Content-Type': 'text/xml'})
# 拿到结果,并把xml的返回转成json
msg = response.text
xmlmsg = xmltodict.parse(msg)