从官方文档可以看出,他做到了简简单单,但没有做到明明白白。
那么接下来我首先说下文中的url,很多人都不知道这个url,其实他就是
当这些正准备好之后,直接上代码
//微信推送事件 url@RequestMapping(value = "/wx", method = RequestMethod.GET)@ResponseBodypublic void get(HttpServletRequest request, HttpServletResponse response)throws Exception {boolean isGet = request.getMethod().toLowerCase().equals("get");if (isGet) {// 微信加密签名String signature = request.getParameter("signature");// 时间戳String timestamp = request.getParameter("timestamp");// 随机数String nonce = request.getParameter("nonce");// 随机字符串String echostr = request.getParameter("echostr");// 通过检验signature对请求进行校验,若校验成功则原样返回echostr,表示接入成功,否则接入失败if (signature != null && CheckoutUtil.checkSignature(signature, timestamp, nonce)) {try {boolean flag = CheckoutUtil.checkSignature(signature, timestamp, nonce);System.out.println(flag);PrintWriter print = response.getWriter();print.write(echostr);System.out.println(echostr);print.flush();print.close();} catch (IOException e) {e.printStackTrace();}}}}
这个方法是你配置Url的时候他会请求这个地址,验证地址的准确性,请求通过下一步:
@RequestMapping(value = "/wx", method = RequestMethod.POST)@ResponseBodypublic String responseMsg(HttpServletRequest req, HttpServletResponse resp) throws IOException {req.setCharacterEncoding("UTF-8");String message = "success";try {//把微信返回的xml信息转义成mapMap<String, String> map = XmlUtil.xmlToMap(req);String fromUserName = map.get("FromUserName");//这个就是你关注公众号的openId)String toUserName = map.get("ToUserName");//这个是用户微信的idString msgType = map.get("MsgType");//消息类型(event或者text)System.out.println("消息来自(公众号的openId):" + fromUserName);System.out.println("消息类型为:" + msgType);String eventType = map.get("Event");//事件类型JSONObject unionIdOpenId = getUnionIdOpenId(fromUserName);String unionid = unionIdOpenId.getStr("unionid");String nickname = unionIdOpenId.getStr("nickname");String subscribe_time = unionIdOpenId.getStr("subscribe_time");Date date=new Date();if (!StringUtil.isEmpty(subscribe_time)){date = DateUtil.LongToDate(Long.valueOf(subscribe_time));System.out.println("关注取消的时间是======"+date);}//根据unionid获取数据库里的用户增加公众号的openIdif (MessageUtil.MSGTYPE_EVENT.equals(msgType)) {//事件类型的监听if (MessageUtil.SUBSCIBE_EVENT.equals(eventType)) {//关注取消事件的监听String content = "欢迎关注,这里会带给你不一样的惊喜!";String msg = "@" + nickname + "," + content;System.out.println("事件类型为:关注公众号 =======" + eventType+";时间是:"+date);message = MessageUtil.subscribeForText(toUserName, fromUserName, msg);} else if (MessageUtil.UNSUBSCIBE_EVENT.equals(eventType)) {//处理取消订阅事件System.out.println("事件类型为:取消订阅事件------" + eventType+";时间是:"+date);message = MessageUtil.unsubscribe(toUserName, fromUserName);}} } catch (DocumentException e) {e.printStackTrace();}System.out.println("关注微信公众号自动回复的消息内容为:" + message);return message;}
这里面就可以写各种逻辑了,我这边是通过公众号发送小程序里的消息 获取到了unionid,然后通过unionid获取到了用户增加公众号的openid,这样发送消息的时候就可以通过公众号openId直接给用户推送消息,如下:
第一次写,可能也是简简单单。注意两个代码段的地址保持一致,只是请求方式不同。
交流微信:18611177866