微信开发

用到的gem:weixin_authorize/weixin_rails_middleware/(缓存redis) 原理都是封装微信的后台API接口。

微信开发

模板消息

用Rails搭建微信公众平台API

微信开放平台开发——网页微信扫码登录

步骤

* 获取Appid、APPSecret

通过缓存来存储access_token
# 这里修改成你的的命名空间。
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


重写WeixinAuthorize:
module WeixinAuthorize
  class Client
    def http_get(url, url_params={}, endpoint="plain")
      url_params = url_params.merge(access_token_param)
      result = WeixinAuthorize.http_get_without_token(url, url_params, endpoint)
      if result.code == 40001
        self.token_store.refresh_token
        url_params = url_params.merge(access_token_param)
        result = WeixinAuthorize.http_get_without_token(url, url_params, endpoint)
      end
      result
    end

    def http_post(url, post_body={}, url_params={}, endpoint="plain")
      url_params = access_token_param.merge(url_params)
      result = WeixinAuthorize.http_post_without_token(url, post_body, url_params, endpoint)
      if result.code == 40001
        self.token_store.refresh_token
        url_params = url_params.merge(access_token_param)
        result = WeixinAuthorize.http_post_without_token(url, post_body, url_params, endpoint)
      end
      result
    end
  end
end

$client ||= WeixinAuthorize::Client.new(Settings.app_id, Settings.app_secret)  # 单公众号
执行 rails generate weixin_rails_middleware:install, 会生成:
config/initializers/weixin_rails_middleware.rb
app/decorators/controllers/weixin_rails_middleware/weixin_controller_decorator.rb
  • weixin_controller_decorator.rb