package com.test;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.test.util.MessageUtil;
/**
* 核心请求处理类
* @author V型知识库 www.vxzsk.com
* linfanhehe@163.com
*/
public class WeChatServlet extends HttpServlet {
private static final long serialVersionUID = 1508798736675904038L;
/**
* 确认请求来自微信服务器
*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 微信加密签名
String signature = request.getParameter("signature");
System.out.println("微信加密签名signature:-----------------------"+signature);
// 时间戳
String timestamp = request.getParameter("timestamp");
System.out.println("时间戳timestamp:-----------------------"+timestamp);
// 随机数
String nonce = request.getParameter("nonce");
System.out.println("随机数nonce:-----------------------"+nonce);
// 随机字符串
String echostr = request.getParameter("echostr");
System.out.println("随机字符串echostr:-----------------------"+echostr);
//System.out.println("token-----------------------:"+token);
PrintWriter out = response.getWriter();
// 通过检验signature对请求进行校验,若校验成功则原样返回echostr,表示接入成功,否则接入失败
if (SignUtil.checkSignature("weixinTest", signature, timestamp, nonce)) {
out.print(echostr);
//System.out.println("这是:"+echostr);
}
out.close();
out = null;
}
/**
* 处理微信服务器发来的消息
*/
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("微信服务器发来消息------------");
// 将请求、响应的编码均设置为UTF-8(防止中文乱码)
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
try{
//xml请求解析
Map<String, String> requestMap = MessageUtil.parseXml(request);
//发送方帐号(open_id)
String fromUserName = requestMap.get("FromUserName");
//公众帐号
String toUserName = requestMap.get("ToUserName");
//消息类型
String msgType = requestMap.get("MsgType");
//消息创建时间
String createTime = requestMap.get("CreateTime");
String picUrl = requestMap.get("PicUrl");
System.out.println("用户的openId-----------:"+ fromUserName);
System.out.println("消息类型-----------:"+ msgType);
System.out.println("图片的连接地址---------:"+picUrl);
String respMessage = "<xml>"
+"<ToUserName><![CDATA["+fromUserName+"]]></ToUserName>"
+"<FromUserName><![CDATA["+toUserName+"]]></FromUserName>"
+"<CreateTime>12345678</CreateTime>"
+"<MsgType><![CDATA[text]]></MsgType>"
+"<Content><![CDATA[你妹的用户发来的是图片]]></Content>"
+"</xml>";
// 响应回复消息
PrintWriter out = response.getWriter();
out.print(respMessage);
out.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
package com.test;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
/***
*
* @author V型知识库 www.vxzsk.com
* linfanhehe@163.com
*
*/
public class SignUtil {
/**
* 验证签名
*
* @param signature
* @param timestamp
* @param nonce
* @return
*/
public static boolean checkSignature(String token, String signature, String timestamp, String nonce) {
String[] arr = new String[] { token, timestamp, nonce };
// 将token、timestamp、nonce三个参数进行字典序排序
Arrays.sort(arr);
StringBuilder content = new StringBuilder();
for (int i = 0; i < arr.length; i++) {
content.append(arr[i]);
}
MessageDigest md = null;
String tmpStr = null;
try {
md = MessageDigest.getInstance("SHA-1");
// 将三个参数字符串拼接成一个字符串进行sha1加密
byte[] digest = md.digest(content.toString().getBytes());
tmpStr = byteToStr(digest);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
content = null;
// 将sha1加密后的字符串可与signature对比,标识该请求来源于微信
return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false;
}
/**
* 将字节数组转换为十六进制字符串
* @param byteArray
* @return
*/
private static String byteToStr(byte[] byteArray) {
String strDigest = "";
for (int i = 0; i < byteArray.length; i++) {
strDigest += byteToHexStr(byteArray[i]);
}
return strDigest;
}
/**
* 将字节转换为十六进制字符串
* @param mByte
* @return
*/
private static String byteToHexStr(byte mByte) {
char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
char[] tempArr = new char[2];
tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
tempArr[1] = Digit[mByte & 0X0F];
String s = new String(tempArr);
return s;
}
}
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
/***
*
* @author V型知识库 www.vxzsk.com
* linfanhehe@163.com
*
*/
public class MessageUtil {
/**
* 解析微信发来的请求(XML)
*
* @param request
* @return
* @throws Exception
*/
@SuppressWarnings("unchecked")
public static Map<String, String> parseXml(HttpServletRequest request) throws Exception {
// 将解析结果存储在HashMap中
Map<String, String> map = new HashMap<String, String>();
// 从request中取得输入流
InputStream inputStream = request.getInputStream();
// 读取输入流
SAXReader reader = new SAXReader();
Document document = reader.read(inputStream);
// 得到xml根元素
Element root = document.getRootElement();
// 得到根元素的所有子节点
List<Element> elementList = root.elements();
// 遍历所有子节点
for (Element e : elementList) {
map.put(e.getName(), e.getText());
}
// 释放资源
inputStream.close();
inputStream = null;
return map;
}
}