python实现支付接口的sign签名

 

 

 通过python代码来实现: 

#!/usr/bin/env python
import hashlib  # 导入模块hashlib
# md5加密算法
def MD5(str):
    md = hashlib.md5()  # 创建md5对象
    md.update(str.encode(encoding='utf-8'))
    return md.hexdigest()

# 获取sign签名
def getSign(map: dict, key: str):
    # 遍历字典,组成特定格式(k1=v1&)字符串的列表
    list = []
    for k, v in map.items():
        list.append(k + '=' + v + '&')
    # 列表中,根据元素的字母顺序排序(也就是根据键的字母顺序排)
    list.sort()
    #print(list)
    # 遍历排序后的列表
    result = ''
    for i in list:
        result = result + i
    result_new = result + 'key=' + key
    # print(result_new)
    # md5加密,并转为大写。
    sign = MD5(result_new).upper()
    # 返回sign和最终请求参数
    return sign, result+'sign='+sign

# 主程序
if __name__ == "__main__":
    # 加密秘钥
    key = "THqPive499Pyt6ve4FupdyUIve4TxMySve4O9Pyt6FuQaJvve4ove4Nehg69I4jtu7Ave4YzLJPAve4"
    # 声明字典,用于存放请求参数
    map = {}
    map['mchNo'] = 'C1649497788'
    map['appId'] = 'b70bbe4b06259914c70ba'
    map['mchOrderNo'] = 'H011695922'
    map['wayCode'] = 'ALI_WAP'
    map['amount'] = "100"
    map['currency'] = 'CNY'
    map['subject'] = 'mysubject'
    map['body'] = 'mybody'
    map['notifyUrl'] = 'http://api-user.user.com/payment/jcc-pay-notify/jjpay'
    map['version'] = '2.0'
    map['reqTime'] = '1650198094100'  # 请求时间戳13位,可以百度查询当前时间对应的时间戳
    map['signType'] = 'MD5'
    # 进行签名
    sign, request = getSign(map, key)
    print(sign)
    print(request)

 

posted @ 2022-05-03 02:21  乌鸦哥  阅读(504)  评论(3编辑  收藏  举报