1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
|
packageweixin.guanjia.core.controller;
importjava.io.IOException;
importjava.io.PrintWriter;
importjava.util.List;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importorg.springframework.beans.factory.annotation.Autowired;
importweixin.guanjia.account.entity.WeixinAccountEntity;
importweixin.guanjia.account.service.WeixinAccountServiceI;
importweixin.guanjia.account.service.impl.WeixinAccountServiceImpl;
importweixin.guanjia.core.service.impl.WechatService;
importweixin.guanjia.core.util.SignUtil;
/**
* 核心請求處理類
*
*
@author liufeng
* @date 2013-05-18
*/
publicclassWeixinServletextendsHttpServlet {
privatestaticfinallongserialVersionUID = 4440739483644821986L;
@Autowired
privateWeixinAccountServiceI weixinAccountService;
@Override
publicvoidinit()throwsServletException {
weixinAccountService =newWeixinAccountServiceImpl();
}
/**
* 確認請求來自微信服務器
*/
publicvoiddoGet(HttpServletRequest request, HttpServletResponse response)
throwsServletException, IOException {
// 微信加密簽名
String signature = request.getParameter("signature");
// 時間戳
String timestamp = request.getParameter("timestamp");
// 隨機數
String nonce = request.getParameter("nonce");
// 隨機字符串
String echostr = request.getParameter("echostr");
PrintWriter out = response.getWriter();
List<WeixinAccountEntity> weixinAccountEntities = weixinAccountService
.getList(WeixinAccountEntity.class);
// 經過檢驗signature對請求進行校驗,若校驗成功則原樣返回echostr,表示接入成功,不然接入失敗
for(WeixinAccountEntity account : weixinAccountEntities) {
if(SignUtil.checkSignature(account.getAccounttoken(), signature,
timestamp, nonce)) {
out.print(echostr);
}
}
out.close();
out =null;
}
/**
* 處理微信服務器發來的消息
*/
publicvoiddoPost(HttpServletRequest request, HttpServletResponse response)
throwsServletException, IOException {
// 將請求、響應的編碼均設置爲UTF-8(防止中文亂碼)
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
WechatService wechatService =newWechatService();
// 調用核心業務類接收消息、處理消息
String respMessage = wechatService.coreService(request);
// 響應消息
PrintWriter out = response.getWriter();
out.print(respMessage);
out.close();
}
}
|