1

我正在尝试使用来自 ios 的 binance api 进行交易。

总是给出错误["code": -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 时,我没有遇到任何签名问题。它按预期给出响应

4

1 回答 1

1

我有同样的......问题,我找到了答案。当您生成签名时,测试订单和帐户信息的输入是不同的。

帐户信息的输入:

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&timestamp=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")));
        }
    }
于 2018-08-30T20:54:13.330 回答