qrcode_be/lib/signature.py
2019-12-09 09:48:07 +08:00

37 lines
870 B
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from hashlib import md5
from urllib.parse import urlencode, unquote_plus
def get_signature(key: str, data: dict):
"""
签名过程如下:
0. 忽略已经存在的 sign
1. 将所有参数名按照字典序排列,并以 "参数1=值1&参数2=值2&参数3=值3" 的形式排序
2. 将上面的内容加上 "&key=KEY"KEY 为设置的商户密钥)
3. 将组合后的字符串转换为大写 MD5
:param key: 商户密钥
:param data: 要签名的参数字典
:return: 签名后的字符串
:rtype: str
"""
d = data.copy()
# pop 掉 sign 字段
try:
d.pop('sign')
except KeyError:
pass
# pop 掉无效字段
p = sorted([x for x in d.items() if (x[1] or x[1] == 0)], key=lambda x: x[0])
p.append(('key', key))
p = unquote_plus(urlencode(p))
h = md5()
h.update(p.encode())
r = h.hexdigest().upper()
return r