昨天首次進行微信企業號回調模式的配置,一直卡在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