Coinbase API调用POST购买接口返回401 Unauthorized问题求助
问题根因
401报错由签名生成逻辑不符合Coinbase API规则导致:
- Coinbase要求POST、PUT等携带请求体的接口,生成签名的原始字符串需要包含4部分:
时间戳 + 请求方法 + 请求路径 + 完整请求体字符串,你当前的签名串仅包含前3部分,缺少请求体内容,服务端校验签名不通过返回401。 - 你的GET接口可正常调用刚好验证了这个逻辑:GET请求无请求体,原有签名规则刚好符合要求,因此可以正常通过校验。
解决方法
修改签名串生成逻辑,将完整的请求体字符串追加到签名原始串末尾,修改后的核心代码如下:
$time = 'https://api.coinbase.com/v2/time' $epochtime = [string]((Invoke-WebRequest $time | ConvertFrom-Json).data).epoch $method = 'POST' $requestpath = '/v2/accounts/xxxxxxxx-3ecb-xxxxxxxx-xxxxxxxx/buys' $endpoint = "https://api.coinbase.com/$($requestpath)" $secret_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' # 先定义请求体,保证用于签名和实际发送的内容完全一致 $body = '{"amount": "10", "currency": "XLM", "payment_method": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "commit": "true", "quote":"false"}' # 签名串追加请求体 $sign = $epochtime + $method + $requestpath + $body $hmacsha = New-Object System.Security.Cryptography.HMACSHA256 $hmacsha.key = [Text.Encoding]::UTF8.GetBytes($secret_key) $computeSha = $hmacsha.ComputeHash([Text.Encoding]::UTF8.GetBytes($sign)) $signature = ([System.BitConverter]::ToString($computeSha) -replace "-").ToLower() $header = @{ "CB-ACCESS-SIGN"=$signature "CB-ACCESS-TIMESTAMP"=$epochtime "CB-ACCESS-KEY"='xxxxxxxxxxxxxxxxxxxx' } function Get-CoinBase($method, $endpoint, $header, $body) { $result = Invoke-WebRequest $endpoint -Headers $header -Method $method -body $body -ContentType "application/json" -UseBasicParsing # 修复变量名错误问题,原$APImethod不存在 write-host $method -f yellow return $result } $AccountBAL = Get-CoinBase -method "POST" -endpoint $endpoint -header $header -body $body
- 注意事项:用于签名的body字符串必须和实际传入接口请求的body完全一致,不能有多余的空格、换行或者键值顺序差异,否则仍会出现签名校验失败的问题。
内容的提问来源于stack exchange,提问作者Stephen Galvin
相关产品推荐
相关产品推荐

