Skip to content
lanrion edited this page May 12, 2015 · 2 revisions

RestClient 扩展配置

weixin_authorize 对此项配置rest_client_options默认配置为: {timeout: 2, open_timeout: 3, verify_ssl: true}

如果需要对RestClient HTTP请求做扩展配置,根据如下配置:

WeixinAuthorize.configure do |config|
  # 此处要注意,key 必须是Symbol(符号),否则RestClient不会识别。
  # 原因查看如下:https://github.com/rest-client/rest-client/blob/master/lib%2Frestclient%2Frequest.rb#L106
  config.rest_client_options = {timeout: 1, open_timeout: 1, verify_ssl: true}
end

可配置项,请见:https://github.com/rest-client/rest-client/blob/master/lib%2Frestclient%2Frequest.rb#L17 测试示例: https://github.com/lanrion/weixin_authorize/blob/master/spec%2Fspec_helper.rb#L58

使用Redis做 access_token、jsticket的存储方案

  • 添加 redis-namespace 到你的 Gemfile
# Adds a Redis::Namespace class which can be used to namespace calls to Redis. This is useful when using a single instance of Redis with multiple, different applications.
# http://github.com/resque/redis-namespace
gem "redis-namespace"
  • 添加被始化文件:config/initializers/weixin_authorize.rb
# 这里修改成你的的命名空间。
namespace = "app_name_weixin:weixin_authorize"
redis = Redis.new(:host => "127.0.0.1", :port => "6379", :db => 15)

# 每次重启时,会把当前的命令空间所有的access_token 清除掉。
exist_keys = redis.keys("#{namespace}:*")
exist_keys.each{|key|redis.del(key)}

# Give a special namespace as prefix for Redis key, when your have more than one project used weixin_authorize, this config will make them work fine.
redis = Redis::Namespace.new("#{namespace}", :redis => redis)

WeixinAuthorize.configure do |config|
  config.redis = redis
end

注意,如果不做上述的redis配置,则不会使用Redis来存放access_token,直接存在当前实例中

  • 另外一个可选项是,你可以指定存储access_token的key值,多个公众账号,建议最好用id值即可(插件会进行加密转换),保持唯一性。

没有特别的需求,不建议使用。

$client ||= WeixinAuthorize::Client.new(ENV["APPID"], ENV["APPSECRET"], "your_store_key")

特别注意事项

access_token 每次请求后,上一次的access_token会失效。所以如果存储在Redis中,但同时又在另一边重新跑了一次请求access_token的操作,那么保存在Redis的access_token会失效,在开发环境下,restart你的Rails Server即可,清除所有access_token的代码如下:

# 每次重启时,会把当前的命令空间所有的access_token 清除掉。
exist_keys = redis.keys("#{namespace}:*")
exist_keys.each{|key|redis.del(key)}