一、前言
微信企業號應用中,有兩種模式,一種是普通模式,這種模式只能進行簡單網頁鏈接,以及發送固定的消息。為了可以讓企業號的用戶更好的與應用交互,微信提供了回調模式,這種回調模式的可以將用戶發送給微信的信息,轉發到用戶提供的一個回調接口上,該接口解析用戶發送過來的信息,解析后進行相應,而且回調模式中,可以調用的東西不少,掃碼,圖片,視頻,地理位置信息等。
在應用的模式下,選擇回調模式,之后,需要設置3個參數(1.回調接口URL;2.token;3.ASESKey),URL就是提供的回調接口,微信會把用戶提供的信息,轉發到該接口來。我們這里用的url為http://m.xxx.com:10000/WeiXin/MessageInterface/。接口的驗證是采用http Get的方式,接口獲取消息是采用Post的方式。而且要設置回調模式,必須先實現驗證接口。
這對接口的驗證,微信提供了相應的開發包,有c#專用的,開發包的主要作用就是進行簽名的驗證和加密解密。
接口驗證代碼如下
public string MessageInterface() { string signature = Request.QueryString["msg_signature"]; string timestamp = Request.QueryString["timestamp"]; string nonce = Request.QueryString["nonce"]; string echostr = Request.QueryString["echostr"]; //Careysoft.Basic.Public.Log.LogWrite("111"); if (Request.HttpMethod.ToUpper() == "GET") { string decryptEchoString = ""; if (Careysoft.WeiXin.Public.WeiXinFunction.CheckSignature(m_Token, signature, timestamp, nonce, m_Corpid, m_EncodingAESKey, echostr, ref decryptEchoString)) { if (!string.IsNullOrEmpty(decryptEchoString)) { return decryptEchoString; } } } }
m_Token為回調模式中設置的Token,m_Corpid為企業號微信Id,m_EncodingAESKey為回調模式中設置的AESKey,其余的參數為回調模式傳遞過來的參數。
下面是 CheckSignature 函數:
public static bool CheckSignature(string token, string signature, string timestamp, string nonce, string corpId, string encodingAESKey, string echostr, ref string retEchostr) { WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(token, encodingAESKey, corpId); int result = wxcpt.VerifyURL(signature, timestamp, nonce, echostr, ref retEchostr); if (result != 0) { return false; } return true; //ret==0表示驗證成功,retEchostr參數表示明文,用戶需要將retEchostr作為get請求的返回參數,返回給企業號。 // HttpUtils.SetResponse(retEchostr); }
其中,WXBizMsgCrypt為微信平台回調接口開發包,大家下載引用過來就好。
好的,回調驗證接口就是這樣,有了這個,就可以把應用模式設置為回調模式了!
下一節,我們將試着從回調接口接收用戶發送的信息,並對用戶進行回復。
請看.net之微信企業號開發(四) 回調模式的接口 信息的接收和發送