微信企業號回調模式配置講解 Java Servlet+Struts2版本 echostr校驗失敗解決

異常java.security.InvalidKeyException:illegal Key Size 也就是 echostr校驗失敗,請您檢查是否正確解密並輸出明文echostr 這個錯誤html

企業微信登錄地址http://qy.weixin.qq.com/java

配置成功之後node

 

Servlet 代碼微信

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 微信加密簽名
        String msg_signature = request.getParameter("msg_signature");
        // 時間戳
        String timestamp = request.getParameter("timestamp");
        // 隨機數
        String nonce = request.getParameter("nonce");
        // 隨機字符串
        String echostr = request.getParameter("echostr");
        // 打印請求地址
        System.out.println("request=" + request.getRequestURL());
        // 流
        PrintWriter out = response.getWriter();
        // 經過檢驗signature對請求進行校驗,若校驗成功則原樣返回echostr,表示接入成功,不然接入失敗
        String result = null;
        try {
            WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(ParamesAPI.token, ParamesAPI.encodingAESKey, ParamesAPI.corpId);
            // 驗證URL函數
            result = wxcpt.VerifyURL(msg_signature, timestamp, nonce, echostr);
        } catch (AesException e) {
            e.printStackTrace();
        }
        if (result == null) {
            // result爲空,賦予token
            result = ParamesAPI.token;
        }
        // 拼接請求參數
        String str = msg_signature + " " + timestamp + " " + nonce + " " + echostr;
        // 打印參數+地址+result
        System.out.println("Exception:" + result + " " + request.getRequestURL() + " " + "FourParames:" + str);
        String info = "Exception:" + result + " " + request.getRequestURL() + " " + "FourParames:" + str;
        log.info(info);
        out.print(result);
        out.close();
        out = null;
    }

 

官方回調頁面的代碼oracle

import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import javax.xml.parsers.DocumentBuilderFactory;
import com.qq.weixin.mp.aes.WXBizMsgCrypt;

public class Sample {

    public static void main(String[] args) throws Exception {
        String sToken = "QDG6eK";
        String sCorpID = "wx5823bf96d3bd56c7";
        String sEncodingAESKey = "jWmYm7qr5nMoAUwZRjGtBxmz3KA1tkAj3ykkR6q2B2C";

        WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID);
        /*
        ------------使用示例一:驗證回調URL---------------
        *企業開啓回調模式時,企業號會向驗證url發送一個get請求 
        假設點擊驗證時,企業收到相似請求:
        * GET /cgi-bin/wxpush?msg_signature=5c45ff5e21c57e6ad56bac8758b79b1d9ac89fd3&timestamp=1409659589&nonce=263014780&echostr=P9nAzCzyDtyTWESHep1vC5X9xho%2FqYX3Zpb4yKa9SKld1DsH3Iyt3tP3zNdtp%2B4RPcs8TgAE7OaBO%2BFZXvnaqQ%3D%3D 
        * HTTP/1.1 Host: qy.weixin.qq.com

        接收到該請求時,企業應        1.解析出Get請求的參數,包括消息體簽名(msg_signature),時間戳(timestamp),隨機數字串(nonce)以及公衆平臺推送過來的隨機加密字符串(echostr),
        這一步注意做URL解碼。
        2.驗證消息體簽名的正確性 
        3. 解密出echostr原文,將原文看成Get請求的response,返回給公衆平臺
        第2,3步能夠用公衆平臺提供的庫函數VerifyURL來實現。

        */
        // 解析出url上的參數值以下:
        // String sVerifyMsgSig = HttpUtils.ParseUrl("msg_signature");
        String sVerifyMsgSig = "5c45ff5e21c57e6ad56bac8758b79b1d9ac89fd3";
        // String sVerifyTimeStamp = HttpUtils.ParseUrl("timestamp");
        String sVerifyTimeStamp = "1409659589";
        // String sVerifyNonce = HttpUtils.ParseUrl("nonce");
        String sVerifyNonce = "263014780";
        // String sVerifyEchoStr = HttpUtils.ParseUrl("echostr");
        String sVerifyEchoStr = "P9nAzCzyDtyTWESHep1vC5X9xho/qYX3Zpb4yKa9SKld1DsH3Iyt3tP3zNdtp+4RPcs8TgAE7OaBO+FZXvnaqQ==";
        String sEchoStr; //須要返回的明文
        try {
            sEchoStr = wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp,
                    sVerifyNonce, sVerifyEchoStr);
            System.out.println("verifyurl echostr: " + sEchoStr);
            // 驗證URL成功,將sEchoStr返回
            // HttpUtils.SetResponse(sEchoStr);
        } catch (Exception e) {
            //驗證URL失敗,錯誤緣由請查看異常
            e.printStackTrace();
        }

        /*
        ------------使用示例二:對用戶回覆的消息解密---------------
        用戶回覆消息或者點擊事件響應時,企業會收到回調消息,此消息是通過公衆平臺加密以後的密文以post形式發送給企業,密文格式請參考官方文檔
        假設企業收到公衆平臺的回調消息以下:
        POST /cgi-bin/wxpush? msg_signature=477715d11cdb4164915debcba66cb864d751f3e6&timestamp=1409659813&nonce=1372623149 HTTP/1.1
        Host: qy.weixin.qq.com
        Content-Length: 613
        <xml>        <ToUserName><![CDATA[wx5823bf96d3bd56c7]]></ToUserName><Encrypt><![CDATA[RypEvHKD8QQKFhvQ6QleEB4J58tiPdvo+rtK1I9qca6aM/wvqnLSV5zEPeusUiX5L5X/0lWfrf0QADHHhGd3QczcdCUpj911L3vg3W/sYYvuJTs3TUUkSUXxaccAS0qhxchrRYt66wiSpGLYL42aM6A8dTT+6k4aSknmPj48kzJs8qLjvd4Xgpue06DOdnLxAUHzM6+kDZ+HMZfJYuR+LtwGc2hgf5gsijff0ekUNXZiqATP7PF5mZxZ3Izoun1s4zG4LUMnvw2r+KqCKIw+3IQH03v+BCA9nMELNqbSf6tiWSrXJB3LAVGUcallcrw8V2t9EL4EhzJWrQUax5wLVMNS0+rUPA3k22Ncx4XXZS9o0MBH27Bo6BpNelZpS+/uh9KsNlY6bHCmJU9p8g7m3fVKn28H3KDYA5Pl/T8Z1ptDAVe0lXdQ2YoyyH2uyPIGHBZZIs2pDBS8R07+qN+E7Q==]]></Encrypt>
        <AgentID><![CDATA[218]]></AgentID>
        </xml>

        企業收到post請求以後應該        1.解析出url上的參數,包括消息體簽名(msg_signature),時間戳(timestamp)以及隨機數字串(nonce)
        2.驗證消息體簽名的正確性。
        3.將post請求的數據進行xml解析,並將<Encrypt>標籤的內容進行解密,解密出來的明文便是用戶回覆消息的明文,明文格式請參考官方文檔
        第2,3步能夠用公衆平臺提供的庫函數DecryptMsg來實現。
        */
        // String sReqMsgSig = HttpUtils.ParseUrl("msg_signature");
        String sReqMsgSig = "477715d11cdb4164915debcba66cb864d751f3e6";
        // String sReqTimeStamp = HttpUtils.ParseUrl("timestamp");
        String sReqTimeStamp = "1409659813";
        // String sReqNonce = HttpUtils.ParseUrl("nonce");
        String sReqNonce = "1372623149";
        // post請求的密文數據
        // sReqData = HttpUtils.PostData();
        String sReqData = "<xml><ToUserName><![CDATA[wx5823bf96d3bd56c7]]></ToUserName><Encrypt><![CDATA[RypEvHKD8QQKFhvQ6QleEB4J58tiPdvo+rtK1I9qca6aM/wvqnLSV5zEPeusUiX5L5X/0lWfrf0QADHHhGd3QczcdCUpj911L3vg3W/sYYvuJTs3TUUkSUXxaccAS0qhxchrRYt66wiSpGLYL42aM6A8dTT+6k4aSknmPj48kzJs8qLjvd4Xgpue06DOdnLxAUHzM6+kDZ+HMZfJYuR+LtwGc2hgf5gsijff0ekUNXZiqATP7PF5mZxZ3Izoun1s4zG4LUMnvw2r+KqCKIw+3IQH03v+BCA9nMELNqbSf6tiWSrXJB3LAVGUcallcrw8V2t9EL4EhzJWrQUax5wLVMNS0+rUPA3k22Ncx4XXZS9o0MBH27Bo6BpNelZpS+/uh9KsNlY6bHCmJU9p8g7m3fVKn28H3KDYA5Pl/T8Z1ptDAVe0lXdQ2YoyyH2uyPIGHBZZIs2pDBS8R07+qN+E7Q==]]></Encrypt><AgentID><![CDATA[218]]></AgentID></xml>";

        try {
            String sMsg = wxcpt.DecryptMsg(sReqMsgSig, sReqTimeStamp, sReqNonce, sReqData);
            System.out.println("after decrypt msg: " + sMsg);
            // TODO: 解析出明文xml標籤的內容進行處理
            // For example:
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            StringReader sr = new StringReader(sMsg);
            InputSource is = new InputSource(sr);
            Document document = db.parse(is);

            Element root = document.getDocumentElement();
            NodeList nodelist1 = root.getElementsByTagName("Content");
            String Content = nodelist1.item(0).getTextContent();
            System.out.println("Content:" + Content);
            
        } catch (Exception e) {
            // TODO
            // 解密失敗,失敗緣由請查看異常
            e.printStackTrace();
        }

    /*
        ------------使用示例三:企業回覆用戶消息的加密---------------
        企業被動回覆用戶的消息也須要進行加密,而且拼接成密文格式的xml串。
        假設企業須要回覆用戶的明文以下:
        <xml>
        <ToUserName><![CDATA[mycreate]]></ToUserName>
        <FromUserName><![CDATA[wx5823bf96d3bd56c7]]></FromUserName>
        <CreateTime>1348831860</CreateTime>
        <MsgType><![CDATA[text]]></MsgType>
        <Content><![CDATA[this is a test]]></Content>
        <MsgId>1234567890123456</MsgId>
        <AgentID>128</AgentID>
        </xml>

        爲了將此段明文回覆給用戶,企業應:            1.本身生成時間時間戳(timestamp),隨機數字串(nonce)以便生成消息體簽名,也能夠直接用從公衆平臺的post url上解析出的對應值。
        2.將明文加密獲得密文。    3.用密文,步驟1生成的timestamp,nonce和企業在公衆平臺設定的token生成消息體簽名。            4.將密文,消息體簽名,時間戳,隨機數字串拼接成xml格式的字符串,發送給企業。
        以上2,3,4步能夠用公衆平臺提供的庫函數EncryptMsg來實現。
        */
        String sRespData = "<xml><ToUserName><![CDATA[mycreate]]></ToUserName><FromUserName><![CDATA[wx5823bf96d3bd56c7]]></FromUserName><CreateTime>1348831860</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[this is a test]]></Content><MsgId>1234567890123456</MsgId><AgentID>128</AgentID></xml>";
        try{
            String sEncryptMsg = wxcpt.EncryptMsg(sRespData, sReqTimeStamp, sReqNonce);
            System.out.println("after encrypt sEncrytMsg: " + sEncryptMsg);
            // 加密成功
            // TODO:
            // HttpUtils.SetResponse(sEncryptMsg);
        }
        catch(Exception e)
        {
            e.printStackTrace();
            // 加密失敗
        }

    }
}

來重點了:echostr校驗失敗,請您檢查是否正確解密並輸出明文echostrdom

有可能會遇到這樣的錯誤。你們就百度搜索也找不到。由於官方提供瞭解決方案。因此,仔細函數

看官方提供的驗證加密的源代碼是有做用的。post

 

說明:異常java.security.InvalidKeyException:illegal Key Size的解決方案

 * 在官方網站下載JCE無限制權限策略文件(JDK7的下載地址:
 *   http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html
 * 下載後解壓,能夠看到local_policy.jar和US_export_policy.jar以及readme.txt
 * 若是安裝了JRE,將兩個jar文件放到%JRE_HOME%\lib\security目錄下覆蓋原來的文件
 * 若是安裝了JDK,將兩個jar文件放到%JDK_HOME%\jre\lib\security目錄下覆蓋原來文件
網站

 

‍Struts2ui

    public String execute() throws Exception {
        // 將請求、響應的編碼均設置爲UTF-8(防止中文亂碼)
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpServletResponse response = ServletActionContext.getResponse();
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        //微信加密簽名
        String msg_signature = request.getParameter("msg_signature");
        // 時間戳
        String timestamp = request.getParameter("timestamp");
        // 隨機數
        String nonce = request.getParameter("nonce");
        // 隨機字符串
        String echostr = request.getParameter("echostr");
        PrintWriter out = response.getWriter();
        String result = null;
        // 請求校驗
        try{
            WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(ParamesAPI.token, ParamesAPI.encodingAESKey, ParamesAPI.corpId);
            //驗證URL函數
            result = wxcpt.VerifyURL(msg_signature, timestamp, nonce, echostr);
        
            if(result==null){
                result = ParamesAPI.token;
            }else{
                out.print(result);
            }
        }catch (Exception e) {
            e.printStackTrace();
            log.error("請求錯誤,稍後再試",e);
        }
        out.close();
        out = null;
        return null;
      }

 

我的微博 http://weibo.com/zxshuai319 

我的博客 http://my.oschina.net/xshuai/blog 

公開QQ  783021975

我的聯盟 http://www.bengbeng.com/?sid=687095  

相關文章
相關標籤/搜索