Python中的API调用身份验证(工作PHP示例)

2024-03-28 13:18:11 发布

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

我正试图编写一个脚本来与在线交换进行通信。
“Public”请求发送到:https://yobit.net/api/3/
“Trade”请求发送到:https://yobit.net/tapi/

我的公开请求很有效。不过,我的“私人电话”返回404错误。 我的钥匙100%正确。
我当前生成以下URL:https://yobit.net/tapi/activeorders/ltc_btc/&apikey=MY_APIKEY_HERE&nonce=1456192036

我没有把文件解释清楚吗?可能是一个错误的URL结构?

文档链接--->;here
每个Trade API请求都应该通过身份验证。 通过发送以下HTTP标题来完成身份验证: 键-API键,例如:FAF816D16FFDFBD1D46EEF5D5B10D8A2 签名-数字签名,POST参数(?)?param0=val0&;..&;nonce=1)通过HMAC-SHA512由密钥签名 后续请求中的参数nonce(最小值为1,最大值为2147483646)应超过前一个请求中的参数nonce。 要使nonce为空,必须生成新密钥。

我的脚本

class yobit(object):

def __init__(self, key, secret):
    self.key = key
    self.secret = secret
    self.public = ['info', 'ticker', 'depth', 'trades']
    self.trade = ['activeorders']


def query(self, method, values={}):
    if method in self.public:
        url = 'https://yobit.net/api/3/'
    elif method in self.trade:
        url = 'https://yobit.net/tapi/'
    else:
        return 'You're doing it wrong'

    urlString = ''
    for i, k in values.iteritems():
        urlString += k+'/'

    url += method + '/' + urlString

    print url
    if method not in self.public:
        url += '&apikey=' + self.key
        url += '&nonce=' + str(int(time.time()))
        signature = hmac.new(self.secret, url, hashlib.sha512).hexdigest()
        headers = {'apisign': signature}
    else:
        headers = {}
    print url

    req = requests.get(url, headers=headers)
    response = json.loads(req.text)
    return response
#######公共API
def getinfo(self):
    return self.query('info')

def getticker(self, currency):
    return self.query('ticker', {'currency': currency})

def getdepth(self, currency):
    return self.query('depth', {'currency': currency})

def gettrades(self, currency):
    return self.query('trades', {'currency': currency})
#####贸易原料药
def getactiveorders(self, pair):
    return self.query('activeorders', {'pair': pair})

PHP中的一个工作示例 我相信这是一个PHP的工作示例,不幸的是我不能阅读这门语言。

function yobit_api_query2($method, $req = array())
{
$api_key    = '';
$api_secret = '';

$req['method'] = $method;
$req['nonce'] = time();
$post_data = http_build_query($req, '', '&');
$sign = hash_hmac("sha512", $post_data, $api_secret);
$headers = array(
    'Sign: '.$sign,
    'Key: '.$api_key,
);

$ch = null;
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; SMART_API PHP client; '.php_uname('s').'; PHP/'.phpversion().')');
curl_setopt($ch, CURLOPT_URL, 'https://yobit.net/tapi/');
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_ENCODING , 'gzip');
$res = curl_exec($ch);
if($res === false)
{
    $e = curl_error($ch);
    debuglog($e);
    curl_close($ch);
    return null;
}

curl_close($ch);

$result = json_decode($res, true);
if(!$result) debuglog($res);

return $result;
}

Tags: httpsselfapiurlreturndefcurlch
1条回答
网友
1楼 · 发布于 2024-03-28 13:18:11

我自己才想出来,在这个过程中碰到了你的问题。关于trade API的YoBit文档在如何格式化请求方面有点欠缺。

您希望向API端点发出POST请求,并包含所有参数,包括方法本身作为POST参数。然后,对请求主体(POST params)进行签名,并将其与公钥一起作为HTTP头。

对于TradeHistory请求,这是伪代码;我不太了解Python。希望你能破译或者有人能把它化脓!

request_url = "https://yobit.net/tapi";
request_body = "method=TradeHistory&pair=ltc_btc&nonce=123";
signature = hmac_sha512(request_body,yobit_secret);
http_headers = {
    "Content-Type":"application/x-www-form-urlencoded",
    "Key":yobit_public_key,
    "Sign":signature
}

response = http_post_request(request_url,request_body,http_headers);
result = json_decode(response.text);

更新:以下是在Python 3中使用对象作为引用时可以执行的操作:

import time,hmac,hashlib,requests,json
from urllib.parse import urlencode

class yobit(object):

def __init__(self, key, secret):
    self.key = 'KEY'
    self.secret = b'SECRET'
    self.public = ['info', 'ticker', 'depth', 'trades']
    self.trade = ['activeorders']

def query(self, method, values={}):
    if method in self.public:
        url = 'https://yobit.net/api/3/'+method
        for i, k in values.iteritems():
            url += '/'+k

        req = requests.get(url)
        return = json.loads(req.text)

    elif method in self.trade:
        url = 'https://yobit.net/tapi'
        values['method'] = method
        values['nonce'] = str(int(time.time()))
        body = urlencode(values)
        signature = hmac.new(self.secret, body, hashlib.sha512).hexdigest()
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Key': self.key,
            'Sign': signature
        }

        req = requests.post(url,data=values,headers=headers)
        return json.loads(req.text)

    return false

相关问题 更多 >