企业微信验证get和回调post传xml
2019-07-17 本文已影响0人
Aluha_f289
1、controller
/**
* 接收企业微信信息
* @param map
* @return
*/
@RequestMapping(value = "/pom-attendances/getWeChatInfo/", method = { RequestMethod.GET, RequestMethod.POST })
@Timed
public Map<String, Object> getWeChatInfo(HttpServletRequest request, HttpServletResponse response) {
Map<String, Object> mapResult = null;
pomAttendanceService.getWeChatInfo(request, response);
return mapResult;
}
2、实现类
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
/**
* 接收企业微信信息
* @param map
* @return
*/
@Override
public void getWeChatInfo(HttpServletRequest request, HttpServletResponse response) {
System.out.println("******************************");
//判断当前请求时GET还POST
boolean isGet = request.getMethod().toLowerCase().equals("get");
String sToken = applicationPomProperties.getsToken();
String sCorpID = applicationPomProperties.getCorpid();
String sEncodingAESKey = applicationPomProperties.getsEncodingAESKey();
PrintWriter out = null;
try {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID);
//获取企业微信验证url参数
String msg_signature = request.getParameter("msg_signature");
String timestamp = request.getParameter("timestamp");
String nonce = request.getParameter("nonce");
String echostr = request.getParameter("echostr");
out = response.getWriter();
String sEchoStr; // 需要返回的明文
if (isGet) {
//验证
sEchoStr = wxcpt.VerifyURL(msg_signature, timestamp,nonce, echostr);
System.out.println("verifyurl echostr: " + sEchoStr);
// 验证URL成功,将sEchoStr返回
out.print(sEchoStr);
//post请求
}else {
//获取post请求的数据
BufferedReader reader = request.getReader();
char[] buf = new char[512];
int len = 0;
StringBuffer contentBuffer = new StringBuffer();
while ((len = reader.read(buf)) != -1) {
contentBuffer.append(buf, 0, len);
}
String content = contentBuffer.toString();
if(content == null){
content = "";
}
//解密xml
System.out.println(content);
String sMsg = wxcpt.DecryptMsg(msg_signature, timestamp, nonce, content);
System.out.println(sMsg);
Map <String, String> map = new HashMap<>();
Document doc;
try {
doc = DocumentHelper.parseText(sMsg);
Element root = doc.getRootElement();
// 获取根节点下的所有元素
List children = root.elements();
// 循环所有子元素
if (children != null && children.size() > 0) {
for (int i = 0; i < children.size(); i++) {
Element child = (Element) children.get(i);
//xml转Map
map.put(child.getName(), child.getTextTrim());
}
}
String key = map.get("EventKey");
ZonedDateTime now = ZonedDateTime.now();
//获取审批人姓名,id
String checkUserName = map.get("FromUserName").toLowerCase();
} catch (DocumentException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (out != null) {
out.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}