商户付款到指定微信用户接口调用python实现
文档地址:https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=14_2
代码实现:
class WxHandle(object):
def __init__(self, url, base_param, key, cert_path):
"""
:param url: 请求api
:param base_param: 基本参数 examle {'appid':'wxd930ea5d5a258f4f','mch_id': '10000100','device_info': '1000','body': 'test'}
:param key: 商户平台设置的密钥key
:param cert_path: 证书路径配置 字典形式
"""
self.key = key
self.url = url
self.base_param = base_param
self.cert_path = cert_path
def get_sign(self, param):
assert isinstance(param, dict), "param must be dict instance"
keys = sorted(param)
stringA = ''
for index, key in enumerate(keys):
if not param[key]:
continue
if index == len(keys)-1:
stringA += key + '=' + str(param[key])
else:
stringA += key + '=' + str(param[key]) + "&"
stringSignTemp = stringA + '&key=' + self.key
md = hashlib.md5()
md.update(stringSignTemp.encode('utf-8'))
sign = md.hexdigest().upper()
return sign
def generate_random(self):
return str(uuid.uuid4()).replace('-', '')
def dict_to_xml(self, dict_data):
data = xmltodict.unparse(dict(xml=dict_data))
return data
def parse_xml(self, xml_data):
return dict(xmltodict.parse(xml_data).get('xml'))
def get_res_param(self, param):
param['nonce_str'] = self.generate_random()
param['sign'] = self.get_sign(param)
self.dict_to_xml(param)
return self.dict_to_xml(param)
def request(self):
param = self.get_res_param(self.base_param)
headers = {'Content-Type': 'application/xml'}
try:
res = requests.post(self.url, data=param, headers=headers,
cert=(self.cert_path.get('CERT_PATH'), self.cert_path.get('CERT_KEY_PATH')), verify=True)
except Exception as e:
print(e) # 处理异常
res = None
return res
if __name__ == '__main__':
url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers'
key = "192006250b4c09247ec02edce69f6a2d"
cert_path = {"CERT_PATH": "apiclient_cert.pem", "CERT_KEY_PATH": "apiclient_key.pem"}
base_param = {
'appid':'wxd930ea5d5a258f4f',
'mch_id': '10000100',
'device_info': '1000',
'body': 'test'
}
handle = WxHandle(url, base_param, key, cert_path)
resp = handle.request()
data = handle.parse_xml(resp.text)
print(data)
使用场景:第三方平台的用户提现