Python 如何使用application/x-www-form-urlencoded创建API签名

Python 如何使用application/x-www-form-urlencoded创建API签名,python,python-2.7,urlencode,Python,Python 2.7,Urlencode,第一次尝试连接到比特币交易所的私有API,我已经被困在尝试用我的代码进行测试调用 from urllib2 import Request, urlopen from urllib import urlencode import datetime api_key = "myAPIkey" api_secret = "mySercetKey" timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') values = ur

第一次尝试连接到比特币交易所的私有API,我已经被困在尝试用我的代码进行测试调用

from urllib2 import Request, urlopen
from urllib import urlencode
import datetime

api_key = "myAPIkey"
api_secret = "mySercetKey"

timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
values = urlencode({"timestamp" : timestamp})

headers = {"Content-Type": "application/x-www-form-urlencoded", "key": api_key, "sig": api_secret}
request = Request("https://www.fybsg.com/api/SGD/test", data=values, headers=headers)
response_body = urlopen(request).read()
print response_body
以下是从响应体返回的内容:

{"error":"An unexpected error occurred, its probably your fault, go read the docs."}
善良的灵魂能指出我的代码有什么问题吗?(我觉得这是大错特错)
可以找到比特币交换的API文档。(测试函数)

您传递的是无效的时间戳,在API文档中,他们提到
时间戳必须是
当前Unix时间戳
,可以这样实现:-

timestamp = datetime.datetime.now()
timestamp = int(time.mktime(timestamp.timetuple()))
或者只是:

import time
timestamp= int(time.time())

所以在更新代码之后

from urllib2 import Request, urlopen
from urllib import urlencode
import datetime
import time

api_key = "myAPIkey"
api_secret = "mySercetKey"


timestamp = datetime.datetime.now()               #.strftime('%Y-%m-%d %H:%M:%S')
timestamp = int(time.mktime(timestamp.timetuple()))
print timestamp
values = urlencode({"timestamp" : timestamp})

#sig - HMAC-SHA1 signature of POST Data with Key's Secret
from hashlib import sha1
import hmac
hashed = hmac.new(values, api_secret, sha1)
hashed_value = hashed.digest().encode("base64").rstrip('\n')

headers = {"Content-Type": "application/x-www-form-urlencoded", 
           "key": api_key, "sig":hashed_value}
request = Request("https://www.fybsg.com/api/SGD/test", data=values, headers=headers)
response_body = urlopen(request).read()
print response_body
我得到的回应是:-

{"error":"Invalid API Key or account number"}

我认为您可以通过使用有效的
私钥
账号

或使用
导入时间来修复此问题;timestamp=time.time()
@Rawing感谢您的帮助。根据文档,
sig
应该是带有密钥机密的POST数据的
HMAC-SHA1签名
,我没有看到您的代码中发生任何哈希。Tanveer,您的建议很有帮助!在输入真实的api密钥和密码后,响应体现在返回{“error”:“Invalid Signature!”}。我想我得联系交易所寻求进一步的建议。你好,罗恩,说得好。这可能就是我现在收到“无效签名”响应的原因。关于如何生成HMAC-SHA1签名,有什么推荐的链接可以阅读吗?我不是足够的密码学专家,不知道有什么好的链接。我想是谷歌/维基百科帮了我的忙。@JChan我已经试着用Key's Secret对POST数据进行
HMAC-SHA1签名,就像API文档中提到的那样。希望它能起作用。