腾讯IM Usersig Ruby版

module MobileGroupRoomHelper
  APP_ID = "你的APPid"
  APP_KEY = '你的KEY'

  def gen_sig(identifier, expire = 604800)
    self.__gen_sig(identifier, expire, nil)
  end

  def gen_sig_with_userbuf(identifier, expire, userbuf)
    self.__gen_sig(identifier, expire, userbuf)
  end

  def __hmacsha256(identifier, curr_time, expire, base64_userbuf = nil)
    raw_content_to_be_signed = "TLS.identifier:" + identifier.to_s + "\n"\
                                   + "TLS.sdkappid:" + APP_ID.to_s + "\n"\
                                   + "TLS.time:" + curr_time.to_s + "\n"\
                                   + "TLS.expire:" + expire.to_s + "\n"
    if base64_userbuf
      raw_content_to_be_signed += "TLS.userbuf:" + base64_userbuf + "\n"
    end
    Base64.strict_encode64(OpenSSL::HMAC.digest('sha256', APP_KEY, raw_content_to_be_signed))
  end

  def __gen_sig(identifier, expire = 180*86400, userbuf = nil)
    curr_time = Time.now.to_i
    m = Hash.new
    base64_userbuf = nil

    if nil != userbuf
      base64_userbuf = Base64.encode64(userbuf)
      puts 333
      m["TLS.userbuf"] = base64_userbuf
    end

    m["TLS.sig"] = self.__hmacsha256(identifier, curr_time, expire, base64_userbuf)
    m["TLS.expire"]     = expire.to_i
    m["TLS.sdkappid"]   = APP_ID.to_i
    m["TLS.ver"]        = "2.0"
    m["TLS.time"]       = curr_time
    m["TLS.identifier"] = identifier.to_s

    raw_sig = m.to_json.gsub(/,/,', ').gsub(/:/,': ')

    sig_cmpressed = Zlib::Deflate.deflate(raw_sig)

    base64_encode_url(sig_cmpressed)
  end

  def base64_encode_url(data)
    Base64.strict_encode64(data).gsub('+', '*').gsub('/', '-').gsub('=', '_')
  end
end

在使用的地方include调用即可

原文链接

你可能感兴趣的:(腾讯IM Usersig Ruby版)