Class: EasyWeixin::Api
Instance Method Summary collapse
- #authenticate_headers ⇒ Object
-
#get_access_token ⇒ Object
获取access_token,如果启用redis则使用redis记录,如果没启用就每次进行一次查询。.
- #get_access_token_http ⇒ Object
-
#initialize(app_id, app_secret) ⇒ Api
constructor
A new instance of Api.
- #refresh_token ⇒ Object
- #weixin_redis ⇒ Object
Methods included from Menu
Constructor Details
#initialize(app_id, app_secret) ⇒ Api
Returns a new instance of Api.
7 8 9 10 11 12 13 |
# File 'lib/easy_weixin/api.rb', line 7 def initialize(app_id, app_secret) @app_id = app_id @app_secret = app_secret @redis_key = "weixin_access_token_#{app_id}" @grant_type = 'client_credential' @weixin_api_url = 'https://api.weixin.qq.com' end |
Instance Method Details
#authenticate_headers ⇒ Object
62 63 64 |
# File 'lib/easy_weixin/api.rb', line 62 def authenticate_headers {grant_type: @grant_type, appid: @app_id, secret: @app_secret} end |
#get_access_token ⇒ Object
获取access_token,如果启用redis则使用redis记录,如果没启用就每次进行一次查询。
16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
# File 'lib/easy_weixin/api.rb', line 16 def get_access_token if EasyWeixin.weixin_redis access_token = weixin_redis.get(@redis_key) if access_token access_token else refresh_token end else get_access_token_http end end |
#get_access_token_http ⇒ Object
31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/easy_weixin/api.rb', line 31 def get_access_token_http conn = Faraday.new(url: "https://api.weixin.qq.com") do |faraday| faraday.request :url_encoded faraday.adapter :typhoeus end response = conn.get("cgi-bin/token", authenticate_headers) token_hash = JSON.parse(response.body) access_token = token_hash["access_token"] end |
#refresh_token ⇒ Object
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
# File 'lib/easy_weixin/api.rb', line 43 def refresh_token get_access_token_http conn = Faraday.new(url: "https://api.weixin.qq.com") do |faraday| faraday.request :url_encoded faraday.adapter :typhoeus end response = conn.get("cgi-bin/token", authenticate_headers) token_hash = JSON.parse(response.body) access_token = token_hash["access_token"] expires_in = token_hash["expires_in"] weixin_redis.set(@redis_key, access_token) weixin_redis.expire(@redis_key, expires_in - 5) token_hash["access_token"] end |
#weixin_redis ⇒ Object
66 67 68 |
# File 'lib/easy_weixin/api.rb', line 66 def weixin_redis EasyWeixin.weixin_redis end |