python支付宝 微信支付工具

1、产生随机字符串,不长于32位

def createNoncestr(length=32):
    chars = "abcdefghijklmnopqrstuvwxyz0123456789"
    strs = []
    for x in range(length):
        strs.append(chars[random.randrange(0, len(chars))])
    return "".join(strs)

2、对签名参数进行去空+排序,返回数组和连接串

# 1、支付宝和微信key值不参与排序
# 2、通联的排序需要带着key
def params_filter(params, key):
    if key:
        params['key'] = key
    prestr = ''
    if 'sign' in params:
        params.pop('sign')
    params = OrderedDict({k: v for k, v in params.items() if v != ''})
    params = OrderedDict(sorted(params.items(), key=lambda t: t[0]))
    print(params)
    for k in params:
        prestr += k + '=' + params[k] + '&'
    prestr = prestr[:-1]
    if 'key' in params:
        params.pop('key')
    return params, prestr

3、生成签名结果

def build_ali_sign(prestr, key, sign_type='MD5'):
    if sign_type == 'MD5':
        m = hashlib.md5()
        # 支付宝:
       if 支付宝:后面直接拼接key值
            m.update((prestr + key).encode("utf-8"))
       if 微信:拼接&key=value
            m.update((prestr + key).encode("utf-8"))
        encodeStr = m.hexdigest()
        return encodeStr
    return ''
# 通联生成签名结果
def build_allin_sign(prestr, sign_type='MD5'):
    if sign_type == 'MD5':
        m = hashlib.md5()
        m.update((prestr).encode("utf-8"))
        encodeStr = m.hexdigest()
        return encodeStr.upper()
    return ''

4、字典转xml格式(微信需要xml)

def xml_params_filter(head, params):
    prestr = ''
    if head:
        prestr = '<' + head + '>'
    params = OrderedDict({k: v for k, v in params.items() if v != ''})
    params = OrderedDict(sorted(params.items(), key=lambda t: t[0]))
    print(params)
    for k in params:
        prestr += '<' + k + '>' + params[k] + ''
    if head:
         prestr += ''
    return prestr

你可能感兴趣的:(python支付宝 微信支付工具)