调用 Coinbase pro 沙盒 api 时,无效:401 Unauthorized。文本:""message":"invalid signature&qu

Posted

技术标签:

【中文标题】调用 Coinbase pro 沙盒 api 时,无效:401 Unauthorized。文本:""message":"invalid signature"" Kotlin【英文标题】:when calling Coinbase pro sandbox api, invalid: 401 Unauthorized. Text: ""message":"invalid signature"" Kotlin调用 Coinbase pro 沙盒 api 时,无效:401 Unauthorized。文本:""message":"invalid signature"" Kotlin 【发布时间】:2021-12-01 23:14:37 【问题描述】:

我想做的是调用 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()))
    

【问题讨论】:

您能否通过 cURL 发出成功响应的请求?如果是这样,请分享一个 cURL 命令。 不,我也无法通过 cURL 成功响应,因为我需要生成 cb-access-sign,这是我的问题。 【参考方案1】:

我看到您的消息签名代码在连接消息组件时不使用请求正文 JSON 字符串。这是我的函数版本,它为相同的输入返回与NodeJS script 中相同的字符串:

import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec

fun main() 
    val result = sign(
        secret = "TVlfQVBJX0tFWQ==",
        timestampMs = System.currentTimeMillis(),
        method = "POST",
        requestPath = "/orders",
        request = Req(
            price = "1.0",
            size = "1.0",
            side = "buy",
            product_id = "BTC-USD",
        )
    )

    println(result)


@OptIn(ExperimentalSerializationApi::class)
fun sign(timestampMs: Long, method: String, requestPath: String, request: Req, secret: String): String 
    val accessTimestamp = timestampMs / 1000.0
    val message = "%.3f".format(accessTimestamp) + method + requestPath + Json.encodeToString(request)

    val sha256HMAC = Mac.getInstance("HmacSHA256")
    val key: ByteArray = Base64.getDecoder().decode(secret)
    sha256HMAC.init(SecretKeySpec(key, "HmacSHA256"))

    return Base64.getEncoder().encodeToString(
        sha256HMAC.doFinal(message.toByteArray())
    )


@Serializable
data class Req(val price: String, val size: String, val side: String, val product_id: String)

【讨论】:

我用你的例子来解决我的问题,问题是我传递的是完整路径,而不仅仅是/accounts。当我看到你的例子时,我意识到了这个问题。非常感谢。

以上是关于调用 Coinbase pro 沙盒 api 时,无效:401 Unauthorized。文本:""message":"invalid signature&qu的主要内容,如果未能解决你的问题,请参考以下文章

Python Coinbase Pro API 如何计算限价单的执行价值?

coinbase pro API - 我可以更新未平仓限价单吗?

Coinbase Pro 费用和总额

Coinbase API v2 获得多天的历史价格

Python coinbase API 价格为浮动

Coinbase pro web socket 获取货币的当前价格