Class: Weixin::Menu

Inherits:
Object
  • Object
show all
Defined in:
lib/weixin/menu.rb

Instance Method Summary collapse

Constructor Details

#initialize(api, key) ⇒ Menu

Returns a new instance of Menu.



8
9
10
11
12
13
14
15
# File 'lib/weixin/menu.rb', line 8

def initialize(api, key)
  @api = api
  @key = key
  
  @access_token = nil
  @expired_at   = Time.now
  @endpoint     = 'https://api.weixin.qq.com/cgi-bin'
end

Instance Method Details

#access_tokenObject



17
18
19
20
21
22
# File 'lib/weixin/menu.rb', line 17

def access_token
  if Time.now >= @expired_at
    authenticate
  end
  @access_token
end

#add(menu) ⇒ Object



37
38
39
40
41
42
43
44
# File 'lib/weixin/menu.rb', line 37

def add(menu)
  request = Nestful::Connection.new(gw_url('create')).post(gw_path('create'), MultiJson.dump(menu)) rescue nil
  unless request.nil?
    errcode = MultiJson.load(request.body)['errcode']
    return true if errcode == 0
  end
  false
end

#authenticateObject



46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/weixin/menu.rb', line 46

def authenticate
  url = "#{@endpoint}/token"
  request = Nestful.get url, { :grant_type => 'client_credential', :appid => @api, :secret => @key } rescue nil
  unless request.nil?
    auth = MultiJson.load(request.body)
    unless auth.has_key?('errcode')
      @access_token = auth['access_token']
      @expired_at   = Time.now + auth['expires_in'].to_i
    end
    @access_token
  end
end

#getObject



32
33
34
35
# File 'lib/weixin/menu.rb', line 32

def get
  request = Nestful.get gw_url('get') rescue nil
  MultiJson.load(request.body) unless request.nil?
end

#gw_path(method) ⇒ Object



24
25
26
# File 'lib/weixin/menu.rb', line 24

def gw_path(method)
  "/menu/#{method}?access_token=#{access_token}"
end

#gw_url(method) ⇒ Object



28
29
30
# File 'lib/weixin/menu.rb', line 28

def gw_url(method)
  "#{@endpoint}" + gw_path(method)
end