首页 > 学院 > 开发设计 > 正文

微信URL有效性验证

2019-11-14 21:46:23
字体:
来源:转载
供稿:网友
微信URL有效性验证

1、填写配置项:填写 URL 和 Token 点击提交按钮 微信服务器会以get方式请求到所指定的URL,在此URL中进行URL的有效性验证

2、URL有效性的验证:

 1 if ("get".equalsIgnoreCase(request.getMethod())) { 2                 StringBuffer sb = new StringBuffer(); 3                 // 从数据库找到该token或者设置token为 固定值 4                 String token = ""; 5                 //1. 将token、timestamp、nonce三个参数进行字典序排序 6                 //2. 将三个参数字符串拼接成一个字符串进行sha1加密 7                 //3. 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信 8                 //若确认此次GET请求来自微信服务器,请原样返回echostr参数内容,则接入生效,成为开发者成功,否则接入失败。 9                 String signature = request.getParameter("signature");10                 String timestamp = request.getParameter("timestamp");11                 String nonce = request.getParameter("nonce");12                 String echostr = request.getParameter("echostr");    13                 if(!WeixinUtil.checkSignature(signature,token,timestamp,nonce))14                 {15                     echostr = "";            16                 }        17                 sb.append(echostr);18                 this.inputStream = new ByteArrayInputStream(sb.toString().getBytes("UTF-8"));19             }

/**     * 检查是否为合格的请求     * @param signature     * @param token     * @param timestamp     * @param nonce     * @return true:合格<br/>     *        false:不合格     */    public static boolean checkSignature(String signature, String token,String timestamp, String nonce) {        if (signature == null || token == null || timestamp == null || nonce == null) {            return false;        }        List<String> tmpArr = new ArrayList<String>();        tmpArr.add(token);        tmpArr.add(timestamp);        tmpArr.add(nonce);        Collections.sort(tmpArr);        String tmpStr = tmpArr.get(0) + tmpArr.get(1) + tmpArr.get(2);        try {            MessageDigest md;            md = MessageDigest.getInstance("SHA-1");            md.update(tmpStr.getBytes());            tmpStr = getFormattedText(md.digest());        } catch (NoSuchAlgorithmException e) {            e.PRintStackTrace();        }        if (tmpStr.equals(signature)) {            return true;        } else {            return false;        }    }

 1 /** 2      * 格式化 3      * @param bytes 4      * @return 5      */ 6     public static String getFormattedText(byte[] bytes) { 7         int len = bytes.length; 8         StringBuilder buf = new StringBuilder(len * 2); 9         for (int j = 0; j < len; j++) {10             buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);11             buf.append(HEX_DIGITS[bytes[j] & 0x0f]);12         }13         return buf.toString();14     }


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表