无法发送具有正文(python中)的经过身份验证的OKEx API POST请求。401签名无效。通过身份验证的GET请求可以正常工作

2024-05-13 08:21:29 发布

您现在位置:Python中文网/ 问答频道 /正文

正如标题所示,我能够为OKEx API发送经过身份验证的GET请求,而不会出现任何问题。但是,只要我通过在签名和请求正文中添加额外参数来发出POST请求,我就会得到401响应{'msg':'Invalid Sign','code':'50113'}


def signature(timestamp, method, request_path, body,secret_key):
    if str(body) == '{}' or str(body) == 'None':
        message = str(timestamp) + str.upper(method) + request_path + ''
    else:

        message = str(timestamp) + str.upper(method) + request_path +body
    
    mac = hmac.new(bytes(secret_key, encoding='utf8'), bytes(message, encoding='utf-8'), digestmod='sha256')
    d = mac.digest()
    return base64.b64encode(d)


def get_header(endpoint,request,body={}):

    header = dict()
    header['CONTENT-TYPE'] = 'application/json'
    header['OK-ACCESS-KEY'] = okex_key
    current_time=get_time()
    header['OK-ACCESS-SIGN'] = signature(current_time, request, endpoint , body, okex_secret)
    header['OK-ACCESS-TIMESTAMP'] = str(current_time)
    header['OK-ACCESS-PASSPHRASE'] = okex_pass
    return header


def place_market_order(url,pair,side,amount,tdMode='cash'):

    endpoint='/api/v5/trade/order' 
    request='POST'

    body={
            "instId":pair,
            "tdMode":tdMode, #cash, cross, isolated
            "side":side,
            "ordType":"market",
            "sz":str(Decimal(str(amount)))
        }

    body = json.dumps(body)
    header = get_header(endpoint,request,body)
    response= requests.post(url+endpoint, headers=header,data=body)
    

    return response

#
url = 'http://www.okex.com'

place_market_order(url,pair="BTC-USDT",side="buy",amount=0.001)

签名逻辑应该是正常的,因为经过身份验证的GET请求可以工作

但我处理尸体的方式有什么问题?我正在使用OKEXAPI的v5

提前谢谢


Tags: pathurlaccesstimerequestdefbodyok
1条回答
网友
1楼 · 发布于 2024-05-13 08:21:29

您需要以JSON格式发送POST请求

好例子:

{“机构”:“BTC-USDT”,“tdMode”:“现金”,“方”:“买入”,“订单类型”:“限额”,“sz”:“0.00001”,“px”:“30000”}

坏例子:

机构=BTC-USDT&;tdMode=现金和现金;side=买入&;ordType=极限值&;sz=0.00001&;px=30000

相关问题 更多 >