Ruby中的Bitstamp API签名

时间:2014-02-11 16:52:37

标签: ruby bitcoin

我正在尝试使用API​​访问Bitstamp帐户的余额。

secret = "secret"
key = "key"
nonce = (1000*Time.now.to_f).to_i.to_s
client_id = "123123"

message = nonce + client_id + key
signature = HMAC::SHA256.hexdigest(secret, message).upcase

puts open("https://www.bitstamp.net/api/balance/?nonce=#{nonce}&key=#{key}&signature=#{signature}").read

它清楚地生成所有必需的属性

https://www.bitstamp.net/api/balance/?nonce=1392137355403&key=key&signature=955A3FFC6FEBE69385B9503307873DBCD21E9B7B8EDE67817FFF70961189CE50

然而错误说属性丢失了,为什么?

{"error": "Missing key, signature and nonce parameters"}

1 个答案:

答案 0 :(得分:2)

问题是我发送的请求是GET而不是POST。以下是我现在使用的完整代码。

require 'open-uri'
require 'json'
require 'base64'
require 'openssl'
require 'hmac-sha2'
require 'net/http'
require 'net/https'
require 'uri'

def bitstamp_private_request(method, attrs = {})
  secret = "xxx"
  key = "xxx"
  client_id = "xxx"
  nonce = nonce_generator

  message = nonce + client_id + key
  signature = HMAC::SHA256.hexdigest(secret, message).upcase

  url = URI.parse("https://www.bitstamp.net/api/#{method}/")
  http = Net::HTTP.new(url.host, url.port)
  http.use_ssl = true

  data = {
    nonce: nonce,
    key: key,
    signature: signature
  }
  data.merge!(attrs)
  data = data.map { |k,v| "#{k}=#{v}"}.join('&')

  headers = {
    'Content-Type' => 'application/x-www-form-urlencoded'
  }

  resp = http.post(url.path, data, headers)
  console_log "https://www.bitstamp.net/api/#{method}/"
  resp.body
end

def nonce_generator
  (Time.now.to_f*1000).to_i.to_s
end