APP支付:
微信统一下单接口参数及流程详见官方文档:https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_1
1. 商户系统先调用该接口在微信支付服务后台生成预支付交易单,返回正确的预支付交易会话标识后再在APP里面调起支付
import hashlib
import json
import optparse
import time
from urllib.parse import quote
from xml.etree import ElementTree
import xml.etree.ElementTree as ET
import requests
# from xml2json.xml2json import xml2json
import xmltodict
class WeiXinPay(object):
"""配置账号信息"""
# =======【基本信息设置】=====================================
# 微信公众号身份的唯一标识。审核通过后,在微信发送的邮件中查看
APPID = ""
# JSAPI接口中获取openid,审核后在公众平台开启开发模式后可查看
APPSECRET = ""
# 受理商ID,身份标识
MCHID = ""
# 异步通知url,商户根据实际开发过程设定
NOTIFY_URL = "http://~/v1.0.1/order/payment"
# trade_type为JSAPI时,openid为必填参数!此参数为微信用户在商户对应appid下的唯一标识, 统一支付接口中,缺少必填参数openid!
TRADE_TYPE = 'APP'
APIKEY = ""
def __init__(self, order_id, body, total_fee, spbill_create_ip):
self.params = {
'appid': self.APPID, # appid
'mch_id': self.MCHID, # 商户号
'nonce_str': self.getNonceStr(),
'body': body, # 商品描述
'out_trade_no': str(order_id), # 商户订单号
'total_fee': str(int(total_fee)),
'spbill_create_ip': spbill_create_ip, # 127.0.0.1
'trade_type': self.TRADE_TYPE, # 交易类型
# 'openid': openid, # trade_type为JSAPI时,openid为必填参数!此参数为微信用户在商户对应appid下的唯一标识, 统一支付接口中,缺少必填参数openid!
'notify_url': self.NOTIFY_URL # 微信支付结果异步通知地址
}
# 开发者调用支付统一下单API生成预交易单
self.url = 'https://api.mch.weixin.qq.com/pay/unifiedorder' # 微信请求url
self.error = None
def getNonceStr(self, length=32):
"""生成随机字符串"""
import random
chars = "abcdefghijklmnopqrstuvwxyz0123456789"
strs = []
for x in range(length):
strs.append(chars[random.randrange(0, len(chars))])
return "".join(strs)
def getOpenID(self, code):
'''获取 openid'''
param = {
'code': code, # 用户点击按钮跳转到微信授权页, 微信处理完后重定向到redirect_uri, 并给我们加上code=xxx的参数, 这个code就是我们需要的
'appid': self.params['appid'],
'secret': self.params['APPSECRET'],
'grant_type': self.params['JSAPI'],
}
# 通过code获取access_token
openIdUrl = 'https://api.weixin.qq.com/sns/oauth2/access_token'
resp = requests.get(openIdUrl, params=param)
# {openid, accss_token, refresh_token, openid, scope, expires_in}
openId = json.loads(resp.text)['openid']
# return resp.text
return openId
def key_value_url(self, value, urlencode):
"""
将键值对转为 key1=value1&key2=value2
对参数按照key=value的格式,并按照参数名ASCII字典序排序
"""
slist = sorted(value)
buff = []
for k in slist:
v = quote(value[k]) if urlencode else value[k]
buff.append("{0}={1}".format(k, v))
return "&".join(buff)
def get_sign(self, params):
"""
生成sign
拼接API密钥
"""
stringA = self.key_value_url(params, False)
stringSignTemp = stringA + '&key=' + self.APIKEY # APIKEY, API密钥,需要在商户后台设置
sign = (hashlib.md5(stringSignTemp.encode("utf-8")).hexdigest()).upper()
params['sign'] = sign
return self.params
def get_req_xml(self):
"""
拼接XML
"""
self.get_sign(self.params)
xml = ""
for k, v in self.params.items():
# v = v.encode('utf8')
# k = k.encode('utf8')
xml += '<' + k + '>' + v + '' + k + '>'
xml += " "
return xml.encode("utf-8")
def get_prepay_id(self):
"""
请求获取prepay_id
"""
xml = self.get_req_xml()
# headers = {'Content-Type': 'application/xml'}
# r = requests.post(self.url, data=xml, headers=headers)
# re_xml = ElementTree.fromstring(r.text.encode('utf8'))
# xml_status = re_xml.getiterator('result_code')[0].text
# if xml_status != 'SUCCESS':
# self.error = u"连接微信出错啦!"
# TODO:修改
respone = requests.post(self.url, xml, headers={'Content-Type': 'application/xml'})
msg = respone.text.encode('ISO-8859-1').decode('utf-8')
xmlresp = xmltodict.parse(msg)
if xmlresp['xml']['return_code'] == 'SUCCESS':
if xmlresp['xml']['result_code'] == 'SUCCESS':
prepay_id = xmlresp['xml']['prepay_id']
# ----------
# headers = {'Content-Type': 'application/xml'}
# r = requests.post(self.url, data=xml, headers=headers)
# print(r, "r")
# re_xml = ElementTree.fromstring(r.text.encode('utf8'))
# print(re_xml, "re_xml")
# print(re_xml.getiterator('result_code')[0])
# xml_status = re_xml.getiterator('result_code')[0].text
# print(xml_status, "xml_status")
# if xml_status != 'SUCCESS':
# self.error = u"连接微信出错啦!"
# return
# prepay_id = re_xml.getiterator('prepay_id')[0].text
self.params['prepay_id'] = prepay_id
self.params['package'] = "prepay_id={}".format(prepay_id)
self.params['timestamp'] = str(int(time.time()))
else:
return
else:
return
def re_finall(self):
"""得到prepay_id后再次签名,返回给终端参数
"""
self.get_prepay_id()
if self.error:
return
sign_again_params = {
'appid': self.params['appid'],
'noncestr': self.params['nonce_str'],
'package': self.params['package'],
'partnerid': self.params['mch_id'],
'timestamp': self.params['timestamp'],
'prepayid': self.params['prepay_id']
}
self.get_sign(sign_again_params)
self.params['sign'] = sign_again_params['sign']
# # 移除其他不需要返回参数
# for i in self.params.keys():
# print(i)
# if i not in ['appid', 'mch_id', 'nonce_str', 'timestamp', 'sign', 'package', 'prepay_id']:
# self.params.pop(i)
return self.params # 返回给app
views中将参数返回给前端:
from wechatpay import WeiXinPay
# 获取前端请求参数
def request_data(request, arg):
data = json.loads(request.body.decode("utf-8", "ignore")).get(arg)
return data
order_no = request_data(request, 'order_no') # 订单号
channel = request_data(request, 'channel') # 支付渠道
client_ip = request_data(request, 'client_ip') # 终端IP
body = request_data(request, 'body') # 商品描述信息
'''
'''
'''
try:
params = WeiXinPay(
order_id=batch_no + order_no,
body=body,
total_fee=amount,
spbill_create_ip=client_ip
).re_finall()
return JsonResponse({
"status": "success",
"code": 200,
"order_string": params
})
except Exception as e:
logger.error(e)
return JsonResponse({
"status": "failed",
"code": 400,
"msg": str(e)
})
# 支付成功后异步回调: https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_7&index=3
class Wxpay_server_pub(WeiXinPay):
SUCCESS, FAIL = "SUCCESS", "FAIL"
def __init__(self, xml):
self.xml = xml
self.data = {} # 接收到的数据,类型为关联数组
self.returnParameters = {} # 返回参数,类型为关联数组
self.APIKEY = self.APIKEY
# super(Wxpay_server_pub, self).__init__() # super(子类名, 子类对象).父类方法(参数1,参数2.。。)
def formatBizQueryParaMap(self, paraMap, urlencode):
"""格式化参数,签名过程需要使用"""
slist = sorted(paraMap)
buff = []
for k in slist:
v = quote(paraMap[k]) if urlencode else paraMap[k]
buff.append("{0}={1}".format(k, v))
return "&".join(buff)
def getSign(self, obj):
"""生成签名"""
# 签名步骤一:按字典序排序参数,formatBizQueryParaMap已做
String = self.formatBizQueryParaMap(obj, False)
# 签名步骤二:在string后加入KEY
String = "{0}&key={1}".format(String, self.APIKEY)
# 签名步骤三:MD5加密
# String = hashlib.md5(String).hexdigest()
String = hashlib.md5(String.encode("utf-8")).hexdigest()
# 签名步骤四:所有字符转为大写
result_ = String.upper()
return result_
def xmlToArray(self):
"""将xml转为array"""
array_data = {}
# root = ET.fromstring(self.xml)
root = ElementTree.fromstring(self.xml)
for child in root:
value = child.text
array_data[child.tag] = value
return array_data
def arrayToXml(self, arr):
"""array转xml"""
xml = [""]
for k, v in arr.items():
if v.isdigit():
xml.append("<{0}>{1}{0}>".format(k, v))
else:
xml.append("<{0}>{0}>".format(k, v))
xml.append(" ")
return "".join(xml)
def saveData(self):
"""将微信的请求xml转换成关联数组,以方便数据处理"""
self.data = self.xmlToArray()
def checkSign(self):
"""校验签名"""
tmpData = dict(self.data) # make a copy to save sign
del tmpData['sign']
sign = self.getSign(tmpData) # 本地签名
if self.data['sign'] == sign:
return True
return False
def getData(self):
"""获取微信的通知的数据"""
return self.data
def trimString(self, value):
if value is not None and len(value) == 0:
value = None
return value
def setReturnParameter(self, parameter, parameterValue):
"""设置返回微信的xml数据"""
self.returnParameters[self.trimString(parameter)] = self.trimString(parameterValue)
def createXml(self):
"""生成接口参数xml"""
return self.arrayToXml(self.returnParameters)
def returnXml(self):
"""将xml数据返回微信"""
returnXml = self.createXml()
return returnXml
views :
if request.method == "POST":
params = request.body.decode('utf-8')
try:
Wxpay_server_pub(params).xmlToArray() # 判断是否xml数据格式
except Exception as e:
pass # 其他需求比如 和alipay 支付同一回调地址
else:
wxpay_params = params # xml 字符串
wxpay = Wxpay_server_pub(wxpay_params) # 创建对象
wxpay.saveData()
wxpay_dict = wxpay.getData()
return_code = wxpay_dict.get('return_code')
if return_code == wxpay.SUCCESS:
ret = wxpay.checkSign() # 校验签名
channel = "微信支付"
subject = None
if ret: # 成功则继续后续操作
wxpay_dict = wxpay.xmlToArray()
amount = wxpay_dict.get('total_fee')
order_no = wxpay_dict.get('out_trade_no')
time_string = wxpay_dict.get('time_end')
result_code = wxpay_dict.get('result_code')
# 时间格式转换
datetime_struct = parser.parse(time_string)
time_paid = datetime_struct.strftime('%Y-%m-%d %H:%M:%S')
# 返回微信数据
wxpay.setReturnParameter("return_code", "SUCCESS")
wxpay.setReturnParameter("return_msg", "OK")
returnXml = wxpay.returnXml()
if result_code == wxpay.SUCCESS:
pass # 根据自己需求码代码
else:
return HttpResponse(wxpay.FAIL)
# 处理完成后 返回微信需要参数
return HttpResponse(returnXml)
代码有点累赘 有需要自己再封装~~~