2017-12-15 1 views
4

많은 코딩 경험이 있지만 파이썬은 새로운 영역입니다.GDAX/Coinbase API 인증 프로세스 : 해시 처리 전에 유니 코드 개체를 인코딩해야합니다.

CoinbaseExchangeAuth 클래스를 사용하여 GDAX API의 개인 엔드 포인트에 액세스합니다. 나는

api_url = 'https://public.sandbox.gdax.com/' 
auth = CoinbaseExchangeAuth(API_KEY, API_SECRET, API_PASS) 

(나는 정확하게 API 키, 비밀 정의주의와 코드 줄 전에 제대로 통과 - 샌드 박스 용) ... 몇 가지 간단한 코드를 작성

가 그럼 난 쓰기 :

r = requests.get(api_url + 'accounts', auth=auth) 

이 오류 코드를 실행하고 얻을 :

File "a:\PythonCryptoBot\Bot1.0\CoinbaseExhangeAuth.py", line 16, in call signature = hmac.new(hmackey, message, hashlib.sha256) File "C:\Users\Dylan\AppData\Local\Programs\Python\Python35-32\lib\hmac.py", line 144, in new return HMAC(key, msg, digestmod) File "C:\Users\Dylan\AppData\Local\Programs\Python\Python35-32\lib\hmac.py", line 84, in __init_ self.update(msg) File "C:\Users\Dylan\AppData\Local\Programs\Python\Python35-32\lib\hmac.py", line 93, in update self.inner.update(msg) TypeError: Unicode-objects must be encoded before hashing

이 또한 내가 AP에 시도 있습니다 I_KEY.encode ('utf-8')이며 다른 사람들과 동일합니다. - 아무것도하지 않는 것 같습니다.

답변

3

사용중인 코드는 Python2 용으로 작성되었으므로 그대로 실행될 수는 없습니다. Python3과 호환되도록 일부 부분을 수정했습니다.

원래 코드 :

import json, hmac, hashlib, time, requests, base64 
from requests.auth import AuthBase 

# Create custom authentication for Exchange 
class CoinbaseExchangeAuth(AuthBase): 
    def __init__(self, api_key, secret_key, passphrase): 
     self.api_key = api_key 
     self.secret_key = secret_key 
     self.passphrase = passphrase 

    def __call__(self, request): 
     timestamp = str(time.time()) 
     message = timestamp + request.method + request.path_url + (request.body or '') 
     hmac_key = base64.b64decode(self.secret_key) 
     signature = hmac.new(hmac_key, message, hashlib.sha256) 
     signature_b64 = signature.digest().encode('base64').rstrip('\n') 

     request.headers.update({ 
      'CB-ACCESS-SIGN': signature_b64, 
      'CB-ACCESS-TIMESTAMP': timestamp, 
      'CB-ACCESS-KEY': self.api_key, 
      'CB-ACCESS-PASSPHRASE': self.passphrase, 
      'Content-Type': 'application/json' 
     }) 
     return request 

api_url = 'https://api.gdax.com/' 
auth = CoinbaseExchangeAuth(API_KEY, API_SECRET, API_PASS) 

# Get accounts 
r = requests.get(api_url + 'accounts', auth=auth) 
print r.json() 
# [{"id": "a1b2c3d4", "balance":... 

# Place an order 
order = { 
    'size': 1.0, 
    'price': 1.0, 
    'side': 'buy', 
    'product_id': 'BTC-USD', 
} 
r = requests.post(api_url + 'orders', json=order, auth=auth) 
print r.json() 

수정 된 코드 : 그것은을 위해 내가 단지 원래의 코드를 "번역"한

import json, hmac, hashlib, time, requests, base64 
from requests.auth import AuthBase 

# Create custom authentication for Exchange 
class CoinbaseExchangeAuth(AuthBase): 
    def __init__(self, api_key, secret_key, passphrase): 
     self.api_key = api_key 
     self.secret_key = secret_key 
     self.passphrase = passphrase 

    def __call__(self, request): 
     timestamp = str(time.time()) 
     message = timestamp + request.method + request.path_url + (request.body or b'').decode() 
     hmac_key = base64.b64decode(self.secret_key) 
     signature = hmac.new(hmac_key, message.encode(), hashlib.sha256) 
     signature_b64 = base64.b64encode(signature.digest()).decode() 

     request.headers.update({ 
      'CB-ACCESS-SIGN': signature_b64, 
      'CB-ACCESS-TIMESTAMP': timestamp, 
      'CB-ACCESS-KEY': self.api_key, 
      'CB-ACCESS-PASSPHRASE': self.passphrase, 
      'Content-Type': 'application/json' 
     }) 
     return request 

api_url = 'https://api.gdax.com/' 
auth = CoinbaseExchangeAuth(APIKEY, API_SECRET, API_PASS) 

# Get accounts 
r = requests.get(api_url + 'accounts', auth=auth) 
print(r.json()) 
# [{"id": "a1b2c3d4", "balance":... 

# Place an order 
order = { 
    'size': 1.0, 
    'price': 1.0, 
    'side': 'buy', 
    'product_id': 'BTC-USD', 
} 
r = requests.post(api_url + 'orders', json=order, auth=auth) 
print(r.json()) 

참고, 내가 보장 할 수 없습니다 기능 또는 보안.

+0

그래서 지금은 확실히 작동하고 있습니다. 고맙습니다. 하지만 지금은이 오류가 발생합니다. 역 추적 (마지막으로 가장 최근 통화) : 파일 "A : \ PythonCryptoBot \ Bot1.0 CoinbaseExhangeAuth.py \"를 의미 –

+0

좋아, 라인 (88), 인쇄에서 (r.json()), 즉'.json ()'응답을 구문 분석하지 못했습니다. 'r.text'와'r.status_code'를 출력 할 수 있습니까? –

+0

print (r.status_code) 나에게 200 (작동)! –

관련 문제