wechatpay.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. # coding=utf-8
  2. import uuid
  3. import requests
  4. import json
  5. import xmltodict
  6. import time
  7. from hashlib import md5
  8. from django.conf import settings
  9. from util.splitaccount_tool import SplitAccountTool
  10. from util.exceptions import CustomError
  11. from apps.foundation.models import BizLog
  12. # 微信支付sign_type
  13. WEIXIN_SIGN_TYPE = 'MD5'
  14. # 服务器IP地址
  15. WEIXIN_SPBILL_CREATE_IP = '139.9.148.181'
  16. # 微信支付用途
  17. WEIXIN_BODY = u'小程序支付'
  18. # 微信统一下单URL
  19. WEIXIN_UNIFIED_ORDER_URL = 'https://api.mch.weixin.qq.com/pay/unifiedorder'
  20. # 微信查询订单URL
  21. WEIXIN_QUERY_ORDER_URL = 'https://api.mch.weixin.qq.com/pay/orderquery'
  22. # 微信支付回调API
  23. WEIXIN_CALLBACK_API = 'https://lsr.zzly.vip/api/wechat_notify/'
  24. class SplitAccountFuc(object):
  25. '''直连服务商 分账 文档https://pay.weixin.qq.com/wiki/doc/apiv3/index.shtml'''
  26. def __init__(self,appid, mchid, private_key, cert_serial_no, apiv3_key, cert_dir=None, proxy=None):
  27. self._appid = appid
  28. self._mchid = mchid
  29. self._core = SplitAccountTool(appid, mchid, private_key, cert_serial_no, apiv3_key, cert_dir=cert_dir, proxy=proxy)
  30. def splitaccount_order(self, transaction_id, out_order_no, receivers):
  31. '''
  32. 请求分账 微信订单支付成功后,服务商代特约商户发起分账请求,将结算后的钱分到分账接收方
  33. 注意:对同一笔订单最多能发起50次分账请求,每次请求最多分给50个接收方
  34. 此接口采用异步处理模式,即在接收到商户请求后,优先受理请求再异步处理,最终的分账结果可以通过查询分账接口获取
  35. 请求分账里边的openid 是需要先调用添加分账接收方接口添加分账关系
  36. '''
  37. path = "/v3/profitsharing/orders"
  38. params = {
  39. 'appid': self._appid,
  40. 'transaction_id': transaction_id, # 微信支付订单号
  41. 'out_order_no': out_order_no, # 商户系统内部的分账单号,在商户系统内部唯一,同一分账单号多次请求等同一次。只能是数字、大小写字母_-|*@
  42. 'receivers': [],
  43. 'unfreeze_unsplit': True # 是否解冻剩余未分金额 如果只分一次就填true
  44. }
  45. for item in receivers:
  46. receiver_item = {
  47. 'type': 'PERSONAL_OPENID',
  48. 'account': item['account'],
  49. 'amount': int(round(item['amount'], 0)), # 单位为分 只能为整数 不能超过原订单支付金额及最大分账比例金额
  50. 'description': item['description']
  51. }
  52. params['receivers'].append(receiver_item)
  53. success = True
  54. data = {}
  55. try:
  56. code, message = self._core.request(path, SplitAccountTool.POST, data=params)
  57. result = json.loads(message)
  58. if code == 200:
  59. data['order_id'] = result.get('order_id')
  60. data['state'] = result.get('state')
  61. data['receivers'] = result.get('receivers')
  62. else:
  63. success = False
  64. BizLog.objects.addnew('', BizLog.INSERT, u'[%s]分账失败!原因:' % out_order_no + result.get('code'))
  65. except CustomError as e:
  66. success = False
  67. BizLog.objects.addnew('', BizLog.INSERT, u'[%s]分账失败!原因:' % out_order_no + e.get_error_msg())
  68. except Exception as e:
  69. success = False
  70. BizLog.objects.addnew('', BizLog.INSERT, u'[%s]分账失败!原因:' % out_order_no + str(e))
  71. return success, data
  72. def splitaccount_addreceiver(self, account):
  73. '''添加分账接收方'''
  74. path = "/v3/profitsharing/receivers/add"
  75. params = {
  76. 'appid': self._appid,
  77. 'type': "PERSONAL_OPENID",
  78. 'account': account, # 接收人的openid
  79. 'relation_type': "USER", # body子商户与接收方的关系
  80. }
  81. success = True
  82. try:
  83. code, message = self._core.request(path, SplitAccountTool.POST, data=params)
  84. result = json.loads(message)
  85. if code != 200:
  86. success = False
  87. BizLog.objects.addnew('', BizLog.INSERT, u'[%s]添加分账接收方失败!原因:' % account + result.get('code'))
  88. except CustomError as e:
  89. success = False
  90. BizLog.objects.addnew('', BizLog.INSERT, u'[%s]添加分账接收方失败!原因:' % account + e.get_error_msg())
  91. except Exception as e:
  92. success = False
  93. BizLog.objects.addnew('', BizLog.INSERT, u'[%s]添加分账接收方失败!原因:' % account + str(e))
  94. return success
  95. def splitaccount_deletereceiver(self, account):
  96. '''删除分账接收方'''
  97. path = "/v3/profitsharing/receivers/delete"
  98. params = {
  99. 'appid': self._appid,
  100. 'type': "PERSONAL_OPENID",
  101. 'account': account, # 接收人的openid
  102. }
  103. success = True
  104. try:
  105. code, message = self._core.request(path, SplitAccountTool.POST, data=params)
  106. result = json.loads(message)
  107. if code != 200:
  108. success = False
  109. BizLog.objects.addnew('', BizLog.INSERT, u'[%s]删除分账接收方失败!原因:' % account + result.get('code'))
  110. except CustomError as e:
  111. success = False
  112. BizLog.objects.addnew('', BizLog.INSERT, u'[%s]删除分账接收方失败!原因:' % account + e.get_error_msg())
  113. except Exception as e:
  114. success = False
  115. BizLog.objects.addnew('', BizLog.INSERT, u'[%s]删除分账接收方失败!原因:' % account + str(e))
  116. return success
  117. def splitaccount_orderquery(self, transaction_id, out_order_no):
  118. '''
  119. 查询分账结果
  120. transaction_id 微信支付订单号
  121. out_order_no 商户分账单号
  122. '''
  123. success = True
  124. data = {}
  125. if transaction_id and out_order_no:
  126. path = '/v3/profitsharing/orders/%s?transaction_id=%s' % (out_order_no, transaction_id)
  127. else:
  128. success = False
  129. BizLog.objects.addnew('', BizLog.INSERT, u'[%s]查询分账结果失败!原因:参数错误!' % out_order_no)
  130. return success, data
  131. try:
  132. code, message = self._core.request(path)
  133. result = json.loads(message)
  134. if code == 200:
  135. data['order_id'] = result.get('order_id')
  136. data['state'] = result.get('state')
  137. data['receivers'] = result.get('receivers')
  138. else:
  139. success = False
  140. BizLog.objects.addnew('', BizLog.INSERT, u'[%s]查询分账结果失败!原因:' % out_order_no + result.get('code'))
  141. except CustomError as e:
  142. success = False
  143. BizLog.objects.addnew('', BizLog.INSERT, u'[%s]查询分账结果失败!原因:' % out_order_no + e.get_error_msg())
  144. except Exception as e:
  145. success = False
  146. BizLog.objects.addnew('', BizLog.INSERT, u'[%s]查询分账结果失败!原因:' % out_order_no + str(e))
  147. return success, data
  148. def splitaccount_return(self):
  149. '''请求分账回退'''
  150. pass
  151. def splitaccount_returnquery(self):
  152. '''查询分账回退结果'''
  153. pass
  154. def splitaccount_unfreeze(self, transaction_id, out_order_no):
  155. '''解冻剩余资金'''
  156. path = "/v3/profitsharing/orders"
  157. params = {
  158. 'transaction_id': transaction_id, # 微信支付订单号
  159. 'out_order_no': out_order_no, # 商户系统内部的分账单号,在商户系统内部唯一,同一分账单号多次请求等同一次。只能是数字、大小写字母_-|*@
  160. 'description': "解冻资金"
  161. }
  162. success = True
  163. data = {}
  164. try:
  165. code, message = self._core.request(path, SplitAccountTool.POST, data=params)
  166. result = json.loads(message)
  167. if code == 200:
  168. data['order_id'] = result.get('order_id')
  169. data['state'] = result.get('state')
  170. data['receivers'] = result.get('receivers')
  171. else:
  172. success = False
  173. BizLog.objects.addnew('', BizLog.INSERT, u'[%s]解冻剩余资金失败!原因:'% out_order_no + result.get('code'))
  174. except CustomError as e:
  175. success = False
  176. BizLog.objects.addnew('', BizLog.INSERT, u'[%s]解冻剩余资金失败!原因:'% out_order_no + e.get_error_msg())
  177. except Exception as e:
  178. success = False
  179. BizLog.objects.addnew('', BizLog.INSERT, u'[%s]解冻剩余资金失败!原因:'% out_order_no + str(e))
  180. return success, data
  181. def splitaccount_amountquery(self):
  182. '''查询剩余待分金额'''
  183. pass
  184. def splitaccount_configquery(self):
  185. '''查询最大分账比例'''
  186. pass
  187. def splitaccount_bill(self):
  188. '''申请分账账单'''
  189. pass
  190. class WeChatResponse():
  191. def __init__(self,appid, agent_num, agent_key):
  192. self.params = {
  193. "appid": appid,
  194. 'mch_id': agent_num,
  195. 'nonce_str': '',
  196. 'sign_type': WEIXIN_SIGN_TYPE,
  197. 'sign': '',
  198. 'out_trade_no': '',
  199. }
  200. self.prepay_id = None
  201. self.merchant_key = agent_key
  202. # 查询订单
  203. def orderquery(self, out_trade_no):
  204. self.params['out_trade_no'] = out_trade_no
  205. self.params['nonce_str'] = generate_nonce_str()
  206. self.params['sign'] = generate_sign(self.params, self.merchant_key)
  207. data = xmltodict.unparse({'xml': self.params}, pretty=True, full_document=False).encode('utf-8')
  208. headers = {'Content-Type': 'application/xml'}
  209. res = requests.post(WEIXIN_QUERY_ORDER_URL, data=data, headers=headers)
  210. if res.status_code != 200:
  211. raise CustomError(u'微信请求失败!')
  212. result = json.loads(json.dumps(xmltodict.parse(res.content)))
  213. if result['xml']['return_code'] != 'SUCCESS':
  214. raise CustomError(u'微信通信失败![%s]' % result['xml']['return_msg'])
  215. print(u'微信交易状态![%s]' % (result['xml']['trade_state_desc']))
  216. if result['xml']['trade_state'] == 'NOTPAY':
  217. return result['xml']['total_fee']
  218. # raise CustomError(u'微信交易状态![%s]' % (result['xml']['trade_state_desc']))
  219. # 其他状态,返回金额0
  220. return 0
  221. # return result['xml']['total_fee']
  222. class WechatPay():
  223. def __init__(self, appid, mch_id, merchant_key):
  224. self.params = {
  225. 'appid': appid,
  226. 'mch_id': mch_id,
  227. 'nonce_str': '',
  228. 'sign_type': WEIXIN_SIGN_TYPE,
  229. 'body': WEIXIN_BODY,
  230. 'out_trade_no': '',
  231. 'total_fee': '',
  232. 'spbill_create_ip': WEIXIN_SPBILL_CREATE_IP,
  233. 'notify_url': WEIXIN_CALLBACK_API + appid + '/',
  234. 'trade_type': 'JSAPI'
  235. }
  236. self.prepay_id = None
  237. self.merchant_key = merchant_key
  238. def getAppString(self):
  239. data = {
  240. 'appId': self.params['appid'],
  241. 'signType': WEIXIN_SIGN_TYPE,
  242. 'package': "prepay_id={}".format(self.prepay_id),
  243. 'nonceStr': generate_nonce_str(),
  244. 'timeStamp': str(int(time.time()))
  245. }
  246. data['paySign'] = generate_sign(data, self.merchant_key)
  247. data.pop('appId')
  248. return data
  249. def unifiedOrder(self,out_trade_no,total_fee, openid, profit_sharing):
  250. self.params['profit_sharing'] = profit_sharing # 是否分账参数 Y 需要分账 N 不分账 字母大写默认不分账
  251. self.params['out_trade_no'] = out_trade_no
  252. self.params['total_fee'] = int(round(total_fee, 0))
  253. self.params['openid'] = openid
  254. self.params['nonce_str'] = generate_nonce_str()
  255. self.params['sign'] = generate_sign(self.params, self.merchant_key)
  256. data = xmltodict.unparse({'xml': self.params}, pretty=True, full_document=False).encode('utf-8')
  257. headers = {'Content-Type': 'application/xml'}
  258. res = requests.post(WEIXIN_UNIFIED_ORDER_URL, data=data, headers=headers)
  259. if res.status_code != 200:
  260. raise CustomError(u'微信请求失败!')
  261. result = json.loads(json.dumps(xmltodict.parse(res.content)))
  262. if result['xml']['return_code'] != 'SUCCESS':
  263. raise CustomError(u'微信通信失败![%s]' % result['xml']['return_msg'])
  264. if result['xml']['result_code'] != 'SUCCESS':
  265. raise CustomError(u'微信交易失败![%s:%s]' % (result['xml']['err_code'],result['xml']['err_code_des']))
  266. self.prepay_id = result['xml']['prepay_id']
  267. return result['xml']
  268. class WechatPayNotify():
  269. def __init__(self,params, merchant_key):
  270. self.params = params
  271. self.merchant_key = merchant_key
  272. def handle(self):
  273. resp_dict = json.loads(json.dumps(xmltodict.parse(self.params)))['xml']
  274. return_code = resp_dict['return_code']
  275. if return_code != 'SUCCESS':
  276. return None
  277. if not validate_sign(resp_dict, self.merchant_key):
  278. return None
  279. return resp_dict
  280. @staticmethod
  281. def response_ok():
  282. return_info = {
  283. 'return_code': 'SUCCESS',
  284. 'return_msg': 'OK'
  285. }
  286. return generate_response_data(return_info)
  287. @staticmethod
  288. def response_fail():
  289. return_info = {
  290. 'return_code': 'FAIL',
  291. 'return_msg': 'FAIL'
  292. }
  293. return generate_response_data(return_info)
  294. def generate_nonce_str():
  295. """
  296. 生成随机字符串
  297. """
  298. return str(uuid.uuid4()).replace('-', '')
  299. def generate_sign(params, merchant_key):
  300. """
  301. 生成md5签名的参数
  302. """
  303. if 'sign' in params:
  304. params.pop('sign')
  305. src = '&'.join(['%s=%s' % (k, v) for k, v in sorted(params.items())]) + '&key=%s' % merchant_key
  306. return md5(src.encode('utf-8')).hexdigest().upper()
  307. def validate_sign(resp_dict, merchant_key):
  308. """
  309. 验证微信返回的签名
  310. """
  311. if 'sign' not in resp_dict:
  312. return False
  313. wx_sign = resp_dict['sign']
  314. sign = generate_sign(resp_dict, merchant_key)
  315. if sign == wx_sign:
  316. return True
  317. return False
  318. def generate_response_data(resp_dict):
  319. """
  320. 字典转xml
  321. """
  322. return xmltodict.unparse({'xml': resp_dict}, pretty=True, full_document=False).encode('utf-8')