Class: MpWeixin::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/mp_weixin/client.rb

Overview

The MpWeixin::Client class reference to The OAuth2::Client class

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app_id = nil, app_secret = nil, opts = {}) {|builder| ... } ⇒ Client

Instantiate a new client using the Client ID and Client Secret registered to your weixin mp account.

Parameters:

  • app_id (String) (defaults to: nil)

    the app_id value

  • app_secret (String) (defaults to: nil)

    the app_secret value

  • opts (Hash) (defaults to: {})

    the options to create the client with

Options Hash (opts):

  • :site (String)

    the site host provider to connection

  • :authorize_url (String) — default: '/oauth/authorize'

    absolute or relative URL path to the Authorization endpoint

  • :token_url (String) — default: '/oauth/token'

    absolute or relative URL path to the Token endpoint

  • :connection_opts (Hash) — default: {}

    Hash of connection options to pass to initialize Faraday with

  • :raise_errors (Boolean) — default: true

    whether or not to raise an MpWeixin::Error on responses with 400+ status codes

Yields:

  • (builder)

    The Faraday connection builder



24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/mp_weixin/client.rb', line 24

def initialize(app_id = nil, app_secret = nil, opts={}, &block)
  _opts = opts.dup
  @id = app_id || Config.app_id
  @secret = app_secret || Config.app_secret
  @site = _opts.delete(:site) || "https://api.weixin.qq.com/"
  ssl = _opts.delete(:ssl)
  @options = {:authorize_url    => '/oauth/authorize',
              :token_url        => '/cgi-bin/token',
              :token_method     => :post,
              :connection_opts  => {},
              :connection_build => block,
              :raise_errors     => true}.merge(_opts)
  @options[:connection_opts][:ssl] = ssl if ssl
end

Instance Attribute Details

#connectionObject

The Faraday connection object



55
56
57
58
59
60
61
62
63
# File 'lib/mp_weixin/client.rb', line 55

def connection
  @connection ||= begin
    conn = Faraday.new(site, options[:connection_opts])
    conn.build do |b|
      options[:connection_build].call(b)
    end if options[:connection_build]
    conn
  end
end

#idObject (readonly)

Returns the value of attribute id.



6
7
8
# File 'lib/mp_weixin/client.rb', line 6

def id
  @id
end

#optionsObject

Returns the value of attribute options.



7
8
9
# File 'lib/mp_weixin/client.rb', line 7

def options
  @options
end

#secretObject (readonly)

Returns the value of attribute secret.



6
7
8
# File 'lib/mp_weixin/client.rb', line 6

def secret
  @secret
end

#siteObject

Returns the value of attribute site.



6
7
8
# File 'lib/mp_weixin/client.rb', line 6

def site
  @site
end

#tokenObject

Returns the value of attribute token.



7
8
9
# File 'lib/mp_weixin/client.rb', line 7

def token
  @token
end

Class Method Details

.from_hash(hash, opts = {}) {|builder| ... } ⇒ Object

Initializes a new Client from a hash

Parameters:

  • a (Hash)

    Hash contains access_token and expires

  • opts (Hash) (defaults to: {})

    the options to create the client with

Options Hash (opts):

  • :connection_opts (Hash) — default: {}

    Hash of connection options to pass to initialize Faraday with

  • :max_redirects (FixNum) — default: 5

    maximum number of redirects to follow

Yields:

  • (builder)

    The Faraday connection builder



163
164
165
166
167
168
# File 'lib/mp_weixin/client.rb', line 163

def self.from_hash(hash, opts={}, &block)
  client = self.new(opts, &block)
  client.get_token_from_hash(hash)

  client
end

Instance Method Details

#authorize_url(params = nil) ⇒ Object

The authorize endpoint URL of the MpWeixin provider

Parameters:

  • params (Hash) (defaults to: nil)

    additional query parameters



108
109
110
# File 'lib/mp_weixin/client.rb', line 108

def authorize_url(params=nil)
  connection.build_url(options[:authorize_url], params).to_s
end

#get_token(params = {}, access_token_opts = {}, access_token_class = AccessToken) ⇒ AccessToken

Initializes an AccessToken by making a request to the token endpoint

Parameters:

  • params (Hash) (defaults to: {})

    a Hash of params for the token endpoint

  • access (Hash)

    token options, to pass to the AccessToken object

  • class (Class)

    of access token for easier subclassing MpWeixin::AccessToken

Returns:

Raises:



125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/mp_weixin/client.rb', line 125

def get_token(params = {}, access_token_opts = {}, access_token_class = AccessToken)
  params = ActiveSupport::HashWithIndifferentAccess.new(params)
  params.reverse_merge!(grant_type: "client_credential", appid: id, secret: secret)

  opts = {:raise_errors => options[:raise_errors], :parse => params.delete(:parse)}
  if options[:token_method] == :post
    headers = params.delete(:headers)
    opts[:body] = params
    opts[:headers] =  {'Content-Type' => 'application/x-www-form-urlencoded'}
    opts[:headers].merge!(headers) if headers
  else
    opts[:params] = params
  end
  response = request(options[:token_method], token_url, opts)
  raise Error.new(response) if options[:raise_errors] && !(response.parsed.is_a?(Hash) && response.parsed['access_token'])
  @token = access_token_class.from_hash(self, response.parsed.merge(access_token_opts))
end

#get_token_from_hash(hash) ⇒ AccessToken

Initializes an AccessToken from a hash

Parameters:

  • hash (Hash)

    a Hash contains access_token and expires

Returns:



147
148
149
150
151
152
153
154
# File 'lib/mp_weixin/client.rb', line 147

def get_token_from_hash(hash)
  access_token = hash.delete('access_token') || hash.delete(:access_token) || hash.delete('oauth_token') || hash.delete(:oauth_token)
  opts = {:expires_at => hash["expires"] || hash[:expires],
          :header_format => "OAuth2 %s",
          :param_name => "access_token"}

  @token = AccessToken.new(self, access_token, opts)
end

#groupObject

assocation an Interface::Group instance to client



190
191
192
# File 'lib/mp_weixin/client.rb', line 190

def group
  @group ||= Interface::Group.new(self)
end

#is_authorized?Boolean

Whether or not the client is authorized

Returns:

  • (Boolean)


42
43
44
# File 'lib/mp_weixin/client.rb', line 42

def is_authorized?
  !!token && !token.expired?
end

assocation an Interface::Menu instance to client



180
181
182
# File 'lib/mp_weixin/client.rb', line 180

def menu
  @menu ||= Interface::Menu.new(self)
end

#messageObject

assocation an Interface::Message instance to client



175
176
177
# File 'lib/mp_weixin/client.rb', line 175

def message
  @message ||= Interface::Message.new(self)
end

#promotionObject

assocation an Interface::Promotion instance to client



185
186
187
# File 'lib/mp_weixin/client.rb', line 185

def promotion
  @promotion ||= Interface::Promotion.new(self)
end

#request(verb, url, opts = {}) ⇒ Object

Makes a request relative to the specified site root.

Parameters:

  • verb (Symbol)

    one of :get, :post, :put, :delete

  • url (String)

    URL path of request

  • opts (Hash) (defaults to: {})

    the options to make the request with

Options Hash (opts):

  • :params (Hash)

    additional query parameters for the URL of the request

  • :body (Hash, String)

    the body of the request

  • :headers (Hash)

    http request headers

  • :raise_errors (Boolean)

    whether or not to raise an MpWeixin::Error on 400+ status



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/mp_weixin/client.rb', line 74

def request(verb, url, opts={})
  url = self.connection.build_url(url, opts[:params]).to_s

  response = connection.run_request(verb, url, opts[:body], opts[:headers]) do |req|
    yield(req) if block_given?
  end
  response = Response.new(response, :parse => opts[:parse])

  case response.status
  when 301, 302, 303, 307
    opts[:redirect_count] ||= 0
    opts[:redirect_count] += 1
    return response if opts[:redirect_count] > options[:max_redirects]
    if response.status == 303
      verb = :get
      opts.delete(:body)
    end
    request(verb, response.headers['location'], opts)
  when 200..299, 300..399
    # on non-redirecting 3xx statuses, just return the response
    response
  when 400..599
    e = Error.new(response)
    raise e if opts.fetch(:raise_errors, options[:raise_errors])
    response.error = e
    response
  else
    raise Error.new(response), "Unhandled status code value of #{response.status}"
  end
end

#token_url(params = nil) ⇒ Object

The token endpoint URL of the MpWeixin provider

Parameters:

  • params (Hash) (defaults to: nil)

    additional query parameters



115
116
117
# File 'lib/mp_weixin/client.rb', line 115

def token_url(params=nil)
  connection.build_url(options[:token_url], params).to_s
end

#userObject

assocation an Interface::User instance to client



195
196
197
# File 'lib/mp_weixin/client.rb', line 195

def user
  @user ||= Interface::User.new(self)
end