之前一篇文章介绍python3封装成类调用微信JSAPI下单、支付、生成付款码,本文介绍python实现微信分账功能。
微信支付里面分账接口调用时需要证书,本文介绍python使用证书。

1 JSAPI文档地址

JSAPI文档,普通商户微信分账是通过https请求实现的。

2 代码实现

封装一个类WxPay,实现微信分账,有如下接口:

  • 普通商户添加分账接收方
  • 普通商户删除分账接收方
  • 普通商户单次分账请求
  • 普通商户查询分账请求
  • 普通商户完结分账

2.1 类主体框架

import logging
import requests
import time
import json
import hmac
import hashlibheaders = {'Accept': 'application/json, text/javascript, */*; q=0.01','Accept-Encoding': 'gzip, deflate, br','Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8','Cache-Control': 'no-cache','Connection': 'keep-alive','Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8','Pragma': 'no-cache','User-Agent': 'self-defind-user-agent','Cookie': 'name=self-define-cookies-in header','X-Requested-With': 'XMLHttpRequest'
}def get_md5(data, salt=True):if salt:return hashlib.md5('get{0}{1}md5'.format(data, time.time()).encode(encoding='UTF-8')).hexdigest()else:return hashlib.md5(data.encode(encoding='UTF-8')).hexdigest()class WxPay:__key = 'xxxxxxxx'  # 商户API密钥,自己的商户密钥__appid = 'xxxxxxxxx'  # 小程序ID(是),自己的小程序ID__mch_id = 'xxxxxx'  # 商户号,自己的商户号__device_info = ''  # 设备号(否),这里用门店号做参数__nonce_str = ''  # 随机字符串(是)__sign = ''  # 签名(是)__body = ''  # 商品描述(是)__out_trade_no = ''  # 商户订单号(是),传入系统商品订单__total_fee = ''  # 标价金额(是),订单总金额,单位为分__spbill_create_ip = ''  # 终端IP(是)__notify_url = 'https://www.xxxxxx.com/'  # 通知地址(是),填项自己的url地址__trade_type = 'JSAPI'  # 交易类型(是),小程序支付__cert_name = 'xxxx.p12' # 证书名称__cert_pwd = 'xxxxx'  # 同__mch_id

2.2 生成随机字符串函数

在类里面定义随机字符串生成函数,代码如下:

 @staticmethoddef get_nonce_str():return get_md5(WxPay.__appid)

2.3 生成MD5签名函数

在类里面定义签名字符串生成函数,代码如下:

 @staticmethoddef get_sign_str(sign_dict: dict):data = ''sort_keys = sorted(sign_dict)  # 从小到大排序for i, key in enumerate(sort_keys):data += '{0}={1}&'.format(key, sign_dict.get(key, ''))data += 'key={0}'.format(WxPay.__key)print(data)return get_md5(data, False).upper()

注意:签名里面的key一定要先按升序排序,再组合生成MD5

2.4 生成HMAC-SHA256签名函数

 @staticmethoddef create_hmac_sha256_signature(key: str, message: str):byte_key = key.encode('utf-8')message = message.encode('utf-8')return hmac.new(byte_key, message, hashlib.sha256).hexdigest().upper()@staticmethoddef get_sign_strc_hmac_sha256(sign_dict: dict):data = ''sort_keys = sorted(sign_dict)  # 从小到大排序for i, key in enumerate(sort_keys):data += '{0}={1}&'.format(key, sign_dict.get(key, ''))data += 'key={0}'.format(WxPay.__key)print(data)return WxPay.create_hmac_sha256_signature(WxPay.__key, data)

2.5 数据转换函数

 @staticmethoddef get_xml_str(sign_dict: dict):xml_data = '<xml>'for k, v in sign_dict.items():xml_data += '<{0}>{1}</{0}>'.format(k, v)xml_data += '</xml>'# print(xml_data)return xml_data@staticmethoddef xml_to_dict(xml_data: str):dict_data = {}result = xml_data.split('\n')for res in result:if 'total_fee' in res:dict_data['total_fee'] = res.split('<total_fee>')[-1].split('<')[0]continuetmp1 = res.split('><![CDATA[')if len(tmp1) == 2:tmp2, tmp3 = tmp1[0].split('<'), tmp1[1].split(']')dict_data[tmp2[-1]] = tmp3[0] if tmp3 else ''return dict_data

2.6 创建带证书接口请求函数

  1. 先安装requests_pkcs12,用于发送带证书接口请求
  2. 微信申请证书,参照微信证书申请文档
  3. 代码如下:
 @staticmethoddef send_post_cert(url, jsonData):try:from requests_pkcs12 import post# 注意:用res.content,不用res.text,否则会有中文乱码res = post(url=url, data=jsonData.encode('utf-8'), headers=headers,pkcs12_filename=WxPay.__cert_name, pkcs12_password=WxPay.__cert_pwd)print(res.content.decode("utf-8"))return res.content.decode("utf-8")except Exception as e:logging.error('[send_get]Failed to json.load, {0}'.format(e))return ''

说明:

  • pkcs12_filename:对应的是证书名称
  • pkcs12_password:对应证书密码,密码是商户号
  • 证书格式:.p12格式证书

2.7 普通商户添加分账接收方

 @staticmethoddef profit_add_receiver(type: str, account: str, relation_type: str):  # 普通商户添加分账接收方# https://pay.weixin.qq.com/wiki/doc/api/allocation.php?chapter=27_1&index=1nonce_str = WxPay.get_nonce_str()argc_dict = {'appid': WxPay.__appid, 'mch_id': WxPay.__mch_id,'receiver': json.dumps({'account': account, 'relation_type': relation_type, 'type': type},separators=(',', ':'), ensure_ascii=False),'nonce_str': nonce_str, 'sign_type': 'HMAC-SHA256'}sign_str = WxPay.get_sign_strc_hmac_sha256(argc_dict)argc_dict['sign'] = sign_strurl = 'https://api.mch.weixin.qq.com/pay/profitsharingaddreceiver'data = WxPay.get_xml_str(argc_dict)return WxPay.send_post(url, data)

2.8 普通商户删除分账接收方

 @staticmethoddef profit_del_receiver(type: str, account: str):  # 普通商户删除分账接收方# https://pay.weixin.qq.com/wiki/doc/api/allocation.php?chapter=27_1&index=1nonce_str = WxPay.get_nonce_str()argc_dict = {'appid': WxPay.__appid, 'mch_id': WxPay.__mch_id,'receiver': json.dumps({'account': account, 'type': type},separators=(',', ':'), ensure_ascii=False),'nonce_str': nonce_str, 'sign_type': 'HMAC-SHA256'}sign_str = WxPay.get_sign_strc_hmac_sha256(argc_dict)argc_dict['sign'] = sign_strurl = 'https://api.mch.weixin.qq.com/pay/profitsharingremovereceiver'data = WxPay.get_xml_str(argc_dict)return WxPay.send_post(url, data)

2.9 普通商户单次分账请求

 @staticmethoddef create_profit_sharing(transaction_id: str, out_order_no: str, type: str, account: str, amount: int,description: str):  # 普通商户单次分账请求# https://pay.weixin.qq.com/wiki/doc/api/allocation.php?chapter=27_1&index=1nonce_str = WxPay.get_nonce_str()argc_dict = {'appid': WxPay.__appid, 'mch_id': WxPay.__mch_id, 'transaction_id': transaction_id,'out_order_no': out_order_no,'receivers': json.dumps({'account': account, 'amount': amount, 'description': description,'type': type}, separators=(',', ':'), ensure_ascii=False),'nonce_str': nonce_str, 'sign_type': 'HMAC-SHA256'}sign_str = WxPay.get_sign_strc_hmac_sha256(argc_dict)argc_dict['sign'] = sign_strurl = 'https://api.mch.weixin.qq.com/secapi/pay/profitsharing'data = WxPay.get_xml_str(argc_dict)return WxPay.send_post_cert(url, data)

2.10 普通商户查询分账请求

 @staticmethoddef get_profit_sharing(transaction_id: str, out_order_no: str):  # 普通商户查询分账请求# https://pay.weixin.qq.com/wiki/doc/api/allocation.php?chapter=27_1&index=1nonce_str = WxPay.get_nonce_str()argc_dict = {'mch_id': WxPay.__mch_id, 'transaction_id': transaction_id,'out_order_no': out_order_no, 'nonce_str': nonce_str, 'sign_type': 'HMAC-SHA256'}sign_str = WxPay.get_sign_strc_hmac_sha256(argc_dict)argc_dict['sign'] = sign_strurl = 'https://api.mch.weixin.qq.com/pay/profitsharingquery'data = WxPay.get_xml_str(argc_dict)return WxPay.send_post(url, data)

2.11 普通商户完结分账

 @staticmethoddef finish_profit_sharing(transaction_id: str, out_order_no: str, description: str):  # 普通商户完结分账# https://pay.weixin.qq.com/wiki/doc/api/allocation.php?chapter=27_1&index=1nonce_str = WxPay.get_nonce_str()argc_dict = {'appid': WxPay.__appid, 'mch_id': WxPay.__mch_id, 'transaction_id': transaction_id,'out_order_no': out_order_no, 'description': description,'nonce_str': nonce_str, 'sign_type': 'HMAC-SHA256'}sign_str = WxPay.get_sign_strc_hmac_sha256(argc_dict)argc_dict['sign'] = sign_strurl = 'https://api.mch.weixin.qq.com/secapi/pay/profitsharingfinish'data = WxPay.get_xml_str(argc_dict)return WxPay.send_post_cert(url, data)

3 完整代码

完整代码和接口调用例子

python3封装微信分账功能相关推荐

  1. 微信分账功能与微信支付企业付款相关内容详解(payjs版)

    PAYJS开通微信分账功能以来,有很多同学咨询相关情况.很多同学关心有没有什么办法,可以让自己的商户号快速开通企业付款功能.这里就介绍下微信分账的具体相关内容,可以完美解决问题. 一.什么是微信分账? ...

  2. 微信分账功能 Java 开发

    提示"没有分账权限",参考这里开通. 预下单要 profit_sharing 设为 true,默认是 false 不支持分账的: 分账个人接收方姓名 name,这个是可选的.如果填 ...

  3. 10 分钟了解微信分账 | 微信生态下的最优资金清分方案

    一.什么是微信分账 微信分账即微信推出的交易资金再分配产品,收款后按照平台的业务规则,无需中转直接进行资金分配:主要用于服务商帮助特约商户完成订单收单后的资金分配. 微信分账的推出主要有三个方面的原因 ...

  4. 微信开放平台分账功能实战(Java版)

    ####近期为了接入微信支付以及微信分账等功能,开发了微信类的一系列接口,下面就本着开发的目标,再次记录回顾一下微信开放的步骤.. ####目标:通过微信支付,实现分账到运营商的功能. ####根据实 ...

  5. 实用教程 | 一文读懂「微信分账」功能

    在现有的微信支付互联网生态环境中,存在平台方角色,如电商平台.加盟代理等,用户支付订单金额后,先由平台方统一收款,再由平台方与商家或其他参与方进行结算,若无引入具有支付牌照的第三方,则为「二清」行为, ...

  6. 电商平台分账功能如何实现?

    随着互联网的快速发展,电商平台成了互联网时代下的宠儿,发展得如火如荼,不断冲击着传统企业和传统商业模式.越来越多传统企业通过自建电商平台实现业务上的转型升级,同时也有许多新手创业者嗅到其中商机,纷纷加 ...

  7. 微信分账系统怎么开通?

    在疫情影响下,越来越多企业将业务转为线上化发展,伴随着交易订单的增多,财务人员的分账记账工作越发复杂,为了提高企业的交易管理效率,很多企业考虑接入分账系统.有的企业想要了解微信分账系统怎么开通,接下来 ...

  8. 微信分账:分账接收方列表格式错误

    项目场景: 提示:这里简述项目相关背景: 例如:项目场景:微信商户(不是服务商)做微信分账,再添加分账接收方的时候,微信返回:分账接收方列表格式错误. 问题描述 微信商户(不是服务商)做微信分账,在添 ...

  9. 小程序----分账功能开发

    1.登录商户后台,在产品中心中开通[分账]功能 2.按照文档对接接口 3.发现报错[errCodeDes: "没有分账权限"],搜索发现需要先填写邀请问卷,这个是入口 问卷系统 填 ...

最新文章

  1. jQueryUI Repeater 无刷新删除 新建 更新数据 - JQueryElement [7]
  2. 009_字符串内建函数
  3. 最牛啤的java,没有之一~
  4. 腾讯计费全面开放,为你而来!
  5. tensorflow1、2会话、变量、feed、fetch、最小二乘法
  6. np.squeeze()
  7. html瀑布流视频列表,StaggeredGridLayoutManager实现瀑布流视频列表和头部广告位以及分栏Header条...
  8. 色彩管理实验 matlab,色彩管理实验报告1
  9. 移动安全大讲堂:整体解决方案之Android加固保护
  10. aix 在线软件包安装 字符集 mysql安装
  11. sigar 监控服务器硬件信息
  12. 云计算对网络学习,主要有哪些影响?
  13. 转贴: 傅立叶级数(Fourier Series) 推导
  14. 开源工具:5个优秀的音频编辑器
  15. PHP发送邮件SMTP发邮件,超简单引用,CtrlCV即可实现邮件反馈系统
  16. ArcGIS 网络分析[2.3] 最近设施点
  17. 论文翻译解读:Logmap:Logic-based and scalable ontology matching
  18. PLASTIGAUGE塑料间隙规的正确使用步骤你知道多少?
  19. Map根据Key值进行排序(升序加降序)
  20. iOS 自动布局和弹性盒子

热门文章

  1. 全球回报最好的 40 个 VC 投资案例,我们可以从中学到什么?
  2. html怎么设置毛笔字体,三种实用的毛笔书法字体设计制作教程
  3. JS第二次授课及字节跳动2017秋招前端工程师笔试试卷涉及知识点
  4. linux删除文件面面观
  5. Linux kernel panic 问题解决方案
  6. BZOJ1022 [SHOI2008]小约翰的游戏John 【博弈论】
  7. citrix vdi 服务器性能要求,Citrix测试VDI的最佳hypervisor
  8. 解决DELL台式机两用音频接口不能识别耳麦的问题
  9. 计算机名和DNS域名的关系,域名、DNS、IP地址的对应关系
  10. Asan快速定位内存越界、内存泄漏