class Payment(View):
"""微信支付"""
@staticmethod
def get_nonce_str():
"""生成随机字符串"""
return str(uuid.uuid4()).replace('-', '')
@staticmethod
def getsing(o_dict):
"""生成签名"""
keys, paras = sorted(o_dict), []
paras = ['{}={}'.format(key, o_dict[key]) for key in keys] # and kwargs[key] != '']
stringA = '&'.join(paras)
stringSignTemp = stringA + '&key=' + mch_key
print(stringSignTemp)
md5 = hashlib.md5()
md5.update(stringSignTemp.encode('utf-8'))
return md5.hexdigest().upper()
@staticmethod
def trans_dict_to_xml(data_dict):
data_xml = []
for k in data_dict.keys(): # 遍历字典排序后的key
v = data_dict.get(k) # 取出字典中key对应的value
data_xml.append('<{key}>{value}</{key}>'.format(key=k, value=v))
print('<xml>{}</xml>'.format(''.join(data_xml)))
return '<xml>{}</xml>'.format(''.join(data_xml)).encode('utf-8') # 返回XML,并转成u
@staticmethod
def getxml(kwargs):
# 生成xml
xml = ''
for key, value in kwargs.items():
xml += '<{0}>{1}</{0}>'.format(key, value)
xml = '<xml>{0}</xml>'.format(xml)
return xml
def post(self, request):
url = "https://api.mch.weixin.qq.com/pay/unifiedorder"
body = "test"
trade_type = "JSAPI" # 交易类型
data = json.loads(request.body.decode())
nonce_str = self.get_nonce_str() # 随机字符串
out_trade_no = data.get("out_trade_no") # 商户订单号
total_fee = data.get("total_fee") # 订单总金额 单位为分
openid = data.get("openid")
notify_url = "http://hbaod.sjphyhg.com/notify" # 通知地址
if request.META.get('HTTP_X_FORWARDED_FOR'):
# 终端ip
spbill_create_ip = request.META.get("HTTP_X_FORWARDED_FOR")
else:
spbill_create_ip = request.META.get("REMOTE_ADDR")
data_dict = {
"appid": AppID,
"mch_id": mch_id,
"nonce_str": nonce_str,
"body": body,
"out_trade_no": out_trade_no,
"total_fee": int(total_fee),
"spbill_create_ip": spbill_create_ip,
"notify_url": notify_url,
"trade_type": trade_type,
"openid": openid,
"sign_type": 'MD5'
}
sing = self.getsing(data_dict) # 签名
data_dict['sign'] = sing
xml = self.getxml(data_dict)
print(xml)
headers = {'Content-Type': 'text/xml;charset=utf-8'}
request_data = requests.post(url, data=xml.encode("utf-8"), headers=headers)
content = request_data.content.decode()
print(content)
# xml 转换字典
x = XML2Dict()
xml_dict = x.parse(content)
return_data = xml_dict.get("xml")
print(return_data)
if return_data.get("return_code").decode() == "SUCCESS" and return_data.get("result_code").decode() == "SUCCESS":
prepay_id = return_data.get("prepay_id").decode()
nonce_str = return_data.get("nonce_str").decode()
package = "prepay_id=%s" % prepay_id
signType = "MD5"
timeStamp = str(int(time.time()))
getPaysign_dict = {
"appId": AppID,
"nonceStr": nonce_str,
"package": package,
"signType": signType,
"timeStamp": timeStamp,
}
paySign = self.getsing(getPaysign_dict)
requestPayment = {
"timeStamp": timeStamp,
"nonceStr": nonce_str,
"package": package,
"signType": signType,
"paySign": paySign
}
return http.JsonResponse({"code": 0, "data": requestPayment})
else:
return_msg = return_data.get("return_msg").decode()
err_code = return_data.get("return_code").decode()
if err_code:
return http.JsonResponse({"code": 100, "return_msg": return_msg, "err_code": err_code})
return http.JsonResponse({"code": 107, "msg": "失败"})
微信小程序支付接口 Python版
猜你喜欢
转载自blog.csdn.net/weixin_43762794/article/details/104864373
今日推荐
周排行