首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Python3中对MtGox WebSocket API的验证调用

在Python3中对MtGox WebSocket API的验证调用
EN

Stack Overflow用户
提问于 2013-09-01 10:23:33
回答 1查看 597关注 0票数 1

我正在尝试使用MtGox.com WebSocket API进行身份验证,并在很长一段时间后设法完成JSON所需的“调用”属性。然而,我意识到我正在使用Python 2来运行我的代码示例,API最终将在Python 3中实现的应用程序是用Python 3编写的。当我试图使它在Python 3中工作时,我遇到了一些问题,尽管经过多次尝试,我还是无法解决。

我也尝试过2to3,但是它似乎没有针对这类问题的内置修复程序。

通过身份验证的API调用的API规范可以在这里找到:commands

下面是用于生成JSON调用的Python2脚本,然后通过我为Chrome找到的WebSocket控制台扩展来运行该脚本。

代码语言:javascript
复制
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(“十六进制”)有关,我有一些其他的错误,但不幸的是,由于我尝试了大量不同的方法,所以我没有跟踪它们。我还查看了其他语言中相同功能的代码,但找不到与Python 3问题有关的任何线索。在Python 3中,对字节和字符串的编码和解码所做的更改似乎有很大的关系。

提前谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-09-06 19:14:43

终于解决了!

下面是send_signed_call函数的工作版本,请欣赏:

代码语言:javascript
复制
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"
    })

你们根本不知道我现在有多幸福!

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18557453

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档