lib/wechat/api/client.rb in wechat-api-0.3.0 vs lib/wechat/api/client.rb in wechat-api-0.4.0
- old
+ new
@@ -1,9 +1,10 @@
require 'multi_json'
require 'wechat/api/message'
require 'wechat/api/user'
require 'wechat/api/util'
+require 'wechat/api/js_ticket'
require 'faraday'
require 'logger'
module Wechat
module Api
@@ -16,16 +17,17 @@
include User
include Util
API_BASE = 'https://api.weixin.qq.com/cgi-bin/'
- attr_reader :app_id, :secret
- attr_accessor :logger
+ attr_reader :app_id, :secret, :ticket
+ attr_accessor :logger, :site
def initialize(app_id, secret)
@app_id, @secret = app_id, secret
@logger = Logger.new(STDOUT)
+ @ticket = JsTicket.new self
@token_file = File.join('/tmp', "wechat-api-#{app_id}")
end
def access_token
@access_token ||= begin
@@ -35,14 +37,15 @@
refresh
end
end
def refresh
- url = format('%stoken', API_BASE)
+ url = format('%stoken', base_url)
resp = connection.get(url, token_params)
response = MultiJson.load(resp.body)
return handle_error(response) if response['errcode']
+
@access_token = response['access_token']
File.open(@token_file, 'w') { |f| f.write(resp.body) } if @access_token
@access_token
end
@@ -70,13 +73,15 @@
end
end
end
def with_access_token(uri, params, tried = 2)
- url = format('%s%s', API_BASE, uri)
+ url = format('%s%s', base_url, uri)
begin
resp = yield(url, params.merge(access_token: access_token))
+ raise ResponseError, resp unless resp.success?
+
response = MultiJson.load(resp.body)
handle_error(response)
rescue AccessTokenExpiredError => e
refresh
retry unless (tried -= 1).zero?
@@ -84,10 +89,14 @@
end
end
private
+ def base_url
+ site || API_BASE
+ end
+
def debug_request
response = yield
logger.debug { response }
response
end
@@ -95,12 +104,12 @@
def handle_error(response)
case response['errcode']
when 0, nil
response
when 40_001, 42_001, 40_014
- fail AccessTokenExpiredError, response
+ raise AccessTokenExpiredError, response
else
- fail ResponseError, response
+ raise ResponseError, response
end
end
def token_params
{