昨天首次进行微信企业号回调模式的配置,一直卡在url验证上,刚开始的签名字符串验证还算简单,将微信企业号发生过来的4个参数中的timestamp, nonce, echostr还有自己验证url时填的Token进行sha1加密生产签名字符串,然后与那4个参数中的msg_signature进行比对,如果正确则说明我们现在收到的请求来自于自己配置的微信企业号。可以两种写法:
(1)
require 'digest/sha1'
class M::TasksController < ApplicationController
def auth_wechat
if check_signature?(params[:signature], params[:timestamp], params[:nonce], params[echostr])
#继续往下走
end
end
def check_signature?(signature, timestamp, nonce, echostr)
Digest::SHA1.hexdigest([timestamp, nonce, @@token, echostr].sort.join) == signature
end
end
(2)
def valid_msg_signature?(params)
timestamp = params[:timestamp]
nonce = params[:nonce]
echo_str = params[:echostr]
msg_signature = params[:msg_signature]
sort_params = [qy_token, timestamp, nonce, echo_str].sort.join
current_signature = Digest::SHA1.hexdigest(sort_params)
Rails.logger.info("current_signature: #{current_signature} ")
current_signature == msg_signature
end