Module: MotionWechat::API

Defined in:
lib/motion-wechat/api.rb

Constant Summary collapse

InvalidMediaObject =
Class.new StandardError
InvalidClientError =
Class.new ArgumentError

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.configObject

Returns info_plist_key of MotionWechat

Example:

MotionWechat::API.config


95
96
97
# File 'lib/motion-wechat/api.rb', line 95

def self.config
  NSBundle.mainBundle.objectForInfoDictionaryKey MotionWechat::Config.info_plist_key
end

.instanceObject

Returns singleton instance of MotionWechat

Example:

MotionWechat::API.instance


86
87
88
# File 'lib/motion-wechat/api.rb', line 86

def self.instance
  @instance ||= new config["key"], config["secret"]
end

Instance Method Details

#authorize(opts = {}) ⇒ Object

Sends authorization request

Example:

MotionWechat::API.instance.authorize

Arguments:

opts: (Hash), state: "myapp"


70
71
72
73
74
75
76
77
78
79
# File 'lib/motion-wechat/api.rb', line 70

def authorize(opts={})
  options = {
    scope: "snsapi_userinfo",
    state: "motion-wechat-app"
  }.merge(opts)
  req = SendAuthReq.alloc.init
  req.scope = options[:scope]
  req.state = options[:state]
  WXApi.sendReq(req)
end

#get_user_info(&block) ⇒ Object

Get user information

Example:

MotionWechat::API.instance.get_user_info { |info| ... }

Raises:



50
51
52
53
54
55
56
57
58
59
60
# File 'lib/motion-wechat/api.rb', line 50

def (&block)
  raise InvalidClientError if @client.nil?
  if @token.nil?
    @client.get_token do |token|
      @token = token
      @token. { |info| block.call info }
    end
  else
    @token. { |info| block.call info }
  end
end

#initialize(key, secret, options = {}) ⇒ Object

Initialize weixin API using key and secret

Example:

MtionWechat::API.new 'key', 'secret'

Arguments:

key: (String)
secret: (String)
options: (Hash)


19
20
21
22
# File 'lib/motion-wechat/api.rb', line 19

def initialize(key, secret, options={})
  @key    = key
  @secret = secret
end

#registerAppObject

Register weixin app, usually put in ‘app_delegate.rb`

Example:

MotionWechat::API.instance.registerApp


29
30
31
# File 'lib/motion-wechat/api.rb', line 29

def registerApp
  WXApi.registerApp @key
end

#registerClient(code) ⇒ Object

Register client

Example:

MotionWechat::API.instance.registerClient "code"

Arguments:

code: (String)


41
42
43
# File 'lib/motion-wechat/api.rb', line 41

def registerClient(code)
  @client ||= MotionWechat::Client.new @key, @secret, code
end

#send_text(text) ⇒ Object

Send text to wechat

Example:

MotionWechat::API.instance.send_text "hello, motion"

Arguments:

text: (String)


135
136
137
138
139
140
# File 'lib/motion-wechat/api.rb', line 135

def send_text(text)
  req = SendMessageToWXReq.alloc.init
  req.bText = false
  req.text = text
  WXApi.sendReq(req)
end

#wxObject



7
# File 'lib/motion-wechat/api.rb', line 7

def wx; WXApi; end