Skip to content
lanrion edited this page Apr 8, 2015 · 3 revisions

目前提供的 单公众号多公众号两种应用场景可能并不适应某些特别的场景,以下为自定义场景方法:

修改配置

# Use this hook to configure WeixinRailsMiddleware bahaviors.
WeixinRailsMiddleware.configure do |config|
  config.custom_adapter = "MyWeixinAdapter"
end

实现对应的MyWeixinAdapter:

# encoding: utf-8
class MyWeixinAdapter < WeixinRailsMiddleware::WexinAdapter

  def check_weixin_legality
    return render_authorize_result if !is_weixin_secret_key_valid?
    super
  end

  def is_weixin_secret_key_valid?
    # 验证weixin_secret_key是否有效逻辑代码
  end

  def current_weixin_token
   # 获取weixin Token的逻辑代码
  end

  def current_weixin_public_account
    # 查询当前公众号的逻辑代码
  end

  def error_msg
    "#{__FILE__}:#{__LINE__}: Weixin secret string NotMatch."
  end
end

举一个简单的例子

# encoding: utf-8
class MyWeixinAdapter < WeixinRailsMiddleware::WexinAdapter
  attr_accessor :company

  def check_weixin_legality
    return render_authorize_result if !is_weixin_secret_key_valid?
    super
  end

  def is_weixin_secret_key_valid?
    # 验证 weixin_secret_key 是否为真实有效的
    current_weixin_public_account.config_data["weixin_secret_key"] == weixin_secret_key
  end

  def current_weixin_token
    # 获取微信和Token
    current_weixin_public_account.config_data["weixin_token"]
  end

  def current_weixin_public_account
    # 利用 weixin_secret_key 查找到company
    begin
      self.company   = Company.find_by(id: weixin_secret_key)
      wechat_channel = company.wechat_channel # 返回一个带有 config_data(Hash)的方法的渠道实例
    rescue => e
      Rails.logger.info(e)
      wechat_channel = OpenStruct.new(config_data: {})
    end
    wechat_channel
  end

  def error_msg
    "#{__FILE__}:#{__LINE__}: Weixin secret string NotMatch."
  end
end