2017-10-15 170 views
0

好的,所以我覺得我在這個聯盟之外有點小。 我試圖以方便自定義HTTP標頭是什麼在這裏要注意:Python3:自定義加密標題URLLIB - KrakenAPI

API-Key = API key 
    API-Sign = Message signature using HMAC-SHA512 of (URI path + SHA256(nonce + POST data)) and base64 decoded secret API key 

https://www.kraken.com/help/api

我想單獨制定的urllib如果在所有可能的。

下面是許多嘗試得到它編碼等所要求的一個:

import os 
    import sys 
    import time 
    import datetime 
    import urllib.request 
    import urllib.parse 
    import json 
    import hashlib 
    import hmac 
    import base64 

    APIKey = 'ThisKey' 
    secret = 'ThisSecret' 

    data = {} 

    data['nonce'] = int(time.time()*1000) 

    data['asset'] = 'ZUSD' 

    uripath = '/0/private/TradeBalance' 

    postdata = urllib.parse.urlencode(data) 

    encoded = (str(data['nonce']) + postdata).encode() 
    message = uripath.encode() + hashlib.sha256(encoded).digest() 

    signature = hmac.new(base64.b64decode(secret), 
        message, hashlib.sha512) 
    sigdigest = base64.b64encode(signature.digest()) 

    #this is purely for checking how things are coming along. 
    print(sigdigest.decode()) 

    headers = { 
    'API-Key': APIKey, 
    'API-Sign': sigdigest.decode() 
    } 

以上可以工作得很好,在那裏我現在掙扎適當它讓到現場。 這是我最近一次嘗試:

myBalance = urllib.urlopen('https://api.kraken.com/0/private/TradeBalance', urllib.parse.urlencode({'asset': 'ZUSD'}).encode("utf-8"), headers) 

任何幫助是極大的讚賞。 謝謝!

+0

信貸,由於順便說一句,這部分代碼是由拉:https://開頭的github .com/veox/python3-krakenex 但是由於它使用了請求,我無法在我的機器上運行它。 – Samuel

回答

0

urlopen不支持添加標題,所以你需要創建一個Request對象,並把它傳遞給urlopen

url = 'https://api.kraken.com/0/private/TradeBalance' 
body = urllib.parse.urlencode({'asset': 'ZUSD'}).encode("utf-8") 
headers = { 
    'API-Key': APIKey, 
    'API-Sign': sigdigest.decode() 
} 

request = urllib.request.Request(url, data=body, headers=headers) 
response = urllib.request.urlopen(request) 
+0

感謝朋友!現在它回來了「{'錯誤':['EAPI:Invalid key']}」,這讓我想到了我編碼錯誤的地方。 – Samuel

+0

得到它的工作,感謝您的幫助! – Samuel