JavaWeb接入微信公衆號

不囉嗦,直接上代碼:

//這裏注意要確保微信公衆號開發配置時的網址可以訪問到這個方法
@RequestMapping(value = "/setwechat")
    public void setWechat(HttpServletRequest request,HttpServletResponse response) throws Exception{

        response.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");
        String result = "";
        /* 不管在微信上進行什麼操作,都會有xml報文傳到綁定URL上 */
        Map res = showParams(request);
        Set<Map.Entry<Integer,String>> entrys = res.entrySet();
        System.out.println("setwechat微信獲取數據如下:");
        for(Map.Entry entry:entrys){
            String key = (String)entry.getKey();
            String value = (String)entry.getValue();
            System.out.println("key:"+key+" value:"+value);
        }
        if(request.getParameter("openid")==null){//接入校驗
            String timestamp = "", nonce = "", signature = "", echostr = "";
            timestamp = request.getParameter("timestamp");
            nonce = request.getParameter("nonce");
            signature = request.getParameter("signature");
            echostr = request.getParameter("echostr");
            boolean b = checkSignature(token,signature,timestamp,nonce);
            if(b){
                result = echostr;
            }
        }else{//非接入

        }

        PrintWriter pw = response.getWriter();
        pw.print(result);
        pw.close();
    }
//檢查是否合法
public static boolean checkSignature(String token,String signature, String timestamp,
                                         String nonce) {
       String[] arr = new String[] { token, timestamp, nonce };
        Arrays.sort(arr);
        StringBuilder content = new StringBuilder();
        for (int i = 0; i < arr.length; i++) {
            content.append(arr[i]);
        }
        MessageDigest md = null;
        String tmpStr = null;
        try {
            md = MessageDigest.getInstance("SHA-1");
            byte[] digest = md.digest(content.toString().getBytes());
            tmpStr = byteToStr(digest);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false;

    }


    private static String byteToStr(byte[] digest) {
        String strDigest = "";
        for (int i = 0; i < digest.length; i++) {
            strDigest += byteToHexStr(digest[i]);
        }
        return strDigest;
    }


    public static String byteToHexStr(byte b) {
        char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
                'B', 'C', 'D', 'E', 'F' };

        char[] tempArr = new char[2];
        tempArr[0] = Digit[(b >>> 4) & 0X0F];
        tempArr[1] = Digit[b & 0X0F];
        String s = new String(tempArr);
        return s;
    }
    //獲取所有request裏的數據,便於測試
    public static Map<String,Object> showParams(HttpServletRequest request) {
        Map<String,Object> map = new HashMap<String,Object>();
        Enumeration paramNames = request.getParameterNames();
        while (paramNames.hasMoreElements()) {
            String paramName = (String) paramNames.nextElement();

            String[] paramValues = request.getParameterValues(paramName);
            if (paramValues.length >0) {
                String paramValue = paramValues[0];
                if (paramValue.length() != 0) {
                    map.put(paramName, paramValue);
                }
            }
        }
        return map;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章