Class: Itbit::Api

Inherits:
Object
  • Object
show all
Defined in:
lib/itbit/api.rb

Class Method Summary collapse

Class Method Details

.api_urlObject



29
30
31
32
# File 'lib/itbit/api.rb', line 29

def self.api_url
  prefix = Itbit.sandbox ? 'beta-api' : 'api'
  "https://#{prefix}.itbit.com/v1"
end

.request(verb, path, options = { }) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/itbit/api.rb', line 6

def self.request(verb, path, options = { })
  timestamp = (Time.now.to_f * 1000).round.to_s
  nonce = timestamp
  payload = options.empty? || verb == :get ? nil : JSON.dump(options)
  query = options.any? && verb == :get ? "?#{options.to_query}" : ''
  url = "#{api_url}#{path}#{query}"

  signature = sign_message(verb, url, payload, nonce, timestamp)
  headers = {
    authorization: "#{Itbit.client_key}:#{signature}",
    x_auth_timestamp: timestamp,
    x_auth_nonce: nonce,
    content_type: 'application/json'
  }
  response = RestClient::Request.execute(
    :method => verb,
    :url => url,
    :payload => payload,
    :headers => headers,
    :ssl_version => 'SSLv23')
  JSON.parse(response.to_str) if response.to_str.presence
end

.sign_message(verb, url, json_body, nonce, timestamp) ⇒ Object



34
35
36
37
38
39
# File 'lib/itbit/api.rb', line 34

def self.sign_message(verb, url, json_body, nonce, timestamp)
  message = JSON.dump([verb.upcase, url, json_body || '', nonce, timestamp])
  hash_digest = OpenSSL::Digest::SHA256.digest(nonce + message)
  hmac_digest = OpenSSL::HMAC.digest(OpenSSL::Digest::SHA512.new, Itbit.secret, url + hash_digest)
  Base64.strict_encode64(hmac_digest)
end