Python 3.6 微信支付(app支付)
阿新 • • 發佈:2019-01-04
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 = "<xml>" for k, v in self.params.items(): # v = v.encode('utf8') # k = k.encode('utf8') xml += '<' + k + '>' + v + '</' + k + '>' xml += "</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) })
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 = ["<xml>"]
for k, v in arr.items():
if v.isdigit():
xml.append("<{0}>{1}</{0}>".format(k, v))
else:
xml.append("<{0}><![CDATA[{1}]]></{0}>".format(k, v))
xml.append("</xml>")
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)
程式碼有點累贅 有需要自己再封裝~~~