Search code examples
rubybitcoin

Bitstamp API signature in Ruby


I'm trying to access balance of Bitstamp account with API.

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

it clearly generates all required attributes

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

yet the error says attributes are missing, why?

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

Solution

  • The problem was that I was sending the request as GET instead of POST. Here is the full code I am using now that works.

    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