Class: XiWechatCorp::API::Connection

Inherits:
Faraday::Connection
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/xi_wechat_corp/api/connection.rb

Constant Summary collapse

ENDPOINT =
'https://qyapi.weixin.qq.com/cgi-bin'
BUILDER =
Faraday::RackBuilder.new do |builder|
  builder.request :json
  builder.use RaiseClientError
  builder.response :json
  builder.response :raise_error
  builder.adapter Faraday.default_adapter
end
ACCESS_TOKEN_MISSING =
[41001, 'Access token is missing']
ACCESS_TOKEN_EXPIRED =
[40014, 'Access token is expired']

Instance Method Summary collapse

Constructor Details

#initialize(options = {}, &block) ⇒ Connection

Accepts all options supported by Faraday::Connection, as well as:

  • access_token [AccessToken|String] already acquired access token

  • corp_id

  • secret

When both corp_id and secret are specified, access token is fetched and refreshed automatically.



46
47
48
49
50
51
52
53
54
55
# File 'lib/xi_wechat_corp/api/connection.rb', line 46

def initialize(options = {}, &block)
  token = options.delete(:access_token)
  token = options[:params][:access_token] if token.nil? && options.key?(:params)
  @access_token = AccessToken.new(options.delete(:access_token))

  @corp_id = options.delete(:corp_id)
  @secret = options.delete(:secret)

  super(ENDPOINT, { builder: BUILDER }.merge(options), &block)
end

Instance Method Details

#get_access_token(corp_id = nil, secret = nil) ⇒ Object Also known as: auth



60
61
62
63
64
65
66
67
# File 'lib/xi_wechat_corp/api/connection.rb', line 60

def get_access_token(corp_id = nil, secret = nil)
  @corp_id = corp_id unless corp_id.nil?
  @secret = secret unless secret.nil?
  @access_token = maybe_cache do
    resp = get('gettoken', corpid: @corp_id, corpsecret: @secret)
    resp.body['access_token']
  end
end

#run_request(method, url, body, headers, &block) ⇒ Object



71
72
73
74
# File 'lib/xi_wechat_corp/api/connection.rb', line 71

def run_request(method, url, body, headers, &block)
  set_access_token_in_params unless url == 'gettoken'
  super(method, url, body, headers, &block)
end