package com.wx.demo;
import com.qq.weixin.mp.aes.WXBizMsgCrypt;
import com.wx.demo.wx.ElementUtils;
import com.wx.demo.wx.FormatUtils;
import com.wx.demo.wx.model.InMsgEntity;
import com.wx.demo.wx.utils.WeiXinParamesUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Controller
public class UserController {
public static Logger logger = org.slf4j.LoggerFactory.getLogger(UserController.class);
@RequestMapping("/hello")
@ResponseBody
public String hello(@RequestBody InMsgEntity msg,@RequestParam(name = "msg_signature") String signature, String timestamp, String nonce, String echostr) {
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = servletRequestAttributes.getRequest();
HttpServletResponse response = servletRequestAttributes.getResponse();
logger.info("request.getRequestURL()---" + request.getRequestURL());
logger.info("signature---" + signature);
logger.info("timestamp---" + timestamp);
logger.info("nonce---" + nonce);
logger.info("echostr---" + echostr);
//回调key值
String sEchoStr = null;
String contacts_token = WeiXinParamesUtil.token;
String contacts_encodingaeskey = WeiXinParamesUtil.encodingAESKey;
String corpId = WeiXinParamesUtil.corpId;
try {
WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(contacts_token,contacts_encodingaeskey,corpId);
if(echostr != null){
sEchoStr = wxcpt.VerifyURL(signature,timestamp,nonce,echostr);
if(StringUtils.isBlank(sEchoStr)){
logger.error("URL验证失败");
}else {
logger.info("URL验证成功");
}
logger.info(sEchoStr);
}
logger.info("msg---" + msg);
String sReqData = FormatUtils.getReqData(msg);
logger.info("sReqData---" + sReqData);
if(!sReqData.equals("")){
String sMsg = wxcpt.DecryptMsg(signature, timestamp, nonce, sReqData);
ElementUtils element = new ElementUtils(sMsg);
String msgType = element.get("MsgType");
String content = "";
switch (msgType){
/**
* 事件类型处理
*/
case "event":content = "触发事件";break;
/**
* 文字消息处理:这里是将用户发送的消息原样返回
*/
case "text": content = element.get("Content");break;
default:break;
}
String sRespData = FormatUtils.getTextRespData(content);
String sEncryptMsg = wxcpt.EncryptMsg(sRespData, timestamp, nonce);
logger.info("sEncryptMsg..." + sEncryptMsg);
}
}catch (Exception e){
logger.error("企业微信回调url验证错误",e);
}
return sEchoStr;
}
}
1、企业微信配置回调接口:localhost:8080/hello
2、注意,回调接口中的参数
后台配置验证时,需要4个参数
企业微信中信息变更时,会多传过来一个msg,最后一个参数是null