我正在尝试使用ios的binance api进行交易。
始终提供错误 ["代码":-1022," msg":此请求的签名无效。]
代码:
public override func requestFor(api: APIType) -> NSMutableURLRequest {
let mutableURLRequest = api.mutableRequest
if let key = key, let secret = secret, api.authenticated {
var postData = api.postData
//postData["symbol"] = "BNBBTC"
//postData["timestamp"] = "\(Int(Date().timeIntervalSince1970 * 1000))"
postData["symbol"] = "BNBBTC"
postData["side"] = "SELL"
postData["type"] = "MARKET"
postData["recvWindow"] = "5000"
postData["quantity"] = "0.1"
postData["timestamp"] = "\(Int(Date().timeIntervalSince1970 * 1000))"
if let hmac_sha = try? HMAC(key: secret, variant: .sha256).authenticate(Array(postData.queryString.utf8)) {
let signature = Data(bytes: hmac_sha).toHexString()
postData["signature"] = signature
}
var postDataString = ""
if let data = postData.data, let string = data.string, postData.count > 0 {
postDataString = string
if case .GET = api.httpMethod {
mutableURLRequest.httpBody = data
} else if case .POST = api.httpMethod {
var urlString = mutableURLRequest.url?.absoluteString
urlString?.append("?")
urlString?.append(postData.queryString)
let url = URL(string: urlString!)
mutableURLRequest.url = url
}
api.print("Request Data: \(postDataString)", content: .response)
}
mutableURLRequest.setValue(key, forHTTPHeaderField: "X-MBX-APIKEY")
}
return mutableURLRequest
}
编辑:在使用帐户API时,我没有遇到任何签名问题。它按预期给出了响应
答案 0 :(得分:0)
我有同样的问题,我找到了答案。生成签名时,测试订单和帐户信息的输入是不同的。
输入帐户信息:
string input = "timestamp=1535623795177";
string apiSecret = "YOUR API SECRET"
测试极限订单的输入:
string input = "symbol=ETHBTC&side=BUY&recvWindow=6500&type=LIMIT&timeInForce=GTC&quantity=100&price=0.1×tamp=1535623795177";
string apiSecret = "YOUR API SECRET"
并生成签名工作示例(C#):
private string GenerateSignature(string input, string apiSecret)
{
var encoding = new UTF8Encoding();
byte[] keyByte = encoding.GetBytes(apiSecret);
byte[] messageBytes = encoding.GetBytes(input);
using (var hmacsha256 = new HMACSHA256(keyByte))
{
byte[] hashMessage = hmacsha256.ComputeHash(messageBytes);
return String.Concat(hashMessage.Select(b => b.ToString("x2")));
}
}