Class: WeChat::JsTicket

Inherits:
Object
  • Object
show all
Includes:
REST::Utils, Symbolizable
Defined in:
lib/we_chat/js_ticket.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(client, access_token, js_ticket_file) ⇒ JsTicket

Returns a new instance of JsTicket.



12
13
14
15
16
# File 'lib/we_chat/js_ticket.rb', line 12

def initialize(client, access_token, js_ticket_file)
  @client = client
  @access_token = access_token
  @js_ticket_file = js_ticket_file
end

Instance Attribute Details

#access_tokenObject (readonly)

Returns the value of attribute access_token.



10
11
12
# File 'lib/we_chat/js_ticket.rb', line 10

def access_token
  @access_token
end

#clientObject (readonly)

Returns the value of attribute client.



10
11
12
# File 'lib/we_chat/js_ticket.rb', line 10

def client
  @client
end

#js_ticket_dataObject (readonly)

Returns the value of attribute js_ticket_data.



10
11
12
# File 'lib/we_chat/js_ticket.rb', line 10

def js_ticket_data
  @js_ticket_data
end

#js_ticket_fileObject (readonly)

Returns the value of attribute js_ticket_file.



10
11
12
# File 'lib/we_chat/js_ticket.rb', line 10

def js_ticket_file
  @js_ticket_file
end

Class Method Details

.get_js_ticket(file_path = nil) ⇒ Object



46
47
48
49
50
# File 'lib/we_chat/js_ticket.rb', line 46

def get_js_ticket(file_path = nil)
  file_path ||= WeChat.wechat_js_ticket_file_path
  data = JSON.parse(File.read(file_path))
  data["ticket"]
end

Instance Method Details

#retrieveObject



18
19
20
21
22
23
24
25
26
27
# File 'lib/we_chat/js_ticket.rb', line 18

def retrieve
  response = WeChat::REST::Request.new(client, :get, '/ticket/getticket',
    params: {
      type: 'jsapi',
      access_token: access_token
    }).perform

  File.open(js_ticket_file, 'w') { |file| file.write(response.to_json) } if valid?(response)
  return @js_ticket_data = response
end

#valid?(data) ⇒ Boolean

Returns:

  • (Boolean)


39
40
41
42
# File 'lib/we_chat/js_ticket.rb', line 39

def valid?(data)
  ticket = data.nil? ? '' : data[:ticket]
  !ticket.blank?
end

#valueObject



29
30
31
32
33
34
35
36
37
# File 'lib/we_chat/js_ticket.rb', line 29

def value
  begin
    @js_ticket_data ||= symbolize_keys!(JSON.parse(File.read(js_ticket_file)))
  rescue => e
    Rails.logger.debug e
    retrieve
  end
  @js_ticket_data[:ticket]
end