接口请求加签名

def create_salt(length):
    salt = ''
    chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789!@#$%&*^()-+=[]{}|_`~?/,.<>;:'
    len_chars = len(chars) - 1
    for i in range(length):
        # 每次从chars中随机取一位
        salt += chars[random.randint(0, len_chars)]
    return salt

salt = create_salt(8)

def flat(prefix, obj):
    l = []
    if type(obj) == dict:
        if obj:
            for k, v in obj.items():
                l = l + flat(prefix + '.' + k if len(prefix) else k, v)
        else:
            l = [prefix + '=' + str(obj)]
    elif type(obj) == list:
        if obj:
            for i, v in enumerate(obj):
                l = l + flat(prefix + '[' + str(i) + ']', v)
        else:
            l = [prefix + '=' + str(obj)]
    elif type(obj) == float:
        obj = '{:.11e}'.format(obj).replace('e+0', 'E')
        l = [prefix + '=' + str(obj)]
    elif obj is None:
        pass
    elif obj is True:
        l = [prefix + '=true']
    elif obj is False:
        l = [prefix + '=false']
    else:
        l = [prefix + '=' + str(obj)]
    return l

def sign(obj):
    # 如果有signature字段,删除掉,签名不包含signature字段
    if "signature" in obj.keys():
        del obj["signature"]
    # 注意设置对应的senderKey
    s = '&'.join(sorted(flat('', obj) + ['senderKey=123456789']))

    return hashlib.sha256(s.encode('utf-8')).hexdigest()

def create_body(request_body,sender="xxxxxx"):
    # request_body = json.loads(request_body)
    request_body['requestId'] = requestId
    request_body['locale'] = "en_KE"
    request_body['sender'] = sender
    request_body['salt'] = salt
    request_body['timestamp'] = timestamp
    signature = sign(request_body)
    request_body['signature'] = signature
    request_body = json.dumps(request_body)
    return request_body

示例

request_body = {
    "params": {
        "key1": "xxxxxx",
        "key2": "ddddddd"
    },
    "signature": ""
}
url= "http://xxxxxxxxx.com"
a=create_body(request_body)
body=json.loads(a)
print(body)
r2=requests.post(url=url,  json=body,  verify= False)
print(r2.content.decode())
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值