python实现微信的hmac_sha256加密和md5加密,亲测可用。
md5_sign函数实现微信的md5加密签名,
hmac_sha256函数实现微信的hmac_sha256加密签名。
参考https://blog.csdn.net/weixin_42296492/article/details/89331841
import xmltodict
class WXUtils(object):
"""关于微信支付的小工具"""
@staticmethod
def random_str():
"""
随机32位字符串
"""
return ''.join(random.sample(string.ascii_letters + string.digits, 32))
@staticmethod
def md5_sign(param: dict, shop_key):
"""
param: 需要签名的字典数据
shop_key: 商户平台的密钥
对参数进行MD5加密,获取签名
"""
stringA = ""
ks = sorted(param.keys())
# 排序
for k in ks:
stringA += (k + "=" + str(param[k]) + "&")
# 拼接商户key
stringSignTemp = stringA + 'key=' + shop_key
# md5加密
hash_md5 = hashlib.md5(stringSignTemp.encode('utf-8'))
sign = hash_md5.hexdigest().upper()
return sign
@staticmethod
def hmac_sha256_sign(data: dict, key):
"""
data: 需要签名的字典数据
key: 商户平台设置的密钥key
获取微信的hmac_sha256签名
"""
string_a = ""
ks = sorted(data.keys())
# 排序
for k in ks:
string_a += (k + "=" + str(data[k]) + "&")
# 拼接商户key
sign_temp = string_a + 'key=' + key
key = key.encode('utf-8')
message = sign_temp.encode('utf-8')
sign = hmac.new(key, message, digestmod=sha256).hexdigest().upper()
return sign
@staticmethod
def dict_to_xml(data):
"""
将字典转换为xml
"""
data = {'xml': data}
return xmltodict.unparse(data)
@staticmethod
def xml_to_dict(xml):
"""
将xml数据转换为字典
"""
return xmltodict.parse(xml)