Trying to get authentication with BitFinex to work. Docs here: https://www.bitfinex.com/pages/api
Say the client wants to make a request to POST
https://api.bitfinex.com/v1/order/new
With a payload of
{ "request":"/v1/order/new", "nonce": "1234", "option1": ... }
The nonce provided must be strictly increasing.
To authenticate a request, use the following:
payload = parameters-dictionary -> JSON encode -> base64 signature = HMAC-SHA384(payload, api-secret) as hexadecimal send (api-key, payload, signature)
These are encoded as HTTP headers named: X-BFX-APIKEY X-BFX-PAYLOAD X-BFX-SIGNATURE
Here is the c# code, which follows the above example, but generates a HTTP 400 Bad Request. Any ideas how to fix?
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);
}