wechat gem是一个很优秀的gem, 使用这个gem使rails开发者可以迅速的接入微信服务号/订阅号。
我这里遇到一个需求,是网站需要支持多个服务号,经过一系列研究,觉得还是后期的hack做法比较简单,现分享此方法。
- 创建一个Model,WechatApp,此model需要包含原有wechat.yml中的属性。
-
在initializers中加入wechat.rb,内容如下
module Wechat
def self.config(account = :default)
if account == :default
Wechat::ApiLoader.config(account)
else
app = WechatApp.find account.to_s
value = { appid: app.appid,
secret: app.secret,
corpid: nil,
corpsecret: nil,
agentid: nil,
token: app.token,
access_token: app.access_token,
encrypt_mode: app.encrypt_mode,
timeout: 120,
skip_verify_ssl: app.skip_verify_ssl,
encoding_aes_key: app.encoding_aes_key,
jsapi_ticket: app.jsapi_ticket,
trusted_domain_fullname: app.trusted_domain_fullname }
OpenStruct.new value
end
end
def self.api(account = :default)
@wechat_apis ||= {}
if account == :default
@wechat_apis[account.to_sym] ||= Wechat::ApiLoader.with(account: account)
else
@wechat_apis[account.to_sym] ||= Helper.new.send(:load_controller_wechat, account)
end
end
class Helper
include ActionController::WechatResponder
attr_accessor :wechat_api_client, :wechat_cfg_account, :token, :appid, :corpid, :agentid, :encrypt_mode, :timeout,
:skip_verify_ssl, :encoding_aes_key, :trusted_domain_fullname, :oauth2_cookie_duration
end
end
- 在controller中加一个concern, 我这里叫Wechat::Hack
module Wechat::Hack
extend ActiveSupport::Concern
included do
before_action :set_wechat_client
end
def set_wechat_client
appid = params[:appid] || session[:appid]
if appid.to_s.size > 0
app = WechatApp.find appid
@app = app
session[:account] = app.id.to_s.to_sym
Thread.current[:account] = app.id.to_s.to_sym
end
end
module ClassMethods
def appid
Wechat.config(Thread.current[:account] || :default).appid
end
###
#此处 省略几十行
###
end
end
- 在responses_controller中引入此gem
class Wechat::ResponsesController < ActionController::Base
wechat_responder
include Wechat::Hack
end
以subscribe 为例
on :event, with: "subscribe" do |request, e|
wechat_user = wechat.user request[:FromUserName]
wechat_app = WechatApp.find session[:account].to_s
welcome_text = get_text_from_wechat_app(wechat_app)
request.reply.text(welcome_text)
end
WechatApi的接入与此类似,但需要更多几个方法hack.