86 lines
2.4 KiB
Plaintext
86 lines
2.4 KiB
Plaintext
|
|
package com.jysoft;
|
||
|
|
|
||
|
|
import java.io.IOException;
|
||
|
|
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.jysoft.weChat.util.MessageUtil;
|
||
|
|
import com.jysoft.weChat.util.WechatUtil;
|
||
|
|
|
||
|
|
|
||
|
|
public class WeChatServlet extends HttpServlet {
|
||
|
|
|
||
|
|
/**
|
||
|
|
*
|
||
|
|
*/
|
||
|
|
private static final long serialVersionUID = -1886413874581936428L;
|
||
|
|
/*
|
||
|
|
* 自定义token, 用作生成签名,从而验证安全性
|
||
|
|
*/
|
||
|
|
private final String TOKEN = "asdfgh";
|
||
|
|
|
||
|
|
@Override
|
||
|
|
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
|
||
|
|
// 消息响应
|
||
|
|
request.setCharacterEncoding("UTF-8");
|
||
|
|
response.setCharacterEncoding("UTF-8");
|
||
|
|
System.out.println("请求进来了");
|
||
|
|
String result = "";
|
||
|
|
|
||
|
|
try {
|
||
|
|
Map<String, String> map = MessageUtil.parseXml(request);
|
||
|
|
System.out.println("开始构造消息");
|
||
|
|
// 构造响应消息
|
||
|
|
result = MessageUtil.buildXml(map);
|
||
|
|
System.out.println(result);
|
||
|
|
|
||
|
|
if (result.equals("")) {
|
||
|
|
result = "未正确响应";
|
||
|
|
}
|
||
|
|
} catch (Exception e) {
|
||
|
|
e.printStackTrace();
|
||
|
|
System.out.println("发生异常:" + e.getMessage());
|
||
|
|
}
|
||
|
|
// 返回结果
|
||
|
|
response.getWriter().println(result);
|
||
|
|
System.out.println("请求结束");
|
||
|
|
}
|
||
|
|
|
||
|
|
@Override
|
||
|
|
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
|
||
|
|
System.out.println("-----开始校验签名-----");
|
||
|
|
|
||
|
|
/**
|
||
|
|
* 接收微信服务器发送请求时传递过来的参数
|
||
|
|
*/
|
||
|
|
String signature = req.getParameter("signature");
|
||
|
|
String timestamp = req.getParameter("timestamp");
|
||
|
|
String nonce = req.getParameter("nonce"); // 随机数
|
||
|
|
String echostr = req.getParameter("echostr");// 随机字符串
|
||
|
|
|
||
|
|
/**
|
||
|
|
* 将token、timestamp、nonce三个参数进行字典序排序 并拼接为一个字符串
|
||
|
|
*/
|
||
|
|
|
||
|
|
String sortStr = WechatUtil.sort(TOKEN, timestamp, nonce);
|
||
|
|
/**
|
||
|
|
* 字符串进行shal加密
|
||
|
|
*/
|
||
|
|
String mySignature = WechatUtil.shal(sortStr);
|
||
|
|
/**
|
||
|
|
* 校验微信服务器传递过来的签名 和 加密后的字符串是否一致, 若一致则签名通过
|
||
|
|
*/
|
||
|
|
if (!"".equals(signature) && !"".equals(mySignature) && signature.equals(mySignature)) {
|
||
|
|
System.out.println("-----签名校验通过-----");
|
||
|
|
resp.getWriter().write(echostr);
|
||
|
|
} else {
|
||
|
|
System.out.println("-----校验签名失败-----");
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
}
|