如何用swift到yobit.net发出POST请求?

时间:2017-01-05 20:15:05

标签: swift

我无法在SWIFT中发出简单的POST请求来交换yobit.net Yobit API将方法名称作为POST请求的参数,可能是SHA函数有问题吗?

PHP代码:

<?php

function yobit_api_query($method, $req = array())
{

$api_key    = '69F6F4CBFB5EC707869AD92274C934EC';
$api_secret = '1a836b10eb8592fe487bf61c4c8a31c7';

$req['method'] = $method;
$req['nonce'] = time();
$post_data = http_build_query($req, '', '&');
$sign = hash_hmac("sha512", $post_data, $api_secret);
$headers = array(
    'Sign: '.$sign,
    'Key: '.$api_key,
);

$ch = null;
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; SMART_API PHP client; '.php_uname('s').'; PHP/'.phpversion().')');
curl_setopt($ch, CURLOPT_URL, 'https://yobit.net/tapi/');
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_ENCODING , 'gzip');
$res = curl_exec($ch);
if($res === false)
{
    $e = curl_error($ch);
    echo $e;
    debuglog($e);
    curl_close($ch);
    return null;
}

curl_close($ch);

$result = json_decode($res, true);
if(!$result) debuglog($res);
echo $result;
echo $res;
return $result;
}

    yobit_api_query("getInfo");

?>

但是在SWIFT中它不起作用(

let key = "1a836b10eb8592fe487bf61c4c8a31c7"
let nonce = 4
let parameters: Parameters = ["method": "getInfo", "nonce": nonce]

let data = "method=getInfo&nonce=" + String(nonce)
let sign = generateHMAC(key: key, data: data)

let headers: HTTPHeaders = [
  "Content-Type" : "application/x-www-form-urlencoded",
  "Key": "69F6F4CBFB5EC707869AD92274C934EC",
  "Sign": sign,
]

Alamofire.request("https://yobit.net/tapi", method: .post, parameters: parameters, headers: headers).response { response in
  debugPrint(response.response)
}

function generateHMAC:

func generateHMAC(key: String, data: String) -> String {

  var result: [CUnsignedChar]
  if let cKey = key.cString(using: String.Encoding.utf8),
    let cData = data.cString(using: String.Encoding.utf8)
  {
    let algo  = CCHmacAlgorithm(kCCHmacAlgSHA512)
    result = Array(repeating: 0, count: Int(CC_SHA512_DIGEST_LENGTH))

    CCHmac(algo, cKey, cKey.count-1, cData, cData.count-1, &result)
  }
  else {
    fatalError("Nil returned when processing input strings as UTF8")
  }

  let hash = NSMutableString()
  for val in result {
    hash.appendFormat("%02hhx", val)
  }

  return hash as String
}

答案总是代码 - 200,但没有任何信息和访问被拒绝。

0 个答案:

没有答案