Coinbase/GDAX API(401)错误与C#访问尝试
我有两个功能,访问尝试和HMAC签名。它运行并返回一个未经授权的错误(401),但除此之外,我觉得我的代码比它需要的要长,或者不知何故是多余的,指出这将对我非常有帮助,提前感谢Coinbase/GDAX API(401)错误与C#访问尝试,c#,hmac,coinbase-api,C#,Hmac,Coinbase Api,我有两个功能,访问尝试和HMAC签名。它运行并返回一个未经授权的错误(401),但除此之外,我觉得我的代码比它需要的要长,或者不知何故是多余的,指出这将对我非常有帮助,提前感谢 void AccessAttempt(){ var message = Epoch.ToString () + "GET" + "/v2/payment-methods"; const string WEBSERVICE_URL = "https://api.coinbase.co
void AccessAttempt(){
var message = Epoch.ToString () + "GET" + "/v2/payment-methods";
const string WEBSERVICE_URL = "https://api.coinbase.com/v2/payment-methods";
try
{
var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
if (webRequest != null)
{
webRequest.Method = "POST";
webRequest.ContentType = "application/json";
webRequest.Headers.Add("CB-ACCESS-SIGN", genHMAC(message));
webRequest.Headers.Add("CB-ACCESS-TIMESTAMP", Epoch.ToString());
webRequest.Headers.Add("CB-ACCESS-KEY", _apiKey);
webRequest.Headers.Add("CB-VERSION",_apiVersion);
using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
{
var jsonResponse = sr.ReadToEnd();
OutputText.text = jsonResponse.ToString();
}
}
}
}
catch (Exception ex)
{
OutputText.text = ex.ToString();
}
}
下面是在上面的主函数中调用的HMAC签名函数:
private string genHMAC(string message)
{
byte [] APISecret_Bytes = System.Text.Encoding.UTF8.GetBytes(_apiSecret);
HMACSHA256 hmac = new HMACSHA256(APISecret_Bytes);
hmac.Initialize ();
byte [] MESSAGE_Bytes = System.Text.Encoding.UTF8.GetBytes(message);
var rawHmac = hmac.ComputeHash(MESSAGE_Bytes);
string rawHmacString = string.Empty;
for (int i=0; i<rawHmac.Length; i++)
{
rawHmacString += rawHmac[i];
}
string hexString = string.Empty;
for (int i=0; i<rawHmac.Length; i++)
{
hexString += rawHmac[i].ToString("X2");
}
return hexString;
}
私有字符串genHMAC(字符串消息)
{
byte[]APISecret\u Bytes=System.Text.Encoding.UTF8.GetBytes(\u APISecret);
HMACSHA256 hmac=新的HMACSHA256(APISecret_字节);
初始化();
byte[]MESSAGE_Bytes=System.Text.Encoding.UTF8.GetBytes(MESSAGE);
var rawHmac=hmac.ComputeHash(消息字节);
string rawHmacString=string.Empty;
对于(inti=0;i这是一个非常老的问题,但如果您还没有答案,那么您的请求似乎有一些地方出错-下面是一些适合我的代码
public class CoinbaseV2
{
private string APIKey;
private string Secret;
private const string URL_BASE = "https://api.coinbase.com";
private const string URL_BASE_VERSION = URL_BASE + "/v2/";
private const String GET = "GET";
private const String POST = "POST";
private const String PUT = "PUT";
private const String DELETE = "DELETE";
public CoinbaseV2(string inAPIKey, string inSecret)
{
APIKey = inAPIKey;
Secret = inSecret;
}
public string GetUser()
{
return JsonRequest(URL_BASE_VERSION + "user", GET);
}
public string GetUserAccounts()
{
return JsonRequest(URL_BASE_VERSION + "accounts", GET);
}
private string JsonRequest(string url, string method)
{
// take care of any spaces in params
url = Uri.EscapeUriString(url);
string returnData = String.Empty;
var webRequest = HttpWebRequest.Create(url) as HttpWebRequest;
if (webRequest != null)
{
webRequest.Method = method;
webRequest.ContentType = "application/json";
string timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(CultureInfo.CurrentCulture);
string body = "";
string sigurl = url.Replace(URL_BASE,"");
string signature = GenerateSignature(timestamp,method,sigurl,body,Secret);
var whc = new WebHeaderCollection();
whc.Add("CB-ACCESS-SIGN", signature);
whc.Add("CB-ACCESS-TIMESTAMP", timestamp);
whc.Add("CB-ACCESS-KEY", APIKey);
whc.Add("CB-VERSION", "2017-08-07");
webRequest.Headers = whc;
using (WebResponse response = webRequest.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream);
returnData = reader.ReadToEnd();
}
}
}
return returnData;
}
//https://github.com/bchavez/Coinbase
public static string GenerateSignature(string timestamp, string method, string url, string body, string appSecret)
{
return GetHMACInHex(appSecret, timestamp + method + url + body).ToLower();
}
internal static string GetHMACInHex(string key, string data)
{
var hmacKey = Encoding.UTF8.GetBytes(key);
var dataBytes = Encoding.UTF8.GetBytes(data);
using (var hmac = new HMACSHA256(hmacKey))
{
var sig = hmac.ComputeHash(dataBytes);
return ByteToHexString(sig);
}
}
//https://stackoverflow.com/questions/311165/how-do-you-convert-a-byte-array-to-a-hexadecimal-string-and-vice-versa/14333437#14333437
static string ByteToHexString(byte[] bytes)
{
char[] c = new char[bytes.Length * 2];
int b;
for (int i = 0; i < bytes.Length; i++)
{
b = bytes[i] >> 4;
c[i * 2] = (char)(87 + b + (((b - 10) >> 31) & -39));
b = bytes[i] & 0xF;
c[i * 2 + 1] = (char)(87 + b + (((b - 10) >> 31) & -39));
}
return new string(c);
}
}
公共类CoinbaseV2
{
私钥;
私人字符串秘密;
私有常量字符串URL_BASE=”https://api.coinbase.com";
私有常量字符串URL_BASE_VERSION=URL_BASE+“/v2/”;
私有常量字符串GET=“GET”;
private const String POST=“POST”;
private const String PUT=“PUT”;
private const String DELETE=“DELETE”;
public CoinbaseV2(字符串inAPIKey,字符串unsecret)
{
APIKey=inAPIKey;
秘密=不安全;
}
公共字符串GetUser()
{
返回JsonRequest(URL\u BASE\u VERSION+“user”,GET);
}
公共字符串GetUserAccounts()
{
返回JsonRequest(URL\u BASE\u VERSION+“accounts”,GET);
}
私有字符串JsonRequest(字符串url、字符串方法)
{
//注意params中的所有空格
url=Uri.EscapeUriString(url);
string returnData=string.Empty;
var webRequest=HttpWebRequest.Create(url)为HttpWebRequest;
if(webRequest!=null)
{
webRequest.Method=Method;
webRequest.ContentType=“应用程序/json”;
字符串timestamp=DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(CultureInfo.CurrentCulture);
字符串体=”;
字符串sigurl=url.Replace(url\u BASE,“”);
字符串签名=GenerateSignature(时间戳、方法、sigurl、正文、机密);
var whc=新WebHeaderCollection();
whc.添加(“CB-ACCESS-SIGN”,签名);
whc.添加(“CB-ACCESS-TIMESTAMP”,时间戳);
whc.添加(“CB-ACCESS-KEY”,APIKey);
whc.添加(“CB-VERSION”、“2017-08-07”);
webRequest.Headers=whc;
使用(WebResponse=webRequest.GetResponse())
{
使用(Stream=response.GetResponseStream())
{
StreamReader=新的StreamReader(流);
returnData=reader.ReadToEnd();
}
}
}
返回数据;
}
//https://github.com/bchavez/Coinbase
公共静态字符串生成器签名(字符串时间戳、字符串方法、字符串url、字符串正文、字符串appSecret)
{
返回gethmacinex(appSecret,timestamp+method+url+body).ToLower();
}
内部静态字符串gethmacinex(字符串键、字符串数据)
{
var hmacKey=Encoding.UTF8.GetBytes(键);
var-dataBytes=Encoding.UTF8.GetBytes(数据);
使用(var hmac=新的HMACSHA256(hmacKey))
{
var sig=hmac.ComputeHash(数据字节);
返回ByteToHexString(sig);
}
}
//https://stackoverflow.com/questions/311165/how-do-you-convert-a-byte-array-to-a-hexadecimal-string-and-vice-versa/14333437#14333437
静态字符串ByteToHexString(字节[]字节)
{
char[]c=新字符[bytes.Length*2];
int b;
for(int i=0;i>4;
c[i*2]=(char)(87+b+((b-10>>31)和-39));
b=字节[i]&0xF;
c[i*2+1]=(char)(87+b+((b-10>>31)和-39));
}
返回新字符串(c);
}
}