WeixinIndexController.java
9.31 KB
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
package com.server.web.controller;
import com.server.utils.SHA1;
import com.server.utils.weixin.WXMessageType;
import com.server.utils.weixin.WeixinBaseUtil;
import com.server.web.common.mapper.TKzyUserMapper;
import com.server.web.common.model.TKzyUser;
import com.server.web.common.model.TKzyUserExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import static com.jfinal.weixin.sdk.kit.PaymentKit.xmlToMap;
/**
* Created by 豆腐干Sama on 2018/12/5.
*/
@RestController
@RequestMapping(value = BaseController.WX_NAMESPACE + "/wxIndex",produces = "application/json")
public class WeixinIndexController extends BaseController{
@Value("${wx.app.secret}")
private String appSecret;
@Value("${wx.app.id}")
private String appId;
@Value("${wx.tocken}")
private String wxTocken;
@Autowired
private TKzyUserMapper userMapper;
@RequestMapping(value = "/authorizeCallback",method = {RequestMethod.GET,RequestMethod.POST})
public void authorizeCallback(HttpServletRequest request, HttpServletResponse response) {
try {
String code = request.getParameter("code");// 授权码
String redirectUri = request.getParameter("redirectUri");// redirectUri参数,验证成功跳转
WeixinBaseUtil weixinBaseUtil = new WeixinBaseUtil();
logger.error("授权回调参数:code " + code + " appId " + appId + " appSecret:" + appSecret);
Map<String, Object> _AuthMap = weixinBaseUtil.authorization(appId, appSecret, code);
if (_AuthMap == null) {
response.sendRedirect(redirectUri);
return;
}
String openId = (String)_AuthMap.get("openid");
String nickname = (String) _AuthMap.get("nickname");
String headimgurl = (String) _AuthMap.get("headimgurl");
logger.error("nickname:" + nickname + "");
TKzyUser user;
TKzyUserExample example = new TKzyUserExample();
example.createCriteria().andWxOpenidEqualTo(openId);
List<TKzyUser> users = userMapper.selectByExample(example);
if (CollectionUtils.isEmpty(users)) {
user = new TKzyUser();
user.setHeadPhoto(headimgurl);
user.setFullName(nickname);
user.setWxOpenid(openId);
} else {
user = users.get(0);
user.setLastLoginDt(new Date());
if (StringUtils.isEmpty(user.getFullName())) {
user.setFullName(nickname);
}
if (StringUtils.isEmpty(user.getHeadPhoto())) {
user.setHeadPhoto(headimgurl);
}
userMapper.updateByPrimaryKeySelective(user);
}
request.getSession().setAttribute(WX_USER_SESSION_KEY,user);
logger.error("user.getNickName:" + user.getFullName());
response.sendRedirect(redirectUri);
} catch (Exception e) {
e.printStackTrace();
}
}
public Map<String,Object> getAccessToken() {
String accessToken = getAccessToken(appId, appSecret);
if (StringUtils.hasText(accessToken)) {
return returnSuccess(accessToken);
} else {
return returnError("0","获取access_toke失败",null);
}
}
public void textWrite(String text,HttpServletResponse response) {
response.setContentType("text/html; charset=UTF-8");
try {
response.getWriter().write(text);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 处理接受参数
* @param request
* @return
*/
public static String readRequestStr(HttpServletRequest request) {
BufferedReader reader = null;
StringBuilder sb = new StringBuilder();
try {
reader = new BufferedReader(new InputStreamReader(request.getInputStream(), "utf-8"));
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (null != reader) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
@RequestMapping(value = "/callback", method = {RequestMethod.POST, RequestMethod.GET})
public void callback(HttpServletRequest request, HttpServletResponse response){
try{
String signature = request.getParameter("signature");
String nonce = request.getParameter("nonce");
String echostr = request.getParameter("echostr");
String timestamp = request.getParameter("timestamp");
boolean isPass =checkSignature(signature, timestamp, nonce);
if (!isPass) {
logger.error("isPass 验证错误!!");
return;
} else if (StringUtils.hasText(echostr)) {
textWrite(echostr,response);
return;
}
String xmlStr =readRequestStr(request);
Map<String, String> map = xmlToMap(xmlStr);
if (map == null) {
logger.error("callback-map is null !!");
}else{
String msgType = map.get("MsgType");
String content ="";
if (WXMessageType.event.toString().equals(msgType)) {//点击事件
// FIXME: 2018/12/5
}else if(WXMessageType.text.toString().equals(msgType)){//关键字回复
// FIXME: 2018/12/5
}
String openId = map.get("ToUserName");
String wx_id = map.get("FromUserName");
if(content!=null&&!"".equals(content.trim())){
textWrite(getWxStringMsg(openId,wx_id, content),response);
}
}
}catch (Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) {
String urlTicket = "http://kzy-wx.jimijiayuan.cn/home?shareFlag=true";
urlTicket = urlTicket.substring(0,urlTicket.indexOf("?"));
System.out.println(urlTicket);
}
@ResponseBody
@RequestMapping(value = "/jsApiSignature", method = {RequestMethod.POST, RequestMethod.GET}, produces = "application/json")
public Map<String,Object> jsApiSignature(HttpServletRequest request) throws Exception{
try{
String urlTicket = request.getParameter("url");
if(StringUtils.hasText(urlTicket)){
if(urlTicket.contains("?")){
urlTicket = urlTicket.substring(0,urlTicket.indexOf("?"));
}
Map<String, Object> signature = jsApiSignature(urlTicket);
if(signature!=null) {
return returnSuccess(signature);
}
}else{
return returnError("0","参数url缺失",null);
}
}catch (Exception e){
e.printStackTrace();
return returnError("0","服务器异常",null);
}
return returnError("0","获取签名失败","");
}
public boolean checkSignature(String signature,String timestamp,String nonce) {
String[] str = new String[]{wxTocken, timestamp, nonce};
//排序
Arrays.sort(str);
//拼接字符串
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < str.length; i++) {
buffer.append(str[i]);
}
//进行sha1加密
String temp = SHA1.encode(buffer.toString());
//与微信提供的signature进行匹对
return signature.equals(temp);
}
public String getWxStringMsg(String fromUserName, String toUserName, String content) {
String msg = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[%s]]></MsgType><Content><![CDATA[%s]]></Content></xml>";
return String.format(msg, new String[]{toUserName, fromUserName, Long.valueOf(System.currentTimeMillis() / 1000).toString(), "text", content});
}
public Map<String,Object> jsApiSignature(String url) throws Exception{
if(StringUtils.hasText(appId)&&StringUtils.hasText(appId)&&StringUtils.hasText(url)){
String jsapi_ticket =WeixinBaseUtil.getTicket(appId,getAccessToken(appId,appSecret),url,redisTemplate);
Map<String, Object> sign = WeixinBaseUtil.sign(jsapi_ticket, url, appId);
return sign;
}else{
return null;
}
}
}