Class: Wechat::Client

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(base) ⇒ Client

Returns a new instance of Client.



8
9
10
# File 'lib/wechat/client.rb', line 8

def initialize(base)
  @base = base
end

Instance Attribute Details

#baseObject (readonly)

Returns the value of attribute base.



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

def base
  @base
end

Instance Method Details

#get(path, header = {}) ⇒ Object



12
13
14
15
16
# File 'lib/wechat/client.rb', line 12

def get path, header={}
  request(path, header) do |url, header|
    RestClient.get(url, header)
  end
end

#post(path, payload, header = {}) ⇒ Object



18
19
20
21
22
# File 'lib/wechat/client.rb', line 18

def post path, payload, header = {}
  request(path, header) do |url, header|
    RestClient.post(url, payload, header)
  end
end

#request(path, header = {}, &block) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/wechat/client.rb', line 24

def request path, header={}, &block
  url = "#{header.delete(:base) || self.base}#{path}"
  as = header.delete(:as)
  header.merge!(:accept => :json)
  response = yield(url, header)

  raise "Request not OK, response code #{response.code}" if response.code != 200
  parse_response(response, as || :json) do |parse_as, data|
    break data unless (parse_as == :json && data["errcode"].present?)

    case data["errcode"]
    when 0 # for request didn't expect results
      true

    when 42001, 40014 #42001: access_token超时, 40014:不合法的access_token
      raise AccessTokenExpiredError
      
    else
      raise ResponseError.new(data['errcode'], data['errmsg'])
    end
  end
end