我正在嘗試使用描述爲here的API。它使用基於密鑰的HMAC SHA512授權。使用HMAC SHA512從API獲取數據 - Swift
有實現的PHP的例子:
function bitmarket_api($method, $params = array())
{
$key = "klucz_jawny";
$secret = "klucz_tajny";
$params["method"] = $method;
$params["tonce"] = time();
$post = http_build_query($params, "", "&");
$sign = hash_hmac("sha512", $post, $secret);
$headers = array(
"API-Key: " . $key,
"API-Hash: " . $sign,
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_URL, "https://www.bitmarket.pl/api2/");
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$ret = curl_exec($curl);
return json_decode($ret);
}
然後我試圖實現它在斯威夫特:
import Alamofire
import CryptoSwift
func getRawJSON(method: String, params: [String]) -> String {
let publicKey = "publicKeyHere"
let secretKey = "secretKeyHere"
let APIURL = "https://www.bitmarket.pl/api2/"
var params = [
"method": method,
"tonce:": NSDate().timeIntervalSince1970
] as [String : Any]
let hmac: Array<UInt8> = try! HMAC(key: secretKey.utf8.map({$0}), variant: .sha512).authenticate(params)
var headers = [
"API-Key": publicKey,
"API-Hash": hmac
] as [String : Any]
}
你可能注意到了,有沒有Alamofire使用情況獲取數據但是因爲我在準備發送數據時遇到了問題。我的意思是我已經搞砸了CryptoSwift的東西,因爲我得到這個錯誤:Cannot convert value of type '[String : Any]' to expected argument type 'Array<UInt8>'
當我試圖聲明hmac
變量。
如何解決? 我可能必須以某種方式將params
數組轉換爲Array<UInt8
,但我不知道該怎麼做。我不確定是否一切正確。
編輯: 感謝Martin R,實際的代碼是:
func getRawJSON(method: String, paramether: String) {
let publicKey = "publicKeyHere"
let secretKey = "secretKeyHere"
let APIURL = "https://www.bitmarket.pl/api2/"
let query = NSURLComponents()
query.queryItems = [NSURLQueryItem(name: "method", value: method) as URLQueryItem,
NSURLQueryItem(name: "tonce", value: String(Int(NSDate().timeIntervalSince1970))) as URLQueryItem]
let requestString = query.query!
let requestData = Array(requestString.utf8)
let params = [
"method": method,
"tonce:": String(Int(NSDate().timeIntervalSince1970))
] as [String : Any]
let hmac: Array<UInt8> = try! HMAC(key: secretKey.utf8.map({$0}), variant: .sha512).authenticate(requestData)
let hmacData = Data(bytes: hmac)
let hmacString = hmacData.base64EncodedString()
let headers = [
"API-Key": publicKey,
"API-Hash": hmacString
] as [String : String]
Alamofire.request(APIURL, withMethod: .post, parameters: params, encoding: .url, headers: headers)
.responseJSON { response in
print(response)
}
}
不幸的是,調用函數(getRawJSON(method: "info", paramether: "")
)後,我獲取一個錯誤一個JSON:
{
error = 502;
errorMsg = "Invalid message hash";
time = 1472910139;
}
我的散列有什麼問題?
巨大的感謝,幫了不少忙。現在我遇到了散列問題,用更多細節編輯了我的問題。 – kkarol
@kkarol:比較PHP代碼中'$ post'和'$ sign'值與Swift代碼中的'requestString'和'hmac'。 –
'requestString'等於'$ post',但是'$ sign'與'hmac'和'hmacString'不同。 'hmacString'是base64,而'$ sign'包含例如'450043310da274122369bfc0ca621e47fb0b03857746c096a944748585fcd3280744ee4633711f98bbfe3bf0c199deec329a64b723799e597304cfd683ac40e6'。不知道如何將'Array'轉換爲正確的格式。 –
kkarol