PageRenderTime 67ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/src/main/java/lehuo/lsm/controller/WechatController.java

https://gitlab.com/Simon0622/web
Java | 1147 lines | 1008 code | 117 blank | 22 comment | 119 complexity | a3ea65d2d8213e23d96876131d359491 MD5 | raw file
  1. package lehuo.lsm.controller;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONObject;
  4. import com.google.common.primitives.Doubles;
  5. import java.io.IOException;
  6. import java.io.PrintWriter;
  7. import java.text.SimpleDateFormat;
  8. import java.util.ArrayList;
  9. import java.util.Collections;
  10. import java.util.Date;
  11. import java.util.HashMap;
  12. import java.util.List;
  13. import java.util.Map;
  14. import java.util.Timer;
  15. import java.util.regex.Pattern;
  16. import javax.annotation.Resource;
  17. import javax.servlet.http.HttpServletResponse;
  18. import org.apache.commons.lang.StringUtils;
  19. import org.dom4j.Document;
  20. import org.dom4j.DocumentException;
  21. import org.dom4j.DocumentHelper;
  22. import org.dom4j.Element;
  23. import org.dom4j.Node;
  24. import org.slf4j.Logger;
  25. import org.slf4j.LoggerFactory;
  26. import org.springframework.stereotype.Controller;
  27. import org.springframework.web.bind.annotation.RequestBody;
  28. import org.springframework.web.bind.annotation.RequestMapping;
  29. import org.springframework.web.bind.annotation.ResponseBody;
  30. import lehuo.lsm.dao.BzHuodongDao;
  31. import lehuo.lsm.dao.HuodongCommentDao;
  32. import lehuo.lsm.dao.HuodongDao;
  33. import lehuo.lsm.dao.SearchWordDao;
  34. import lehuo.lsm.dao.WeChatCommentDao;
  35. import lehuo.lsm.dao.WeChatImageDao;
  36. import lehuo.lsm.dao.WeChatUserDao;
  37. import lehuo.lsm.dao.WeChatUserfromDao;
  38. import lehuo.lsm.dao.ZhenghunDao;
  39. import lehuo.lsm.model.SearchWord;
  40. import lehuo.lsm.model.WechatModel.Article;
  41. import lehuo.lsm.model.WechatModel.ImgTextMsgVo;
  42. import lehuo.lsm.model.WechatModel.ImgVoiceMsgVo;
  43. import lehuo.lsm.model.WechatModel.TextMsgVo;
  44. import lehuo.lsm.model.WechatModel.db.BzHuodong;
  45. import lehuo.lsm.model.WechatModel.db.Huodong;
  46. import lehuo.lsm.model.WechatModel.db.HuodongComment;
  47. import lehuo.lsm.model.WechatModel.db.WeChatComment;
  48. import lehuo.lsm.model.WechatModel.db.WeChatImage;
  49. import lehuo.lsm.model.WechatModel.db.WeChatUser;
  50. import lehuo.lsm.model.WechatModel.db.WeChatUserfrom;
  51. import lehuo.lsm.model.WechatModel.db.WexinComment;
  52. import lehuo.lsm.model.WechatModel.db.Zhenghun;
  53. import lehuo.lsm.util.ATTimerTask;
  54. import lehuo.lsm.util.EncoderHandler;
  55. import lehuo.lsm.util.HttpUtils;
  56. /**
  57. * Created by simon on 14/12/20.
  58. */
  59. @Controller
  60. @RequestMapping(value = "/wechat")
  61. public class WechatController
  62. {
  63. protected static Logger logger = LoggerFactory.getLogger(WechatController.class);
  64. private static String token = "AfUG9fSG";
  65. private static final String weburl = "www.ygkbnu.com/xiaoxianrou/";
  66. private static final String appid = "wx75f426630ab9a4fd";
  67. private static final String secret = "81668fc80beb4691b2e6bf80d8459999";
  68. public static volatile String timestamp;
  69. public static volatile String nonceStr;
  70. public static volatile String signature;
  71. private Map<String, String> eventMap = new HashMap<String, String>();
  72. private Map<String, String> locationMap = new HashMap<String, String>();
  73. private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  74. private static final Pattern huodongpattern = Pattern.compile("^10[1-9][0-9]*");
  75. private static final Pattern gerenpattern = Pattern.compile("^20[1-9][0-9]*");
  76. private static final Pattern zhenghunpattern = Pattern.compile("^[gGmM]{2}[0-9]{1,4}$");
  77. Timer timer;
  78. @Resource
  79. WeChatUserDao weChatUserDao;
  80. @Resource
  81. WeChatImageDao weChatImageDao;
  82. @Resource
  83. HuodongDao huodongDao;
  84. @Resource
  85. HuodongCommentDao huodongCommentDao;
  86. @Resource
  87. private WeChatCommentDao weChatCommentDao;
  88. @Resource
  89. WeChatUserfromDao weChatUserfromDao;
  90. @Resource
  91. BzHuodongDao bzHuodongDao;
  92. @Resource
  93. SearchWordDao searchWordDao;
  94. @Resource
  95. ZhenghunDao zhenghunDao;
  96. public WechatController()
  97. {
  98. timer = new Timer();
  99. timer.schedule(new ATTimerTask(), 1 * 1000, 7200 * 1000);
  100. }
  101. @RequestMapping(value = "/callback")
  102. public String callback(String code, String state, String fromid)
  103. {
  104. logger.info("callback step into code {},state {},fromid {}", code, state, fromid);
  105. if (StringUtils.isBlank(code))
  106. {
  107. return "error";
  108. }
  109. else
  110. {
  111. String result = HttpUtils.httpsCon("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + secret
  112. + "&code=" + code + "&grant_type=authorization_code");
  113. logger.info("step one {}", result);
  114. JSONObject jsonObject = JSON.parseObject(result);
  115. String access_token = jsonObject.getString("access_token");
  116. String refresh_token = jsonObject.getString("refresh_token");
  117. String openid = jsonObject.getString("openid");
  118. // 延长access_token时间的代码,暂时不用延长,延长再打开即可
  119. result = HttpUtils.httpsCon("https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + appid
  120. + "&grant_type=refresh_token&refresh_token=" + refresh_token);
  121. logger.info("step two {}", result);
  122. jsonObject = JSON.parseObject(result);
  123. access_token = jsonObject.getString("access_token");
  124. if (access_token != null)
  125. {
  126. result = HttpUtils.httpsCon("https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid
  127. + "&lang=zh_CN");
  128. jsonObject = JSON.parseObject(result);
  129. logger.info("callback user is {}", jsonObject.toString());
  130. /*WeChatUser weChatUser = new WeChatUser(jsonObject.getString("openid"));
  131. weChatUser.setNickname(jsonObject.getString("nickname"));
  132. weChatUser.setSex(jsonObject.getString("sex"));
  133. weChatUser.setProvince(jsonObject.getString("province"));
  134. weChatUser.setCity(jsonObject.getString("city"));
  135. weChatUser.setCountry(jsonObject.getString("country"));
  136. weChatUser.setHeadimgurl(jsonObject.getString("headimgurl"));*/
  137. // session.setAttribute(jsonObject.getString("openid"), weChatUser);
  138. }
  139. return "redirect:/wechatuser/detail?fromid=" + fromid + "&viewid=" + openid;
  140. }
  141. }
  142. @RequestMapping(value = "/ucenter")
  143. public String ucenter(String code, String state, String fromid)
  144. {
  145. logger.info("ucenter step into code {},state {},fromid {}", code, state, fromid);
  146. if (StringUtils.isBlank(code))
  147. {
  148. return "error";
  149. }
  150. else
  151. {
  152. String result = HttpUtils.httpsCon("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + secret
  153. + "&code=" + code + "&grant_type=authorization_code");
  154. logger.info("step one {}", result);
  155. JSONObject jsonObject = JSON.parseObject(result);
  156. String access_token = jsonObject.getString("access_token");
  157. String refresh_token = jsonObject.getString("refresh_token");
  158. String openid = jsonObject.getString("openid");
  159. // 延长access_token时间的代码,暂时不用延长,延长再打开即可
  160. result = HttpUtils.httpsCon("https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + appid
  161. + "&grant_type=refresh_token&refresh_token=" + refresh_token);
  162. logger.info("step two {}", result);
  163. jsonObject = JSON.parseObject(result);
  164. access_token = jsonObject.getString("access_token");
  165. if (access_token != null)
  166. {
  167. result = HttpUtils.httpsCon("https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid
  168. + "&lang=zh_CN");
  169. jsonObject = JSON.parseObject(result);
  170. logger.info("ucenter user is {}", jsonObject.toString());
  171. WeChatUser weChatUser = new WeChatUser(jsonObject.getString("openid"));
  172. weChatUser.setNickname(jsonObject.getString("nickname"));
  173. weChatUser.setSex(jsonObject.getString("sex"));
  174. weChatUser.setProvince(jsonObject.getString("province"));
  175. weChatUser.setCity(jsonObject.getString("city"));
  176. weChatUser.setCountry(jsonObject.getString("country"));
  177. weChatUser.setHeadimgurl(jsonObject.getString("headimgurl"));
  178. }
  179. return "redirect:/wechatuser/index?fromid=" + jsonObject.getString("openid");
  180. }
  181. }
  182. @RequestMapping(value = "/uactivity")
  183. public String uactivity(String code, String state, String fromid)
  184. {
  185. logger.info("uactivity step into code {},state {},fromid {}", code, state, fromid);
  186. if (StringUtils.isBlank(code))
  187. {
  188. return "error";
  189. }
  190. else
  191. {
  192. String result = HttpUtils.httpsCon("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + secret
  193. + "&code=" + code + "&grant_type=authorization_code");
  194. logger.info("step one {}", result);
  195. JSONObject jsonObject = JSON.parseObject(result);
  196. String access_token = jsonObject.getString("access_token");
  197. String refresh_token = jsonObject.getString("refresh_token");
  198. String openid = jsonObject.getString("openid");
  199. // 延长access_token时间的代码,暂时不用延长,延长再打开即可
  200. result = HttpUtils.httpsCon("https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + appid
  201. + "&grant_type=refresh_token&refresh_token=" + refresh_token);
  202. logger.info("step two {}", result);
  203. jsonObject = JSON.parseObject(result);
  204. access_token = jsonObject.getString("access_token");
  205. if (access_token != null)
  206. {
  207. result = HttpUtils.httpsCon("https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid
  208. + "&lang=zh_CN");
  209. jsonObject = JSON.parseObject(result);
  210. logger.info("ucenter user is {}", jsonObject.toString());
  211. WeChatUser weChatUser = new WeChatUser(jsonObject.getString("openid"));
  212. weChatUser.setNickname(jsonObject.getString("nickname"));
  213. weChatUser.setSex(jsonObject.getString("sex"));
  214. weChatUser.setProvince(jsonObject.getString("province"));
  215. weChatUser.setCity(jsonObject.getString("city"));
  216. weChatUser.setCountry(jsonObject.getString("country"));
  217. weChatUser.setHeadimgurl(jsonObject.getString("headimgurl"));
  218. return "redirect:/huodong/userhdindex?fromuserid=" + weChatUser.getFromid();
  219. }
  220. else
  221. {
  222. return "";
  223. }
  224. }
  225. }
  226. @RequestMapping(value = "/index")
  227. public void index(String signature, String timestamp, String nonce, String echostr,
  228. @RequestBody String body, HttpServletResponse response)
  229. {
  230. response.setCharacterEncoding("UTF-8");
  231. List<String> list = new ArrayList<String>();
  232. logger.info("signature is {},timestamp is {},nonce is {},echostr is {}", signature, timestamp, nonce, echostr);
  233. WechatController.timestamp = timestamp;
  234. WechatController.nonceStr = nonce;
  235. WechatController.signature = signature;
  236. logger.info("request body is {}", body);
  237. list.add(timestamp);
  238. list.add(token);
  239. list.add(nonce);
  240. Collections.sort(list);
  241. StringBuffer sb = new StringBuffer();
  242. for (String l : list)
  243. {
  244. sb.append(l);
  245. }
  246. logger.info("jiami list is {}", sb.toString());
  247. String verify = EncoderHandler.encode("SHA1", sb.toString());
  248. logger.info("verify is {}", verify);
  249. Document doc = null;
  250. try
  251. {
  252. doc = DocumentHelper.parseText(body);
  253. }
  254. catch (DocumentException e)
  255. {
  256. logger.error("xml parse error", e);
  257. }
  258. Element rootElement = doc.getRootElement();
  259. String rep = dispatchMsg(rootElement);
  260. if (rep == null)
  261. {
  262. rep = "";
  263. }
  264. logger.info("response result {}", rep);
  265. if (verify.equals(signature))
  266. {
  267. logger.info("wechar verify success");
  268. try
  269. {
  270. PrintWriter out = response.getWriter();
  271. out.print(rep);
  272. out.close();
  273. }
  274. catch (IOException e)
  275. {
  276. logger.error("response error", e);
  277. }
  278. }
  279. else
  280. {
  281. logger.info("wechar verify failed");
  282. try
  283. {
  284. PrintWriter out = response.getWriter();
  285. out.print("");
  286. out.close();
  287. }
  288. catch (IOException e)
  289. {
  290. logger.error("response error", e);
  291. }
  292. }
  293. }
  294. private String dispatchMsg(Element rootElement)
  295. {
  296. if (rootElement == null)
  297. {
  298. return null;
  299. }
  300. else
  301. {
  302. Node MsgType = rootElement.element("MsgType");
  303. if (MsgType != null)
  304. {
  305. if (MsgType.getText().equals("text"))
  306. {
  307. logger.info("text msg");
  308. return handleTextMsg(rootElement);
  309. }
  310. else if (MsgType.getText().equals("image"))
  311. {
  312. logger.info("image msg");
  313. return handleImgMsg(rootElement);
  314. }
  315. else if (MsgType.getText().equals("voice"))
  316. {
  317. logger.info("voice msg");
  318. return handleVoiceMsg(rootElement);
  319. }
  320. else if (MsgType.getText().equals("video"))
  321. {
  322. logger.info("video msg");
  323. return handleVideoMsg(rootElement);
  324. }
  325. else if (MsgType.getText().equals("location"))
  326. {
  327. logger.info("location msg");
  328. return handleLocationMsg(rootElement);
  329. }
  330. else if (MsgType.getText().equals("link"))
  331. {
  332. logger.info("link msg");
  333. return handleLinkMsg(rootElement);
  334. }
  335. else if (MsgType.getText().equals("event"))
  336. {
  337. logger.info("event msg");
  338. return handleEventMsg(rootElement);
  339. }
  340. else
  341. {
  342. logger.info("other msg");
  343. return handleOtherMsg(rootElement);
  344. }
  345. }
  346. else
  347. {
  348. return null;
  349. }
  350. }
  351. }
  352. private String handleTextMsg(Element rootElement)
  353. {
  354. String content = rootElement.element("Content").getText();
  355. String fromUserName = rootElement.element("FromUserName").getText();
  356. String toUserName = rootElement.element("ToUserName").getText();
  357. String createTime = rootElement.element("CreateTime").getText();
  358. if (huodongpattern.matcher(content).find())
  359. {
  360. if (StringUtils.isBlank(fromUserName))
  361. {
  362. return null;
  363. }
  364. else
  365. {
  366. // 截取10
  367. String[] args = content.split(" ");
  368. String cId = args[0].substring(2, args[0].length());
  369. content.replaceAll(args[0], "");
  370. try
  371. {
  372. Integer commentId = Integer.parseInt(cId);
  373. HuodongComment huodongComment = huodongCommentDao.select(new HuodongComment(commentId));
  374. HuodongComment newComment = new HuodongComment(huodongComment.getToid());
  375. newComment.setToid(huodongComment.getFromid());
  376. newComment.setContent(content);
  377. newComment.setReplyId(huodongComment.getId());
  378. huodongCommentDao.insert(newComment);
  379. sendKFMsg(newComment, "10");
  380. TextMsgVo textMsgVo = new TextMsgVo(fromUserName, toUserName, createTime);
  381. textMsgVo.setContent("回复成功");
  382. String result = sendTextMsg(textMsgVo);
  383. logger.info("handleTextMsg return {}", result);
  384. return result;
  385. }
  386. catch (Exception e)
  387. {
  388. logger.error(e.getMessage(), e);
  389. return "";
  390. }
  391. }
  392. }
  393. else if (gerenpattern.matcher(content).find())
  394. {
  395. String[] args = content.split(" ");
  396. if (StringUtils.isBlank(fromUserName))
  397. {
  398. return null;
  399. }
  400. else
  401. {
  402. // 截取20
  403. String cId = args[0].substring(2, args[0].length());
  404. content.replaceAll(args[0], "");
  405. WeChatComment weChatComment = weChatCommentDao.select(new WeChatComment(Integer.parseInt(cId)));
  406. WeChatComment newComment = new WeChatComment(weChatComment.getToid());
  407. newComment.setContent(content);
  408. newComment.setToid(weChatComment.getFromid());
  409. newComment.setReplyId(weChatComment.getId());
  410. weChatCommentDao.insert(newComment);
  411. sendKFMsg(newComment, "20");
  412. TextMsgVo textMsgVo = new TextMsgVo(fromUserName, toUserName, createTime);
  413. textMsgVo.setContent("回复成功");
  414. String result = sendTextMsg(textMsgVo);
  415. logger.info("handleTextMsg return {}", result);
  416. return result;
  417. }
  418. }
  419. else if (zhenghunpattern.matcher(content).find())
  420. {
  421. if (StringUtils.isBlank(fromUserName))
  422. {
  423. return null;
  424. }
  425. else
  426. {
  427. String sex = content.substring(0, 2);
  428. String num = content.substring(2);
  429. StringBuffer sb = new StringBuffer();
  430. if (sex.equalsIgnoreCase("GG"))
  431. {
  432. sb.append("GG").append(num);
  433. Zhenghun zhengh = zhenghunDao.selectGivenNum(sb.toString());
  434. ImgTextMsgVo imgTextMsgVo = new ImgTextMsgVo(fromUserName, toUserName, createTime);
  435. List<Article> articles = new ArrayList<Article>();
  436. Article article = new Article(zhengh.getTitle(), "详情请点击查看", zhengh.getImgurl(), zhengh.getUrl());
  437. articles.add(article);
  438. imgTextMsgVo.setList(articles);
  439. imgTextMsgVo.setMsgType("news");
  440. String result = sendTWMsg(imgTextMsgVo);
  441. return result;
  442. }
  443. else if (sex.equalsIgnoreCase("MM"))
  444. {
  445. sb.append("MM").append(num);
  446. Zhenghun zhengh = zhenghunDao.selectGivenNum(sb.toString());
  447. ImgTextMsgVo imgTextMsgVo = new ImgTextMsgVo(fromUserName, toUserName, createTime);
  448. List<Article> articles = new ArrayList<Article>();
  449. Article article = new Article(zhengh.getTitle(), "详情请点击查看", zhengh.getImgurl(), zhengh.getUrl());
  450. articles.add(article);
  451. imgTextMsgVo.setList(articles);
  452. imgTextMsgVo.setMsgType("news");
  453. String result = sendTWMsg(imgTextMsgVo);
  454. return result;
  455. }
  456. else
  457. {
  458. return "";
  459. }
  460. }
  461. }
  462. else if (content.startsWith("官方活动"))
  463. {
  464. String args[] = content.split(" ");
  465. WeChatUser wu = weChatUserDao.select(new WeChatUser(fromUserName));
  466. searchWordDao.insert(new SearchWord(wu.getId(), args[1]));
  467. TextMsgVo textMsgVo = new TextMsgVo(fromUserName, toUserName, createTime);
  468. textMsgVo.setContent("报名成功,稍后会有客服把您拉到这周的活动群");
  469. String result = sendTextMsg(textMsgVo);
  470. logger.info("handleTextMsg return {}", result);
  471. return result;
  472. }
  473. else
  474. {
  475. return "";
  476. }
  477. }
  478. private String handleImgMsg(Element rootElement)
  479. {
  480. String fromUserName = rootElement.element("FromUserName").getText();
  481. String toUserName = rootElement.element("ToUserName").getText();
  482. String createTime = rootElement.element("CreateTime").getText();
  483. String result = "";
  484. String evententry = eventMap.get(fromUserName);
  485. logger.info("get key {},value is {}", fromUserName, evententry);
  486. if ("V1002_CREATEDATE".equals(evententry))
  487. {
  488. // 移除key
  489. eventMap.remove(fromUserName);
  490. logger.info("eventMap size {}", eventMap.size());
  491. String picUrl = rootElement.element("PicUrl").getText();
  492. Date today = new Date();
  493. String t = sdf.format(today);
  494. Huodong update = new Huodong();
  495. update.setHdewm(picUrl);
  496. Huodong huodong = huodongDao.selectTodayLast(t, fromUserName);
  497. huodongDao.update(update, new Huodong(fromUserName));
  498. TextMsgVo textMsgVo = new TextMsgVo(fromUserName, toUserName, createTime);
  499. textMsgVo.setContent("上传二维码成功");
  500. result = sendTextMsg(textMsgVo);
  501. return result;
  502. }
  503. else
  504. {
  505. String picUrl = rootElement.element("PicUrl").getText();
  506. String msgId = rootElement.element("MsgId").getText();
  507. String mediaId = rootElement.element("MediaId").getText();
  508. WeChatImage weChatImage = new WeChatImage(fromUserName);
  509. weChatImage.setImgurl(picUrl);
  510. weChatImage.setMsgid(msgId);
  511. weChatImage.setMediaid(mediaId);
  512. weChatImageDao.insert(weChatImage);
  513. logger.info("handleImgMsg insert img success");
  514. ImgTextMsgVo imgTextMsgVo = new ImgTextMsgVo(fromUserName, toUserName, createTime);
  515. List<Article> list = new ArrayList<Article>();
  516. Article article = new Article("上传成功", "点击查看", weChatImage.getImgurl(), "www.ygkbnu.com/xiaoxianrou/wechatuser/edit?fromid="
  517. + fromUserName);
  518. list.add(article);
  519. imgTextMsgVo.setList(list);
  520. imgTextMsgVo.setMsgType("news");
  521. result = sendTWMsg(imgTextMsgVo);
  522. return result;
  523. }
  524. }
  525. private String handleVoiceMsg(Element rootElement)
  526. {
  527. return null;
  528. }
  529. private String handleVideoMsg(Element rootElement)
  530. {
  531. return null;
  532. }
  533. private String handleLocationMsg(Element rootElement)
  534. {
  535. String fromUserName = rootElement.element("FromUserName").getText();
  536. String toUserName = rootElement.element("ToUserName").getText();
  537. String createTime = rootElement.element("CreateTime").getText();
  538. String latitude = rootElement.element("Location_X").getText();
  539. String longitude = rootElement.element("Location_Y").getText();
  540. String address = rootElement.element("Label").getText();
  541. String result = "";
  542. TextMsgVo textMsgVo = null;
  543. WeChatUser weChatUser = weChatUserDao.selectRecommondUser(new WeChatUser(fromUserName));
  544. if (weChatUser == null)
  545. {
  546. textMsgVo = new TextMsgVo(fromUserName, toUserName, createTime);
  547. textMsgVo.setContent("请您先选择会员-上传形象照");
  548. result = sendTextMsg(textMsgVo);
  549. logger.info("handleTextMsg return {}", result);
  550. return result;
  551. }
  552. Huodong huodong = new Huodong();
  553. huodong.setHdname("修改名称");
  554. huodong.setLongitude(Double.parseDouble(longitude));
  555. huodong.setLatitude(Double.parseDouble(latitude));
  556. huodong.setUserfromid(fromUserName);
  557. huodong.setAddress(address);
  558. huodongDao.insert(huodong);
  559. ImgTextMsgVo vo = new ImgTextMsgVo(fromUserName, toUserName, createTime);
  560. List<Article> list = new ArrayList<Article>();
  561. Article a = new Article("完善活动内容", "新建活动", weChatUser.getHeadimgurl(), weburl + "huodong/huodongedit?id=" + huodong.getId());
  562. list.add(a);
  563. vo.setList(list);
  564. vo.setMsgType("news");
  565. result = sendTWMsg(vo);
  566. logger.info("handleLocationMsg return {}", result);
  567. return result;
  568. }
  569. private String handleLinkMsg(Element rootElement)
  570. {
  571. return null;
  572. }
  573. private String handleEventMsg(Element rootElement)
  574. {
  575. Node event = rootElement.element("Event");
  576. logger.info("handleEventMsg {}", event.getText());
  577. String fromUserName = rootElement.element("FromUserName").getText();
  578. String toUserName = rootElement.element("ToUserName").getText();
  579. String createTime = rootElement.element("CreateTime").getText();
  580. String result = "";
  581. Node eventKey = rootElement.element("EventKey");
  582. if (event.getText().equals("CLICK"))
  583. {
  584. if (eventKey.getText().equals("V1001_UCENTER"))
  585. {
  586. ImgTextMsgVo imgTextMsgVo = new ImgTextMsgVo(fromUserName, toUserName, createTime);
  587. WeChatUser weChatUser = weChatUserDao.select(new WeChatUser(fromUserName));
  588. List<Article> list = new ArrayList<Article>();
  589. Article article = new Article(
  590. "个人中心",
  591. "点击查看",
  592. weChatUser.getHeadimgurl(),
  593. "https://open.weixin.qq.com/connect/oauth2/authorize?appid="
  594. + appid
  595. + "&redirect_uri=http://www.ygkbnu.com/xiaoxianrou/wechat/ucenter&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
  596. list.add(article);
  597. imgTextMsgVo.setList(list);
  598. imgTextMsgVo.setMsgType("news");
  599. result = sendTWMsg(imgTextMsgVo);
  600. return result;
  601. }
  602. else if (eventKey.getText().equals("V1001_RECOMMEND"))
  603. {
  604. // todo 先是随机推荐吧,以后要慢慢改
  605. TextMsgVo textMsgVo = null;
  606. WeChatUser weChatUser = weChatUserDao.selectRecommondUser(new WeChatUser(fromUserName));
  607. if (weChatUser == null)
  608. {
  609. textMsgVo = new TextMsgVo(fromUserName, toUserName, createTime);
  610. textMsgVo.setContent("请您先选择会员-上传形象照");
  611. result = sendTextMsg(textMsgVo);
  612. logger.info("handleTextMsg return {}", result);
  613. return result;
  614. }
  615. else if (weChatUser.getSex() == null || weChatUser.getSex().equals("0"))
  616. {
  617. textMsgVo = new TextMsgVo(fromUserName, toUserName, createTime);
  618. textMsgVo.setContent("请输入您的性别,请在个人中心完善您的资料");
  619. result = sendTextMsg(textMsgVo);
  620. logger.info("handleTextMsg return {}", result);
  621. return result;
  622. }
  623. else if (StringUtils.isBlank(weChatUser.getProvince()))
  624. {
  625. textMsgVo = new TextMsgVo(fromUserName, toUserName, createTime);
  626. textMsgVo.setContent("获得不到您所在的城市,请在个人中心完善");
  627. result = sendTextMsg(textMsgVo);
  628. logger.info("handleTextMsg return {}", result);
  629. return result;
  630. }
  631. else
  632. {
  633. WeChatUser item = new WeChatUser();
  634. // 设置查询异性
  635. if (weChatUser.getSex().equals("1"))
  636. {
  637. item.setSex("2");
  638. }
  639. else
  640. {
  641. item.setSex("1");
  642. }
  643. item.setProvince(weChatUser.getProvince());
  644. item.setFromid(fromUserName);
  645. List<WeChatUser> weChatUserList = weChatUserDao.selectListnoSelf(item);
  646. if (weChatUserList == null || weChatUserList.size() == 0)
  647. {
  648. textMsgVo = new TextMsgVo(fromUserName, toUserName, createTime);
  649. textMsgVo.setContent("暂时没有和您所在同一个城市的异性,您可以邀请你的好友关注我们");
  650. result = sendTextMsg(textMsgVo);
  651. logger.info("handleTextMsg return {}", result);
  652. return result;
  653. }
  654. else
  655. {
  656. ImgTextMsgVo vo = new ImgTextMsgVo(fromUserName, toUserName, createTime);
  657. List<Article> list = new ArrayList<Article>();
  658. for (WeChatUser weChatUser1 : weChatUserList)
  659. {
  660. Article a = new Article(weChatUser1.getNickname(), weChatUser1.getCareer(), weChatUser1.getWeChatImageList().get(0)
  661. .getImgurl(),
  662. "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid
  663. + "&redirect_uri=http://www.ygkbnu.com/xiaoxianrou/wechat/callback?fromid=" + weChatUser1.getFromid()
  664. + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect");
  665. list.add(a);
  666. weChatUserDao.updaterecnum(weChatUser1.getFromid());
  667. }
  668. vo.setList(list);
  669. vo.setMsgType("news");
  670. result = sendTWMsg(vo);
  671. logger.info("handleEventMsg V1001_RECOMMEND return {}", result);
  672. }
  673. }
  674. }
  675. else if (eventKey.getText().equals("V1002_WEEKACTIVITY"))
  676. {
  677. BzHuodong bzHuodong = bzHuodongDao.select(null);
  678. ImgTextMsgVo imgTextMsgVo = new ImgTextMsgVo(fromUserName, toUserName, createTime);
  679. List<Article> articles = new ArrayList<Article>();
  680. Article article = new Article("本周活动", "点击查看", bzHuodong.getImgurl(), bzHuodong.getUrl());
  681. articles.add(article);
  682. imgTextMsgVo.setList(articles);
  683. imgTextMsgVo.setMsgType("news");
  684. result = sendTWMsg(imgTextMsgVo);
  685. return result;
  686. }
  687. else if (eventKey.getText().equals("V1002_MYDATE"))
  688. {
  689. Date today = new Date();
  690. String t = sdf.format(today);
  691. Huodong item = new Huodong(fromUserName);
  692. item.setCreatetime(t);
  693. List<Huodong> list = huodongDao.selectHuodongList(item, 0, 10);
  694. ImgTextMsgVo imgTextMsgVo = new ImgTextMsgVo(fromUserName, toUserName, createTime);
  695. List<Article> articles = new ArrayList<Article>();
  696. for (Huodong huodong : list)
  697. {
  698. Article article = new Article(huodong.getHdname(), "进入后编辑", huodong.getHeadimgurl(), weburl + "huodong/huodongdetail?id="
  699. + huodong.getId() + "&viewid=" + fromUserName);
  700. articles.add(article);
  701. }
  702. imgTextMsgVo.setList(articles);
  703. imgTextMsgVo.setMsgType("news");
  704. result = sendTWMsg(imgTextMsgVo);
  705. return result;
  706. }
  707. else if (eventKey.getText().equals("V1002_CANDATE"))
  708. {
  709. logger.info("{} click V1002_CANDATE", fromUserName);
  710. WeChatUser update = new WeChatUser();
  711. update.setCandate(1);// 今晚有空
  712. weChatUserDao.update(update, new WeChatUser(fromUserName));
  713. WeChatUser weChatUser = weChatUserDao.select(new WeChatUser(fromUserName));
  714. if (Doubles.isFinite(weChatUser.getLatitude()) && Doubles.isFinite(weChatUser.getLongitude()))
  715. {
  716. if (StringUtils.isBlank(weChatUser.getSex()))
  717. {
  718. TextMsgVo textMsgVo = null;
  719. textMsgVo = new TextMsgVo(fromUserName, toUserName, createTime);
  720. textMsgVo.setContent("您还没有填写您的性别信息");
  721. result = sendTextMsg(textMsgVo);
  722. logger.info("handleTextMsg return {}", result);
  723. return result;
  724. }
  725. else
  726. {
  727. // 设置成异性
  728. if (weChatUser.getSex().equals("1"))
  729. {
  730. weChatUser.setSex("2");
  731. }
  732. else
  733. {
  734. weChatUser.setSex("1");
  735. }
  736. }
  737. List<WeChatUser> list = weChatUserDao.selectNearUser(weChatUser);
  738. if (list.size() == 0)
  739. {
  740. TextMsgVo textMsgVo = null;
  741. textMsgVo = new TextMsgVo(fromUserName, toUserName, createTime);
  742. textMsgVo.setContent("您附近1公里内还没有其他用户今天有空");
  743. result = sendTextMsg(textMsgVo);
  744. logger.info("handleTextMsg return {}", result);
  745. return result;
  746. }
  747. ImgTextMsgVo imgTextMsgVo = new ImgTextMsgVo(fromUserName, toUserName, createTime);
  748. List<Article> articles = new ArrayList<Article>();
  749. for (WeChatUser weChatUser1 : list)
  750. {
  751. Article article = new Article(weChatUser1.getNickname(), "进入给他留言可直接发送至他的微信", weChatUser1.getHeadimgurl(), weburl
  752. + "wechatuser/detail?fromid=" + weChatUser1.getFromid() + "&viewid=" + fromUserName);
  753. articles.add(article);
  754. }
  755. imgTextMsgVo.setList(articles);
  756. imgTextMsgVo.setMsgType("news");
  757. result = sendTWMsg(imgTextMsgVo);
  758. return result;
  759. }
  760. else
  761. {
  762. TextMsgVo textMsgVo = null;
  763. textMsgVo = new TextMsgVo(fromUserName, toUserName, createTime);
  764. textMsgVo.setContent("您还没有开启提供位置信息,请点击右上角人形图标打开提供位置信息开关");
  765. result = sendTextMsg(textMsgVo);
  766. logger.info("handleTextMsg return {}", result);
  767. return result;
  768. }
  769. }
  770. else if (eventKey.getText().equals("V1002_VIEWACTIVITY"))
  771. {
  772. TextMsgVo textMsgVo = null;
  773. WeChatUser weChatUser = weChatUserDao.selectRecommondUser(new WeChatUser(fromUserName));
  774. if (weChatUser == null)
  775. {
  776. textMsgVo = new TextMsgVo(fromUserName, toUserName, createTime);
  777. textMsgVo.setContent("请您先选择会员-上传形象照");
  778. result = sendTextMsg(textMsgVo);
  779. logger.info("handleTextMsg return {}", result);
  780. return result;
  781. }
  782. // 查看附近约会
  783. WeChatUser wu = weChatUserDao.select(new WeChatUser(fromUserName));
  784. if (wu.getLatitude() == null || wu.getLongitude() == null)
  785. {
  786. TextMsgVo vo = new TextMsgVo(fromUserName, toUserName, createTime);
  787. vo.setContent("您还没有开启提供位置信息,请点击右上角人形图标打开提供位置信息开关");
  788. result = sendTextMsg(vo);
  789. logger.info("handleTextMsg return {}", result);
  790. return result;
  791. }
  792. ImgTextMsgVo imgTextMsgVo = new ImgTextMsgVo(fromUserName, toUserName, createTime);
  793. List<Article> articles = new ArrayList<Article>();
  794. List<Huodong> list = huodongDao.selectNear(wu.getLatitude(), wu.getLongitude(), 5);
  795. if (list == null || list.size() == 0)
  796. {
  797. TextMsgVo vo = new TextMsgVo(fromUserName, toUserName, createTime);
  798. vo.setContent("您附近暂时没有活动,您可以尝试发起一个活动");
  799. result = sendTextMsg(vo);
  800. logger.info("handleTextMsg return {}", result);
  801. return result;
  802. }
  803. else
  804. {
  805. for (Huodong huodong : list)
  806. {
  807. if (huodong.getHdname() == null)
  808. {
  809. huodong.setHdname("点击查看");
  810. }
  811. Article article = new Article(huodong.getHdname(), "进入后识别二维码添加联系人", huodong.getImgurl(), weburl
  812. + "huodong/huodongdetail?id=" + huodong.getId() + "&viewid=" + fromUserName);
  813. articles.add(article);
  814. }
  815. }
  816. imgTextMsgVo.setList(articles);
  817. imgTextMsgVo.setMsgType("news");
  818. result = sendTWMsg(imgTextMsgVo);
  819. return result;
  820. }
  821. }
  822. else if (event.getText().equals("subscribe"))
  823. {
  824. WeChatUser vo = new WeChatUser(fromUserName);
  825. String userInfo = getUserInfo(fromUserName);
  826. JSONObject jsonObject = JSON.parseObject(userInfo);
  827. String nickname = jsonObject.getString("nickname");
  828. String sex = jsonObject.getString("sex");
  829. String city = jsonObject.getString("city");
  830. String province = jsonObject.getString("province");
  831. String country = jsonObject.getString("country");
  832. String headimgurl = jsonObject.getString("headimgurl");
  833. vo.setNickname(nickname);
  834. vo.setSex(sex);
  835. vo.setProvince(province);
  836. vo.setCity(city);
  837. vo.setCountry(country);
  838. vo.setHeadimgurl(headimgurl);
  839. TextMsgVo textMsgVo = new TextMsgVo(fromUserName, toUserName, createTime);
  840. textMsgVo.setContent("欢迎关注\"他她社区\"!他她社区缘起于北京高校,是一个优质的单身青年婚恋交友平台!回复GG1,GG2,GG3...查看男生征婚信息,回复MM1,MM2,MM3,...查看女生征婚信息");
  841. result = sendTextMsg(textMsgVo);
  842. logger.info("handleTextMsg return {}", result);
  843. try
  844. {
  845. weChatUserDao.insert(vo);
  846. }
  847. catch (Exception e)
  848. {
  849. logger.error(e.getMessage(), e);
  850. }
  851. return result;
  852. }
  853. else if (event.getText().equals("LOCATION"))
  854. {
  855. String Latitude = rootElement.element("Latitude").getText();
  856. String Longitude = rootElement.element("Longitude").getText();
  857. WeChatUser weChatUser = new WeChatUser(fromUserName);
  858. weChatUser.setLatitude(Double.parseDouble(Latitude));
  859. weChatUser.setLongitude(Double.parseDouble(Longitude));
  860. WeChatUser wu = weChatUserDao.select(weChatUser);
  861. if (wu == null)
  862. {
  863. weChatUserDao.insert(weChatUser);
  864. }
  865. else
  866. {
  867. if (StringUtils.isBlank(wu.getProvince()))
  868. {
  869. // todo,增加根据经纬度获取省份
  870. }
  871. weChatUserDao.update(weChatUser, wu);
  872. }
  873. }
  874. else if (event.getText().equals("pic_photo_or_album"))
  875. {
  876. logger.info("pic_photo_or_album event");
  877. if (eventKey.getText().equals("V1001_SHOW"))
  878. {
  879. eventMap.put(fromUserName + createTime, "V1001_SHOW");
  880. }
  881. else
  882. {
  883. }
  884. }
  885. else if (event.getText().equals("pic_weixin"))
  886. {
  887. logger.info("pic_weixin event");
  888. if (eventKey.getText().equals("V1002_CREATEDATE"))
  889. {
  890. eventMap.put(fromUserName, "V1002_CREATEDATE");
  891. logger.info("map key is {},value V1002_CREATEDATE", fromUserName);
  892. }
  893. }
  894. else if (event.getText().equals("location_select"))
  895. {
  896. logger.info("location_select event");
  897. TextMsgVo textMsgVo = null;
  898. WeChatUser weChatUser = weChatUserDao.selectRecommondUser(new WeChatUser(fromUserName));
  899. if (weChatUser == null)
  900. {
  901. textMsgVo = new TextMsgVo(fromUserName, toUserName, createTime);
  902. textMsgVo.setContent("请您先选择会员-上传形象照");
  903. result = sendTextMsg(textMsgVo);
  904. logger.info("handleTextMsg return {}", result);
  905. return result;
  906. }
  907. }
  908. else if (event.getText().equals("SCAN"))
  909. {
  910. WeChatUserfrom wechatUserfrom = new WeChatUserfrom(fromUserName);
  911. wechatUserfrom.setEventkey(eventKey.getText());
  912. weChatUserfromDao.insert(wechatUserfrom);
  913. logger.info("scan ok");
  914. }
  915. return result;
  916. }
  917. private String handleOtherMsg(Element rootElement)
  918. {
  919. return "";
  920. }
  921. private void getBaseNode(Element rootElement, Node toUserName, Node fromUserName, Node createTime)
  922. {
  923. }
  924. public static String sendTextMsg(TextMsgVo vo)
  925. {
  926. StringBuffer sb = new StringBuffer();
  927. sb.append("<xml>")
  928. .append("<ToUserName><![CDATA[").append(vo.getFromUserName()).append("]]></ToUserName>")
  929. .append("<FromUserName><![CDATA[").append(vo.getToUserName()).append("]]></FromUserName>")
  930. .append("<CreateTime>").append(vo.getCreateTime()).append("</CreateTime>")
  931. .append("<MsgType><![CDATA[").append("text").append("]]></MsgType>")
  932. .append("<Content><![CDATA[").append(vo.getContent()).append("]]></Content>")
  933. .append("</xml>");
  934. return sb.toString();
  935. }
  936. private String sendImgVoiceMsg(ImgVoiceMsgVo vo)
  937. {
  938. StringBuffer sb = new StringBuffer();
  939. if (vo.getMsgType().equals("image"))
  940. {
  941. sb.append("<xml>")
  942. .append("<ToUserName><![CDATA[").append(vo.getFromUserName()).append("]]></ToUserName>")
  943. .append("<FromUserName><![CDATA[").append(vo.getToUserName()).append("]]></FromUserName>")
  944. .append("<CreateTime>").append(vo.getCreateTime()).append("</CreateTime>")
  945. .append("<MsgType><![CDATA[").append(vo.getMsgType()).append("]]></MsgType>")
  946. .append("<Image><MediaId><![CDATA[").append(vo.getMediaId()).append("]]></MediaId></Image>")
  947. .append("</xml>");
  948. }
  949. else if (vo.getMsgType().equals("voice"))
  950. {
  951. sb.append("<xml>")
  952. .append("<ToUserName><![CDATA[").append(vo.getFromUserName()).append("]]></ToUserName>")
  953. .append("<FromUserName><![CDATA[").append(vo.getToUserName()).append("]]></FromUserName>")
  954. .append("<CreateTime>").append(vo.getCreateTime()).append("</CreateTime>")
  955. .append("<MsgType><![CDATA[").append(vo.getMsgType()).append("]]></MsgType>")
  956. .append("<Voice><MediaId><![CDATA[").append(vo.getMediaId()).append("]]></MediaId></Voice>")
  957. .append("</xml>");
  958. }
  959. return sb.toString();
  960. }
  961. private String sendTWMsg(ImgTextMsgVo vo)
  962. {
  963. StringBuffer sb = new StringBuffer();
  964. sb.append("<xml>")
  965. .append("<ToUserName><![CDATA[").append(vo.getFromUserName()).append("]]></ToUserName>")
  966. .append("<FromUserName><![CDATA[").append(vo.getToUserName()).append("]]></FromUserName>")
  967. .append("<CreateTime>").append(vo.getCreateTime()).append("</CreateTime>")
  968. .append("<MsgType><![CDATA[").append(vo.getMsgType()).append("]]></MsgType>")
  969. .append("<ArticleCount><![CDATA[").append(vo.getList().size()).append("]]></ArticleCount>")
  970. .append("<Articles>");
  971. for (Article article : vo.getList())
  972. {
  973. sb.append("<item>");
  974. sb.append("<Title><![CDATA[").append(article.getTitle()).append("]]></Title>")
  975. .append("<Description><![CDATA[").append(article.getDescription()).append("]]></Description>")
  976. .append("<PicUrl><![CDATA[").append(article.getPicurl()).append("]]></PicUrl>")
  977. .append("<Url><![CDATA[").append(article.getUrl()).append("]]></Url>");
  978. sb.append("</item>");
  979. }
  980. sb.append("</Articles>");
  981. sb.append("</xml>");
  982. return sb.toString();
  983. }
  984. public String getUserInfo(String openid)
  985. {
  986. String userInfoUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + ATTimerTask.accessToken +
  987. "&openid=" + openid + "&lang=zh_CN";
  988. return HttpUtils.httpsCon(userInfoUrl);
  989. }
  990. public void sendKFMsg(WexinComment huodongComment, String seq)
  991. {
  992. String content = huodongComment.getContent();
  993. String[] args = content.split(" ");
  994. content = content.replaceAll(args[0], "");
  995. WeChatUser weChatUser = weChatUserDao.select(new WeChatUser(huodongComment.getFromid()));
  996. String cc = weChatUser.getNickname() + "给你留言:" + content + " (回复" + seq + huodongComment.getId() + " 空格 你要回复的内容,可直接向他发消息)";
  997. String result = HttpUtils.sendKFMsg(huodongComment.getToid(), cc);
  998. logger.info("comment success result {}", result);
  999. }
  1000. @RequestMapping(value = "emptyUserInfo")
  1001. @ResponseBody
  1002. public void getEmptyUserinfo()
  1003. {
  1004. List<WeChatUser> weChatUserList = weChatUserDao.selectEmptyUser();
  1005. if (weChatUserList != null)
  1006. {
  1007. for (WeChatUser weChatUser : weChatUserList)
  1008. {
  1009. WeChatUser update = new WeChatUser();
  1010. String userInfo = getUserInfo(weChatUser.getFromid());
  1011. JSONObject jsonObject = JSON.parseObject(userInfo);
  1012. String nickname = jsonObject.getString("nickname");
  1013. String sex = jsonObject.getString("sex");
  1014. String city = jsonObject.getString("city");
  1015. String province = jsonObject.getString("province");
  1016. String country = jsonObject.getString("country");
  1017. String headimgurl = jsonObject.getString("headimgurl");
  1018. logger.info("nickname {},sex {},city {},province {},country {},headimgurl {}",
  1019. nickname, sex, city, province, country, headimgurl);
  1020. update.setNickname(nickname);
  1021. update.setSex(sex);
  1022. update.setProvince(province);
  1023. update.setCity(city);
  1024. update.setCountry(country);
  1025. update.setHeadimgurl(headimgurl);
  1026. weChatUserDao.update(update, new WeChatUser(weChatUser.getFromid()));
  1027. }
  1028. }
  1029. }
  1030. }