Class: MotionWechat::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/motion-wechat/client.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(client_id, client_secret, code, options = {}) ⇒ Client

Instantiate a new OAuth 2.0 client using the Client ID and Client Secret registered to your application.

Example:

MtionWechat::Client.new 'key', 'secret', 'code', {}

Arguments:

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


18
19
20
21
22
23
24
25
26
27
# File 'lib/motion-wechat/client.rb', line 18

def initialize(client_id, client_secret, code, options = {})
  opts      = options.dup
  @id       = client_id
  @secret   = client_secret
  @code     = code
  @site     = opts[:site] || "https://api.weixin.qq.com"
  @options  = {
    token_url: '/sns/oauth2/access_token'
  }.merge(opts)
end

Instance Attribute Details

#idObject (readonly)

Returns the value of attribute id.



3
4
5
# File 'lib/motion-wechat/client.rb', line 3

def id
  @id
end

#optionsObject

Returns the value of attribute options.



4
5
6
# File 'lib/motion-wechat/client.rb', line 4

def options
  @options
end

#secretObject (readonly)

Returns the value of attribute secret.



3
4
5
# File 'lib/motion-wechat/client.rb', line 3

def secret
  @secret
end

#siteObject (readonly)

Returns the value of attribute site.



3
4
5
# File 'lib/motion-wechat/client.rb', line 3

def site
  @site
end

Instance Method Details

#get(path, opts = {}, &block) ⇒ Object

Request information

Example:

@client.get '/sns/userinfo', openid: "openid" do |info|
  p info
end


61
62
63
64
65
66
# File 'lib/motion-wechat/client.rb', line 61

def get(path, opts = {}, &block)
  AFMotion::HTTP.get(@site + path, opts) do |res|
    hash = to_hash res.body.to_s
    block.call hash
  end
end

#get_token(&block) ⇒ Object

Returns token url to get access token

Example:

@client.get_token do |token|
  p token
end


45
46
47
48
49
50
51
52
# File 'lib/motion-wechat/client.rb', line 45

def get_token(&block)
  params = "appid=#{@id}&secret=#{@secret}&code=#{@code}&grant_type=authorization_code"
  AFMotion::HTTP.get(token_url + "?" + params) do |res|
    hash  = to_hash res.body.to_s
    token = AccessToken.from_hash self, hash
    block.call token
  end
end

#token_urlObject

Returns token url to get access token

Example:

@client.token_url


34
35
36
# File 'lib/motion-wechat/client.rb', line 34

def token_url
  @site + @options[:token_url]
end