我想做的是调用 Coinbase 沙盒 API 来获取配置文件的所有帐户。
我正在关注官方文档https://docs.cloud.coinbase.com/exchange/reference/exchangerestapi_getaccounts
但不断收到此错误
Client request(https://api-public.sandbox.exchange.coinbase.com/accounts) invalid: 401 Unauthorized. Text: "{"message":"invalid signature"}"
我错过了什么吗?
suspend fun getTradingAccounts(): String {
val timestamp = getTimeStamp()
val response: String = client.get("https://api-public.sandbox.exchange.coinbase.com/accounts") {
headers {
append("Accept", "application/json")
append("Content-Type", "application/json")
append(
"cb-access-key",
"MY_KEY..."
)
append("cb-access-passphrase", "MY_PASSPHRASE....")
append("cb-access-sign", signMessage(
timestamp = timestamp,
method = "GET",
path = "https://api-public.sandbox.exchange.coinbase.com/accounts"
))
append("cb-access-timestamp", timestamp)
}
}
return response
}
private fun getTimeStamp(): String {
val time = LocalDateTime.now()
val zoneId = ZoneId.of("Europe/London")
val epoch = time.atZone(zoneId).toEpochSecond()
return epoch.toString()
}
@Throws(NoSuchAlgorithmException::class, InvalidKeyException::class)
private fun signMessage(timestamp: String, method: String, path: String): String {
val prehash = timestamp + method + path
val sha256_HMAC = Mac.getInstance("HmacSHA256")
val secretDecoded: ByteArray = Base64.getDecoder().decode("MY_API_KEY==")
val secret_key = SecretKeySpec(secretDecoded, "HmacSHA256")
sha256_HMAC.init(secret_key)
return Base64.getEncoder().encodeToString(sha256_HMAC.doFinal(prehash.toByteArray()))
}