LoginSignup
0
0

SwitchBot API v1.1をRubyから呼び出す

Last updated at Posted at 2023-05-13

はじめに

SwitchBot API v1.1をPostmanから呼び出す に引き続き、RubyでSwitchBot APIを呼び出すテストを行いました。公式の SwitchBot Open API Documents にはPython, JavaScript, C#など代表的な言語のサンプルコードは用意されていますがなぜかRubyはなかったので参考になれば幸いです。

コード

SwitchBotAPIv11.rb
require 'openssl'
require 'securerandom'
require 'base64'
require 'httpclient'

def getDevices
    token = "92708d6a34f4ea9f4a79f..."
    secret = "00f394fc46f732b6..."
    t = (Time.now.to_f * 1000).to_i
    nonce = SecureRandom.uuid
    payload = "#{token}#{t}#{nonce}"
    signature = Base64.strict_encode64(OpenSSL::HMAC.digest('sha256', secret, payload))

    client = HTTPClient.new
    url = "https://api.switch-bot.com/v1.1/devices"
    header = { "Authorization" => token, "sign" => signature, "nonce" => nonce, "t" => t }
    response = client.get(url, header: header)
    puts (response.body)
end

getDevices

実行結果

$ ruby SwitchBotAPIv11.rb 
{"statusCode":100,"body":{"deviceList":[{"deviceId":"44179310230F","deviceName":"デバイス名"...

ハマったポイント

  • 唯一ハマったのがt(UnixTime)です。RubyのTime.now.to_iは秒単位までのUnixTimeしか返してくれず、Time.now.to_iで送っても応答はUnauthorizedになってしまいます。必要なのはミリ秒単位のUnixTimeなのですが、それを送るにはTime.now.to_f * 1000と小数のUnixTimeを1000倍してから整数に直すという力技が必要になります。
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0