簡體   English   中英

在Python 3中對MtGox WebSocket API的經過身份驗證的調用

[英]Authenticated call to MtGox WebSocket API in Python 3

我正在嘗試使用MtGox.com WebSocket API進行身份驗證,並在很長一段時間后設法完成了JSON數據所需的“調用”屬性。 但是,我意識到我正在使用Python 2運行我的代碼示例,並且最終要在其中實現API的應用程序是用Python 3編寫的。當我試圖使其在Python 3中運行時,我遇到了兩個問題經過數次長時間嘗試后仍無法解決。

我也嘗試了2to3 ,但似乎沒有針對這些問題的內置修復程序。

可在以下位置找到經過身份驗證的API調用的API規范: https : //en.bitcoin.it/wiki/MtGox/API/Streaming#Authenticated_commands

這是我用來生成JSON調用的有效Python 2腳本,然后通過為Chrome找到的WebSocket控制台擴展運行該腳本。

import hashlib
import time
import hmac
import json
import base64
import binascii

apikey = ""
apisecret = ""

def _nonce():
    """produce a unique nonce that is guaranteed to be ever increasing"""
    microtime = int(time.time() * 1E6)
    return microtime

def _reqid(nonce):
    return hashlib.md5(str(nonce)).hexdigest()

def send_signed_call(api_endpoint, params):
    nonce = _nonce()
    reqid = _reqid(nonce)
    call = json.dumps({
        "id"       : reqid,
        "nonce"    : nonce,
        "call"     : api_endpoint,
        "params"   : params,
    })

    sign = hmac.new(base64.b64decode(apisecret), call, hashlib.sha512).digest()
    signedcall = apikey.replace("-", "").decode("hex") + sign + call

    return json.dumps({
        "op"      : "call",
        "call"    : base64.b64encode(signedcall),
        "id"      : reqid,
        "context" : "mtgox.com"
    })

msg = send_signed_call("private/info", {})
print(msg)

我遇到的一些錯誤與不再存在的String.decode(“ hex”)有關,我還有其他一些錯誤,但是不幸的是,由於嘗試了許多不同的方法,我沒有跟蹤所有錯誤。 我還查看了其他語言中具有相同功能的代碼示例,但找不到與Python 3問題有關的任何線索。 似乎與Python 3中對字節和字符串的編碼和解碼所做的更改有關。

在此先多謝!

終於解決了!

這是send_signed_call函數的工作版本,請欣賞:

def send_signed_call(api_endpoint, params):
    nonce = _nonce()
    reqid = _reqid(nonce)
    call = json.dumps({
        "id"       : reqid,
        "nonce"    : nonce,
        "call"     : api_endpoint,
        "params"   : params,
    })
    callByte = bytes(call, "utf-8")

    sign = hmac.new(base64.b64decode(api_secret), callByte, hashlib.sha512).digest()
    skey = bytes.fromhex(api_key.replace("-",""))

    signedcall = skey + sign + callByte
    return json.dumps({
        "op"      : "call",
        "call"    : base64.b64encode(signedcall).decode("utf-8"),
        "id"      : reqid,
        "context" : "mtgox.com"
    })

你們不知道我現在熊貓有多幸福!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM