首先需要多些网上的大神
链接:https://bbs.csdn.net/topics/390991193 ;
https://blog.csdn.net/sinat_22878395/article/details/69258165 ;
https://blog.csdn.net/hanghangde/article/details/51028755 ;
https://bbs.csdn.net/topics/391878796
本文只是将这几个大神的攻略进行排列组合。
Controller类
/**
*@author TEDYYAN
* @throws DocumentException
* @throws IOException
* @throws AesException
*@注释:公众号用户互动
*/
@RequestMapping(value="/extensionInsurance/weiXinInteraction",produces = {"text/plain;charset=UTF-8"})
@ResponseBody
public String weiXinInteraction(HttpServletRequest request) throws IOException, DocumentException, AesException{
String msgSignature = request.getParameter("signature");
String msgTimestamp = request.getParameter("timestamp");
String msgNonce = request.getParameter("nonce");
String echostr = request.getParameter("echostr");
if (WXPublicUtils.verifyUrl(msgSignature, msgTimestamp, msgNonce,sysConfigService.getValue("sacon.app.token"))) {
LOG.info("---------------------------------------------公众号成功连接!");
LOG.info("msgNonce"+msgNonce+" msgTimestamp"+msgTimestamp+" msgNonce"+msgNonce+" echostr"+echostr);
return echostr;
}
LOG.info("msgNonce"+msgNonce+" msgTimestamp"+msgTimestamp+" msgNonce"+msgNonce+" echostr"+echostr+"公众号成功失败!");
return null;
}
WXPublicUtils 类
package com.dido.common.util;
import com.dido.common.payment.weixin.WeiXinConfig;
public class WXPublicUtils {
/**
* 验证Token
* @param msgSignature 签名串,对应URL参数的signature
* @param timeStamp 时间戳,对应URL参数的timestamp
* @param nonce 随机串,对应URL参数的nonce
*
* @return 是否为安全签名
* @throws AesException 执行失败,请查看该异常的错误码和具体的错误信息
*/
public static boolean verifyUrl(String msgSignature, String timeStamp, String nonce,String token)
throws AesException {
// 这里的 WXPublicConstants.TOKEN 填写你自己设置的Token就可以了
String signature = SHA1.getSHA1(token, timeStamp, nonce);
if (!signature.equals(msgSignature)) {
throw new AesException(AesException.ValidateSignatureError);
}
return true;
}
}
AesException 类
package com.dido.common.util;
@SuppressWarnings("serial")
public class AesException extends Exception {
public final static int OK = 0;
public final static int ValidateSignatureError = -40001;
public final static int ParseXmlError = -40002;
public final static int ComputeSignatureError = -40003;
public final static int IllegalAesKey = -40004;
public final static int ValidateAppidError = -40005;
public final static int EncryptAESError = -40006;
public final static int DecryptAESError = -40007;
public fin