class EasyWeixin::Api
Public Class Methods
new(app_id, app_secret)
click to toggle source
# 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
Public Instance Methods
authenticate_headers()
click to toggle source
# 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()
click to toggle source
获取access_token,如果启用redis则使用redis记录,如果没启用就每次进行一次查询。
# 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()
click to toggle source
# 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()
click to toggle source
# 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()
click to toggle source
# File lib/easy_weixin/api.rb, line 66 def weixin_redis EasyWeixin.weixin_redis end
Private Instance Methods
http_post(url, data)
click to toggle source
# File lib/easy_weixin/api.rb, line 72 def http_post(url, data) conn = Faraday.new(url: @weixin_api_url) do |faraday| faraday.request :url_encoded faraday.adapter :typhoeus end response = conn.post do |req| req.url url req.params['access_token'] = get_access_token req.headers['Content-Type'] = 'application/json' req.body = data end end