r - 在 R 中验证 API

标签 r api authentication

我正在尝试通过 api 访问 Bitfinex,但很难正确验证我的请求。有一个 Python 示例说明了我想要执行的操作 ( https://gist.github.com/jordanbaucke/5812039 ),但我似乎无法让它在 R 中工作。

key <- c("MY API KEY")
secret = c("MY API SECRET")

req <- GET("https://api.bitfinex.com/v1/balances", 
               authenticate(key, secret))
               add_headers(X-BFX-APIKEY = key))
    stop_for_status(req)
    content(req)

有人可以告诉我我做错了什么吗?

最佳答案

/v1/balances 是经过 Bitfinex 身份验证的端点,因此它需要 POST 请求并正确处理 payload header

这是我自己的脚本中的一个工作示例:

library(httr)

key <- "..."
secret <- "..."

# payload JSON object, the request should refer to the URL
# nonce should always be greater than for previous calls
payload_json <- list(request = '/v1/account_infos', nonce = as.character(as.numeric(as.POSIXct(Sys.time()))))

# creating string from JSON payload
payload <- jsonlite::toJSON(payload_json, auto_unbox = TRUE)

# encoding payload string
payload_str <- base64enc::base64encode(charToRaw(as.character(payload)))

# adding three Bitfinex headers:
# X-BFX-APIKEY = key
# X-BFX-PAYLOAD = base64 encoded payload string
# X-BFX-SIGNATURE = sha384 encrypted payload string with the secret key
req <- POST("https://api.bitfinex.com/v1/account_infos",
           add_headers('X-BFX-APIKEY' = key,
                       'X-BFX-PAYLOAD' = payload_str,
                       'X-BFX-SIGNATURE' = openssl::sha384(payload_str, key = secret))
           )

content(req)

要创建“新订单”,您只需将有效负载更改为某些内容,如下所示:

payload_json <- list(request = '/v1/account_infos',
  nonce = as.character(as.numeric(as.POSIXct(Sys.time()))),
  symbol = 'BTCUSD',
  amount = '0.3',
  price = '1000',
  exchange = 'bitfinex',
  side = 'sell',
  type = 'exchange market'
)

其余代码无需更改即可运行。

有关 payload 参数列表,请查看 Bitfinex API 文档,例如"New Order" .

关于r - 在 R 中验证 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48723175/

相关文章:

[R] 中两列的字符串匹配

api - 正式且可测试的 API 定义

python - Tweepy 不将重复的推文存储到数据库中

java - 如何在身份验证失败 url 中包含 SPRING_SECURITY_LAST_USERNAME?

r - R 国家/地区内的大圆 map

xml - 从 XML 属性到 R 中的 data.frame

带有自定义 API 的 Javascript Windows Azure 移动服务客户端

asp.net - HTTP 模块和 HTTP 处理程序

spring - 如何在Spring Security 3中设置用户角色?

引用对象元素