Commit 663720e8 by lanrion

refactor

parent b81efc95
...@@ -20,27 +20,32 @@ module WeixinAuthorize ...@@ -20,27 +20,32 @@ module WeixinAuthorize
def initialize(app_id, app_secret, redis_key=nil) def initialize(app_id, app_secret, redis_key=nil)
@app_id = app_id @app_id = app_id
@app_secret = app_secret @app_secret = app_secret
@expired_at = (expired_at.to_i || Time.now.to_i) @expired_at = Time.now.to_i
@redis_key = (redis_key || "weixin_" + app_id) @redis_key = (redis_key || "weixin_" + app_id)
end end
# return token # return token
def get_access_token def get_access_token
authenticate if token_expired? authenticate if token_expired?
if !is_weixin_redis_blank?
self.access_token = weixin_redis.hget(redis_key, "access_token")
self.expired_at = weixin_redis.hget(redis_key, "expired_at")
end
@access_token @access_token
end end
# authenticate access_token # authenticate access_token
def authenticate def authenticate
if weixin_redis.nil? if is_weixin_redis_blank?
http_get_access_token http_get_access_token
else else
puts "authenticate_with_redis"
authenticate_with_redis authenticate_with_redis
end end
end end
def token_expired? def token_expired?
if weixin_redis.nil? if is_weixin_redis_blank?
# 如果当前token过期时间小于现在的时间,则重新获取一次 # 如果当前token过期时间小于现在的时间,则重新获取一次
@expired_at <= Time.now.to_i @expired_at <= Time.now.to_i
else else
...@@ -51,14 +56,9 @@ module WeixinAuthorize ...@@ -51,14 +56,9 @@ module WeixinAuthorize
private private
def authenticate_with_redis def authenticate_with_redis
if token_expired? http_get_access_token
http_get_access_token weixin_redis.hmset(redis_key, :access_token, access_token, :expired_at, expired_at)
weixin_redis.hmset(redis_key, :access_token, access_token, :expired_at, expired_at) weixin_redis.expireat(redis_key, expired_at.to_i-10) # 提前10秒超时
weixin_redis.expireat(redis_key, expired_at.to_i-10) # 提前10秒超时
else
self.access_token = weixin_redis.hget(redis_key, "access_token")
self.expired_at = weixin_redis.hget(redis_key, "expired_at")
end
end end
def http_get_access_token def http_get_access_token
...@@ -109,5 +109,9 @@ module WeixinAuthorize ...@@ -109,5 +109,9 @@ module WeixinAuthorize
@redis ||= WeixinAuthorize.config.redis @redis ||= WeixinAuthorize.config.redis
end end
def is_weixin_redis_blank?
weixin_redis.nil?
end
end end
end end
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment