Api

BitFinex API 呼叫返回 400 錯誤請求

  • January 30, 2015

嘗試使用 BitFinex 進行身份驗證才能正常工作。此處的文件:https ://www.bitfinex.com/pages/api

假設客戶想要發出 POST 請求

<https://api.bitfinex.com/v1/order/new>

有效載荷為{ "request":"/v1/order/new", "nonce": "1234", "option1": ... }

提供的隨機數必須嚴格增加。

要驗證請求,請使用以下命令:

payload = parameters-dictionary -&gt; JSON encode -&gt; base64 
signature = HMAC-SHA384(payload, api-secret) as hexadecimal 
send (api-key, payload, signature) 

這些被編碼為 HTTP 標頭,名為:X-BFX-APIKEY X-BFX-PAYLOAD X-BFX-SIGNATURE

這是 c# 程式碼,它遵循上面的範例,但會生成 HTTP 400 錯誤請求。任何想法如何解決?

       long nonce = DateTime.Now.ToUnixTimestampMS(); //returns a strictly increasing timestamp based number e.g. 1402207693893

       string path = "https://api.bitfinex.com/v1/balances";
       string paramDict = "{\"request\": \"/v1/balances\",\"nonce\": \"" + nonce + "\"}"; //ie. {"request": "/v1/balances","nonce": "1402207693893"}
       string payload = Convert.ToBase64String(Encoding.UTF8.GetBytes(paramDict));

       //API Sign
       HMACSHA384 hmac = new HMACSHA384(Encoding.UTF8.GetBytes(APISECRET));           //My API SECRET
       byte[] hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(payload));
       string hexHash = BitConverter.ToString(hash).Replace("-", "");

       NameValueCollection headers = new NameValueCollection();
       headers.Add("X-BFX-APIKEY", APIKEY);                                            //My API KEY
       headers.Add("X-BFX-PAYLOAD", payload);
       headers.Add("X-BFX-SIGNATURE", hexHash);

       //POST data
       try
       {
           //create post request
           HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(path);
           request.KeepAlive = true;
           request.Method = "POST";

           //add headers
           request.Headers.Add(headers);

           //write out payload
           byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(paramDict);
           request.ContentLength = byteArray.Length;
           using (var writer = request.GetRequestStream()){writer.Write(byteArray, 0, byteArray.Length);}

           //read reply
           using (var response = request.GetResponse() as System.Net.HttpWebResponse)
           {
               using (var reader = new System.IO.StreamReader(response.GetResponseStream()))
               {
                   //get reply (JSON)
                   string responseContent = reader.ReadToEnd();
               }
           }
       }
       catch (Exception e)
       {
           //always throws an exception here
           Debug.WriteLine(e.Message);
       }

終於找到了解決方法:hexhash 必須是小寫:

string hexHash = BitConverter.ToString(hash).Replace("-", "").ToLower();

引用自:https://bitcoin.stackexchange.com/questions/25835