我正在玩实现一个 API。通常这很简单,但这给我带来了问题。但是,我很确定问题出在我身上,而不是 API。
此特定 API 的 URL:
我想对“帐户余额”进行 POST 调用。目前我得到以下答案:
{"error": "Missing key, signature and nonce parameters"}
我尝试使用以下代码来做到这一点:
var path = "https://www.bitstamp.net/api/user_transactions";
var nonce = GetNonce();
var signature = GetSignature(nonce);
using (WebClient client = new WebClient())
{
byte[] response = client.UploadValues(path, new NameValueCollection()
{
{ "key", Constants.ThirdParty.BitStamp.ApiKey },
{ "signature", signature },
{ "nonce", nonce},
});
var str = System.Text.Encoding.Default.GetString(response);
}
return 0.0m;
这是我的两个辅助函数:
private string GetSignature(int nonce)
{
string msg = string.Format("{0}{1}{2}", nonce,
Constants.ThirdParty.BitStamp.ClientId,
Constants.ThirdParty.BitStamp.ApiKey);
return HelperFunctions.sign(Constants.ThirdParty.BitStamp.ApiSecret, msg);
}
public static int GetNonce()
{
return (int) (DateTime.Now - new DateTime(1970, 1, 1)).TotalSeconds;
}
我的加密签名功能是这个:
public static String sign(String key, String stringToSign)
{
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
byte[] keyByte = encoding.GetBytes(key);
HMACSHA256 hmacsha256 = new HMACSHA256(keyByte);
return Convert.ToBase64String(hmacsha256.ComputeHash(encoding.GetBytes(stringToSign)));
}
知道为什么我会收到“丢失的钥匙”错误吗?有什么明显的我做错了吗(可能是:))?
编辑:
Fiddler 告诉我我发布了以下数据:
key=mykeymykey&signature=PwhdkSek6GP%2br%2bdd%2bS5aU1MryXgrfOD4fLH05D7%2fRLQ%3d&nonce=1382299103%2c21055
编辑#2:
更新了生成签名的代码:
private string GetSignature(int nonce)
{
string msg = string.Format("{0}{1}{2}", nonce,
Constants.ThirdParty.BitStamp.ClientId,
Constants.ThirdParty.BitStamp.ApiKey);
return HelperFunctions.ByteArrayToString(HelperFunctions.SignHMACSHA256(
Constants.ThirdParty.BitStamp.ApiSecret, msg)).ToUpper();
}
public static byte[] SignHMACSHA256(String key, byte[] data)
{
HMACSHA256 hashMaker = new HMACSHA256(Encoding.ASCII.GetBytes(key));
return hashMaker.ComputeHash(data);
}
public static byte[] StrinToByteArray(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
public static string ByteArrayToString(byte[] ba)
{
return BitConverter.ToString(ba).Replace("-", "");
}