Python中的API调用身份验证(工作的PHP示例) [英] API Call Authentication in Python ( Working PHP example )

查看:100
本文介绍了Python中的API调用身份验证(工作的PHP示例)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写脚本以与在线交易所进行通信.
公开"请求发送至: https://yobit.net/api/3/
交易"请求发送至: https://yobit.net/tapi/

I'm trying to write a script to communicate with an online exchange.
'Public' requests are sent to : https://yobit.net/api/3/
'Trade' requests are sent to: https://yobit.net/tapi/

我的公开要求非常有效.但是,我的私人通话"返回404错误. 我的密钥是100%正确的.
我目前生成以下URL: https://yobit.net/tapi/activeorders/ltc_btc/&apikey=MY_APIKEY_HERE&nonce=1456192036

My public requests work great. My 'private calls' however return a 404 error. My keys are 100% correct.
I currently produce the following URL: https://yobit.net/tapi/activeorders/ltc_btc/&apikey=MY_APIKEY_HERE&nonce=1456192036

我是否误解了文档?也许是错误的URL结构?

Did I missinterpret the documentation? Perhaps a false URL structure?

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

Documentation Link ---> here
Each Trade API request should pass authentication. Authentication is fulfilled by sending the following HTTP-titles: Key - API-key, example: FAF816D16FFDFBD1D46EEF5D5B10D8A2 Sign - digital signature, POST-parameters (?param0=val0 & ...& nonce=1) signed by secret key through HMAC-SHA512 Parameter nonce (1 minimum to 2147483646 maximum) in succeeding request should exceed that in the previous one. To null nonce it is necessary to generate new key.

我的脚本

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

####### PUBLIC API

####### PUBLIC 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})

#####贸易API

##### TRADE API

def getactiveorders(self, pair):
    return self.query('activeorders', {'pair': pair})

PHP中的有效示例
我相信这是PHP的有效示例,很遗憾,我无法阅读此语言.

A working example in PHP
I believe this to be a working example of PHP, unfortunately I can't read this language.

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;
}

推荐答案

我自己弄清楚了这一点,并在此过程中遇到了您的问题.交易API的YoBit文档在如何格式化请求方面有些欠缺.

I just figured this out myself and came across your question in the process. The YoBit documentation on the trade API is a bit lacking as far as how to format the request.

您要向API端点发出POST请求,并包括所有参数(包括方法本身)作为POST参数.然后,您对请求正文(POST参数)进行签名,并将其与您的公共密钥一起作为HTTP标头.

You want to make a POST request to the API endpoint and include all params including the method itself as POST params. Then, you sign the request body (POST params) and include that along with your public key as HTTP headers.

这是伪代码,用于请求TradeHistory;我不太了解Python.希望您可以解密或其他人可以将其Python化!

This is pseudocode for a request for TradeHistory; I don't quite know Python. Hopefully you can decipher or someone else can Pythonize it!

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中使用对象作为参考的方法:

Update: here's how you might do it in Python 3, using your object as reference:

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

这篇关于Python中的API调用身份验证(工作的PHP示例)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆