微信公众号服务器配置验证实现

在微信公众号设置开发模式,需要调用后台服务器进行验证的伪代码实现:

微信公众号服务器配置验证实现

/**
 * 微信服务器配置验证方法
 *
 * @param request
* @param response
* @return
*/
private String access(HttpServletRequest request, HttpServletResponse response) {
    String signature = request.getParameter("signature");
    String timestamp = request.getParameter("timestamp");
    String nonce = request.getParameter("nonce");
    String echostr = request.getParameter("echostr");
    logger.info("微信请求的echostr:{}", echostr);
    // 将token、timestamp、nonce三个参数进行字典序排序
List<String> paramList = new ArrayList<String>();
    paramList.add(token);
    paramList.add(timestamp);
    paramList.add(nonce);
    SortUtils.arrayListSortByDict(paramList);
    logger.info("timestamp、nonce、token三个参数进行字典序排序:{}", JSON.toJSONString(paramList));
    // 将三个参数字符串拼接成一个字符串进行sha1加密
String result = "";
    for (String str : paramList) {
        result += str;
    }
    String resultPass = DigestUtils.sha1Hex(result);
    // 加密后的字符串可与signature对比,标识该请求来源于微信
if (resultPass.equals(signature)) {
        logger.info("返回的echostr:{}", echostr);
        return echostr;
    }
    logger.info(String.format("微信请求验证失败!token:[%s],本服务器signature:[%s],微信signature:[%s]", token, resultPass, signature));
    return "";
}


public class SortUtils {
   /**
    * 根据字典排序
    * 
    * @param sortList
*/
public static void arrayListSortByDict(List<String> sortList) {
      Collections.sort(sortList, new RealizeComparator());
   }
}


猜你喜欢

转载自wangmengbk.iteye.com/blog/2357732