如何使用Dart签署Binance HTTP请求

时间:2019-03-22 23:39:33

标签: android ios api dart flutter

当我尝试发出请求时,出现以下错误消息:

code: -1100, 
msg: Illegal characters found in parameter 'signature'; legal range is '^[A-Fa-f0-9]{64}$'

链接到币安API:https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md

正在向https://api.binance.com/api/v3/account发送请求。查询参数只是时间戳,因为它是必需的。

我100%确信我在邮件签名方式上有问题。我确定是因为它包含“ +-/ _ =”之类的字符,显然这是不允许的。该错误一定在代码的中间部分,但我似乎无法弄清楚。

我已经浏览了以下站点:

String baseUrl = 'https://api.binance.com/api/v3/account';
int timeStamp = DateTime.now().millisecondsSinceEpoch;
String queryParams = 'timestamp=' + timeStamp.toString();
String secret = 'SECRET_KEY_HERE';

List<int> messageBytes = utf8.encode(queryParams);
List<int> key = base64.decode(secret);
Hmac hmac = new Hmac(sha256, key);
Digest digest = hmac.convert(messageBytes);
String signature = base64.encode(digest.bytes);
String url = baseUrl + "?" + "signature=" + signature + "&" + queryParams;

var response = await http.get(
    url,
    headers: {
      "Accept": "application/json",
      "HTTP_ACCEPT_LANGUAGE": "en-US",
      "Accept-Language": "en-US",
      "X-MBX-APIKEY": "API_KEY_HERE"
    }
);

print(response.body);

编辑-工作签名

String baseUrl = 'https://api.binance.com/api/v3/account?';
int timeStamp = DateTime.now().millisecondsSinceEpoch;
String queryParams = 'recvWindow=5000' + '&timestamp=' + timeStamp.toString();
String secret = 'SECRET_KEY_HERE';

List<int> messageBytes = utf8.encode(queryParams);
List<int> key = utf8.encode(secret);
Hmac hmac = new Hmac(sha256, key);
Digest digest = hmac.convert(messageBytes);
String signature = hex.encode(digest.bytes);
String url = baseUrl + queryParams + "&signature=" + signature;

var response = await http.get(
  url,
  headers: {
    "Accept": "application/json",
    "HTTP_ACCEPT_LANGUAGE": "en-US",
    "Accept-Language": "en-US",
    "X-MBX-APIKEY": "API_KEY_HERE"
  }
);

print(response.body);

1 个答案:

答案 0 :(得分:0)

您的API要求签名以十六进制表示-因此正则表达式$contact->setFirstname('Primo'); $form =$this->createFormBuilder($contact) ->add('picture', FileType::class, ['required'=>false, 'label' => 'Add Profile picture (jpg file)']) ->add('firstname', TextType::class, array('attr'=> array('value'=>'mydefaultvalue','class' => 'form-control'))) -即64个十六进制大写或小写字符。

使用convert包将字节转换为十六进制,而不是'^[A-Fa-f0-9]{64}$'将字节转换为基数64。注意:这不是base64.encode(digest.bytes)库。这是一个发布包,因此您必须将其添加到dart:convert并导入。

然后您可以使用pubspec.yaml