Anonymous
Ошибка аутентификации Mexc API при получении баланса счета, код ошибки 602
Сообщение
Anonymous » 30 сен 2024, 21:51
Я использую C# и Unity, чтобы получить баланс учетной записи пользователя в USDT, но получаю код ошибки 602. Пожалуйста, помогите. мой код приведен ниже. Я использовал конечную точку из будущей документации API
Код: Выделить всё
`public class InteractWithAccount : MonoBehaviour
{
private string baseUrl = "https://contract.mexc.com";
private string apiKey = "my key";
private string apiSecret = "my skey";
private HttpClient httpClient;
private async void Start() // code starts here-------------------
{
httpClient = new HttpClient();
string response = await SendSignedAsync(baseUrl + "/api/v1/private/account/asset/USDT", HttpMethod.Get, new Dictionary {
{"currency", "USDT"}
});
Debug.Log(response);
}
public async Task SendSignedAsync(string requestUri, HttpMethod httpMethod, Dictionary query = null, object content = null)
{
string querryString = "";
try
{
querryString = ApiUtility.GetRequestParamString(query);
long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
Debug.Log($"{querryString}");
SignVo sv = new SignVo();
sv.ReqTime = now.ToString();
sv.SecretKey = apiSecret;
sv.AccessKey = apiKey;
sv.RequestParam = querryString;
string signature = ApiUtility.Sign(sv);
return await SendAsync(requestUri, httpMethod, now.ToString(), signature);
}
catch (Exception ex)
{
Debug.LogException(ex);
return null;
}
}
private async Task SendAsync(string requestUri, HttpMethod httpMethod, string timeS, string sign)
{
try
{
using (var request = new HttpRequestMessage(httpMethod, requestUri))
{
request.Headers.Add("ApiKey", apiKey);
request.Headers.Add("Signature", sign);
request.Headers.Add("Request-Time", timeS);
HttpResponseMessage response = await httpClient.SendAsync(request);
Debug.Log(response.Content);
Debug.Log(response.RequestMessage);
Debug.Log(response.StatusCode);
using (HttpContent responseContent = response.Content)
{
string jsonString = await responseContent.ReadAsStringAsync();
return jsonString;
}
}
}
catch (Exception ex)
{
Debug.LogError("Error in SendAsync: " + ex.Message);
return null;
}
}
}
public static class ApiUtility
{
public static string GetRequestParamString(Dictionary param)
{
if (param == null || param.Count == 0)
return "";
StringBuilder sb = new StringBuilder(1024);
SortedDictionary sortedMap = new SortedDictionary(param);
foreach (var entry in sortedMap)
{
string key = entry.Key;
string value = string.IsNullOrEmpty(entry.Value) ? "" : entry.Value;
sb.Append(key).Append('=').Append(UrlEncode(value)).Append('&');
}
if (sb.Length > 0)
sb.Remove(sb.Length - 1, 1);
return sb.ToString();
}
public static string UrlEncode(string s)
{
if (string.IsNullOrEmpty(s))
return "";
return WebUtility.UrlEncode(s).Replace("+", "%20");
}
public static string Sign(SignVo signVo)
{
if (string.IsNullOrEmpty(signVo.RequestParam))
signVo.RequestParam = "";
string str = signVo.AccessKey + signVo.ReqTime + signVo.RequestParam;
return ActualSignature(str, signVo.SecretKey);
}
public static string ActualSignature(string inputStr, string key)
{
using (var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key)))
{
byte[] inputBytes = Encoding.UTF8.GetBytes(inputStr);
byte[] hash = hmac.ComputeHash(inputBytes);
return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
}
}
}
public class SignVo
{
public string ReqTime { get; set; }
public string AccessKey { get; set; }
public string SecretKey { get; set; }
public string RequestParam { get; set; }
}`
Я пробовал все методы из разных тем и документации, но ничего не помогло. возможно, проблема в методе подписи или заголовках
Подробнее здесь:
https://stackoverflow.com/questions/790 ... r-code-602
1727722262
Anonymous
Я использую C# и Unity, чтобы получить баланс учетной записи пользователя в USDT, но получаю код ошибки 602. Пожалуйста, помогите. мой код приведен ниже. Я использовал конечную точку из будущей документации API [code]`public class InteractWithAccount : MonoBehaviour { private string baseUrl = "https://contract.mexc.com"; private string apiKey = "my key"; private string apiSecret = "my skey"; private HttpClient httpClient; private async void Start() // code starts here------------------- { httpClient = new HttpClient(); string response = await SendSignedAsync(baseUrl + "/api/v1/private/account/asset/USDT", HttpMethod.Get, new Dictionary { {"currency", "USDT"} }); Debug.Log(response); } public async Task SendSignedAsync(string requestUri, HttpMethod httpMethod, Dictionary query = null, object content = null) { string querryString = ""; try { querryString = ApiUtility.GetRequestParamString(query); long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); Debug.Log($"{querryString}"); SignVo sv = new SignVo(); sv.ReqTime = now.ToString(); sv.SecretKey = apiSecret; sv.AccessKey = apiKey; sv.RequestParam = querryString; string signature = ApiUtility.Sign(sv); return await SendAsync(requestUri, httpMethod, now.ToString(), signature); } catch (Exception ex) { Debug.LogException(ex); return null; } } private async Task SendAsync(string requestUri, HttpMethod httpMethod, string timeS, string sign) { try { using (var request = new HttpRequestMessage(httpMethod, requestUri)) { request.Headers.Add("ApiKey", apiKey); request.Headers.Add("Signature", sign); request.Headers.Add("Request-Time", timeS); HttpResponseMessage response = await httpClient.SendAsync(request); Debug.Log(response.Content); Debug.Log(response.RequestMessage); Debug.Log(response.StatusCode); using (HttpContent responseContent = response.Content) { string jsonString = await responseContent.ReadAsStringAsync(); return jsonString; } } } catch (Exception ex) { Debug.LogError("Error in SendAsync: " + ex.Message); return null; } } } public static class ApiUtility { public static string GetRequestParamString(Dictionary param) { if (param == null || param.Count == 0) return ""; StringBuilder sb = new StringBuilder(1024); SortedDictionary sortedMap = new SortedDictionary(param); foreach (var entry in sortedMap) { string key = entry.Key; string value = string.IsNullOrEmpty(entry.Value) ? "" : entry.Value; sb.Append(key).Append('=').Append(UrlEncode(value)).Append('&'); } if (sb.Length > 0) sb.Remove(sb.Length - 1, 1); return sb.ToString(); } public static string UrlEncode(string s) { if (string.IsNullOrEmpty(s)) return ""; return WebUtility.UrlEncode(s).Replace("+", "%20"); } public static string Sign(SignVo signVo) { if (string.IsNullOrEmpty(signVo.RequestParam)) signVo.RequestParam = ""; string str = signVo.AccessKey + signVo.ReqTime + signVo.RequestParam; return ActualSignature(str, signVo.SecretKey); } public static string ActualSignature(string inputStr, string key) { using (var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key))) { byte[] inputBytes = Encoding.UTF8.GetBytes(inputStr); byte[] hash = hmac.ComputeHash(inputBytes); return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant(); } } } public class SignVo { public string ReqTime { get; set; } public string AccessKey { get; set; } public string SecretKey { get; set; } public string RequestParam { get; set; } }` [/code] Я пробовал все методы из разных тем и документации, но ничего не помогло. возможно, проблема в методе подписи или заголовках Подробнее здесь: [url]https://stackoverflow.com/questions/79040702/mexc-api-authentication-fail-while-retriving-account-balance-error-code-602[/url]