在R中验证API

时间:2018-02-10 16:50:14

标签: 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)

有人能告诉我我做错了吗?

1 个答案:

答案 0 :(得分:2)

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

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

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)

创建&#34;新订单&#34;您只需要将payload更改为某些内容,例如:

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"