浏览代码

fixed: 提交公众号订阅相关内容

orgycat 3 年之前
父节点
当前提交
6987ecc13a

+ 134 - 134
src/main/java/com/care/client/controller/WxMsgController.java

@@ -1,107 +1,105 @@
-//package com.care.client.controller;
-//
-//import cn.hutool.core.util.XmlUtil;
-//import cn.hutool.json.JSONObject;
-//import com.care.common.entity.CareOfficialMemberInfo;
-//import com.care.common.service.CareOfficialMemberInfoService;
-//import com.care.common.service.WxTemplateService;
-//import com.care.common.util.CheckoutUtil;
-//import com.care.common.util.MessageUtil;
-//import com.care.client.vo.WxAccessTokenVO;
-//import com.care.common.util.WxTemplateUtil;
-//import lombok.extern.slf4j.Slf4j;
-//import org.apache.commons.lang3.ObjectUtils;
-//import org.springframework.stereotype.Controller;
-//import org.springframework.web.bind.annotation.RequestMapping;
-//import org.springframework.web.bind.annotation.RequestMethod;
-//import org.springframework.web.bind.annotation.ResponseBody;
-//import org.w3c.dom.Document;
-//import org.w3c.dom.Element;
-//
-//import javax.annotation.Resource;
-//import javax.servlet.http.HttpServletRequest;
-//import javax.servlet.http.HttpServletResponse;
-//import java.io.IOException;
-//import java.io.PrintWriter;
-//import java.util.Date;
-//import java.util.Map;
-//
-//@Controller
-//@RequestMapping("/wxmsg")
-//@Slf4j
-//public class WxMsgController {
-//
+package com.care.client.controller;
+
+import cn.hutool.core.util.XmlUtil;
+import cn.hutool.json.JSONObject;
+import com.care.client.vo.WxAccessTokenVO;
+import com.care.common.service.WxTemplateService;
+import com.care.common.util.CheckoutUtil;
+import com.care.common.util.MessageUtil;
+import com.care.common.util.WxTemplateUtil;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.ObjectUtils;
+import org.springframework.stereotype.Controller;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.ResponseBody;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+import javax.annotation.Resource;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.util.Map;
+
+@Controller
+@RequestMapping("/wxmsg")
+@Slf4j
+public class WxMsgController {
+
 //    @Resource
 //    private CareOfficialMemberInfoService careOfficialMemberInfoService;
-//
-////    @Resource
-////    private CareMemberInfoService careMemberInfoService;
-//
+
 //    @Resource
-//    private WxTemplateService wxService;
-//
-//    /**
-//     * 微信消息接收和token验证
-//     * @param request
-//     * @param response
-//     * @throws IOException
-//     */
-//        @RequestMapping(value="/checkToken",method= RequestMethod.GET)
-//    public void weChat(HttpServletRequest request, HttpServletResponse response) throws IOException {
-//        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();
-//                }
-//            }
-//        }
-//    }
-//
-//    @RequestMapping(value="/checkToken",method=RequestMethod.POST)
-//    @ResponseBody
-//    public String  responseEvent(HttpServletRequest req, HttpServletResponse resp)throws IOException {
-//        req.setCharacterEncoding("UTF-8");
-//        resp.setCharacterEncoding("UTF-8");
-//        String message = "success";
-//        try {
-//            WxAccessTokenVO wxAccessTokenVO = wxService.processAccessToken();
-//            if (wxAccessTokenVO == null) {
-//                return "failure";
-//            }
-//            // 读取输入流
-//            Document document = XmlUtil.readXML(req.getInputStream());
-//            // 得到xml根元素
-//            Element element = document.getDocumentElement();
-//            //把微信返回的xml信息转义成map
-//            Map<String, Object> map = XmlUtil.xmlToMap(element);
-//            System.out.println("微信接收到的消息为:"+map.toString());
-//            String fromUserName = ObjectUtils.toString(map.get("FromUserName"));//消息来源用户标识
-//            String msgType = ObjectUtils.toString(map.get("MsgType"));//消息类型(event或者text)
-//            String eventType = ObjectUtils.toString(map.get("Event"));//事件类型
-////            String nickName = getUserNickName(fromUserName);
-//            if(MessageUtil.MSGTYPE_EVENT.equals(msgType)){//如果为事件类型
-//                if(MessageUtil.SUBSCIBE_EVENT.equals(eventType)){//处理订阅事件
-//                    JSONObject parseUnionObject = WxTemplateUtil.parseWxOpenIdBySubscribe(wxAccessTokenVO.getAccessToken(), fromUserName);
-////                    parseUnionObject.set("unionid", "oyVYT6Ox9b88n_33lgKWRj5uFbUY");
-//                    if (parseUnionObject != null && parseUnionObject.containsKey("unionid")) {
+//    private CareMemberInfoService careMemberInfoService;
+
+    @Resource
+    private WxTemplateService wxService;
+
+    /**
+     * 微信消息接收和token验证
+     * @param request
+     * @param response
+     * @throws IOException
+     */
+        @RequestMapping(value="/checkToken",method= RequestMethod.GET)
+    public void weChat(HttpServletRequest request, HttpServletResponse response) throws IOException {
+        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();
+                }
+            }
+        }
+    }
+
+    @RequestMapping(value="/checkToken",method=RequestMethod.POST)
+    @ResponseBody
+    public String  responseEvent(HttpServletRequest req, HttpServletResponse resp)throws IOException {
+        req.setCharacterEncoding("UTF-8");
+        resp.setCharacterEncoding("UTF-8");
+        String message = "success";
+        try {
+            WxAccessTokenVO wxAccessTokenVO = wxService.processAccessToken();
+            if (wxAccessTokenVO == null) {
+                return "failure";
+            }
+            // 读取输入流
+            Document document = XmlUtil.readXML(req.getInputStream());
+            // 得到xml根元素
+            Element element = document.getDocumentElement();
+            //把微信返回的xml信息转义成map
+            Map<String, Object> map = XmlUtil.xmlToMap(element);
+            System.out.println("微信接收到的消息为:"+map.toString());
+            String fromUserName = ObjectUtils.toString(map.get("FromUserName"));//消息来源用户标识
+            String msgType = ObjectUtils.toString(map.get("MsgType"));//消息类型(event或者text)
+            String eventType = ObjectUtils.toString(map.get("Event"));//事件类型
+//            String nickName = getUserNickName(fromUserName);
+            if(MessageUtil.MSGTYPE_EVENT.equals(msgType)){//如果为事件类型
+                if(MessageUtil.SUBSCIBE_EVENT.equals(eventType)){//处理订阅事件
+                    JSONObject parseUnionObject = WxTemplateUtil.parseWxOpenIdBySubscribe(wxAccessTokenVO.getAccessToken(), fromUserName);
+                    System.out.println("parseUnionObject:"+parseUnionObject.toString());
+//                    parseUnionObject.set("unionid", "oyVYT6Ox9b88n_33lgKWRj5uFbUY");
+                    if (parseUnionObject != null && parseUnionObject.containsKey("unionid")) {
 //                        CareOfficialMemberInfo careOfficialMemberInfo = new CareOfficialMemberInfo();
 //                        careOfficialMemberInfo.setNickname(parseUnionObject.getStr("nickname"));
 //                        careOfficialMemberInfo.setOpenId(fromUserName);
@@ -115,44 +113,46 @@
 //                        } else {
 //                            return "failure";
 //                        }
-//                    }
-//                } else if (MessageUtil.UNSUBSCIBE_EVENT.equals(eventType)) {//处理取消订阅事件
-//                    System.out.println("事件类型为:"+eventType);
-//                    JSONObject parseUnionObject = WxTemplateUtil.parseWxOpenIdBySubscribe(wxAccessTokenVO.getAccessToken(), fromUserName);
-//                    if (parseUnionObject != null && parseUnionObject.containsKey("unionid")) {
+                        return "success";
+                    }
+                } else if (MessageUtil.UNSUBSCIBE_EVENT.equals(eventType)) {//处理取消订阅事件
+                    System.out.println("事件类型为:"+eventType);
+                    JSONObject parseUnionObject = WxTemplateUtil.parseWxOpenIdBySubscribe(wxAccessTokenVO.getAccessToken(), fromUserName);
+                    if (parseUnionObject != null && parseUnionObject.containsKey("unionid")) {
 //                        boolean updated = careOfficialMemberInfoService.cancelSubscribe(parseUnionObject.getStr("unionid"));
 //                        if (updated) {
 //                            return "success";
 //                        } else {
 //                            return "failure";
 //                        }
+                    }
+                    return "success";
+//                    message = MessageUtil.unsubscribe(toUserName, fromUserName);
+                }
+            }else {
+//                //微信消息分为事件推送消息和普通消息,非事件即为普通消息类型
+//                switch (msgType) {
+//                    case "text":{//文本消息
+//                        String content = map.get("Content");//用户发的消息内容
+//                        content = "您发的消息内容是:"+content+",如需帮助,请联系";
+//                        message = MessageUtil.replyMsg(toUserName, fromUserName,content,"text");
+//                        break;
+//                    }
+//                    case "image":{//图片消息
+//                        String content = "您发的消息内容是图片,如需帮助,请联系";
+//                        message = MessageUtil.replyMsg(toUserName, fromUserName,content,"text");
+//                        break;
+//                    }
+//                    default:{//其他类型的普通消息
+//                        break;
 //                    }
-////                    message = MessageUtil.unsubscribe(toUserName, fromUserName);
 //                }
-//            }else {
-////                //微信消息分为事件推送消息和普通消息,非事件即为普通消息类型
-////                switch (msgType) {
-////                    case "text":{//文本消息
-////                        String content = map.get("Content");//用户发的消息内容
-////                        content = "您发的消息内容是:"+content+",如需帮助,请联系";
-////                        message = MessageUtil.replyMsg(toUserName, fromUserName,content,"text");
-////                        break;
-////                    }
-////                    case "image":{//图片消息
-////                        String content = "您发的消息内容是图片,如需帮助,请联系";
-////                        message = MessageUtil.replyMsg(toUserName, fromUserName,content,"text");
-////                        break;
-////                    }
-////                    default:{//其他类型的普通消息
-////                        break;
-////                    }
-////                }
-//            }
-//        } catch (Exception e) {
-//            e.printStackTrace();
-//        }
-//        System.out.println("关注微信公众号自动回复的消息内容为:" + message);
-//        return message;
-//    }
-//
-//}
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        System.out.println("关注微信公众号自动回复的消息内容为:" + message);
+        return message;
+    }
+
+}

+ 53 - 53
src/main/java/com/care/common/util/CheckoutUtil.java

@@ -1,53 +1,53 @@
-//package com.care.common.util;
-//
-//import java.security.MessageDigest;
-//import java.security.NoSuchAlgorithmException;
-//import java.util.Arrays;
-//import java.util.Formatter;
-//
-//public class CheckoutUtil {
-//
-//    // 与测试账号接口配置信息中的Token要一致
-//    private static String token = "yuanbaotoken";
-//
-//    /**
-//     * 验证签名
-//     * @param signature
-//     * @param timestamp
-//     * @param nonce
-//     * @return
-//     */
-//    public static boolean checkSignature(String signature, String timestamp, String nonce) {
-//        String[] arr = new String[] { token, timestamp, nonce };
-//        Arrays.sort(arr);// 将token、timestamp、nonce三个参数进行字典序排序
-//        StringBuilder content = new StringBuilder();
-//        for (int i = 0; i < arr.length; i++) {
-//            content.append(arr[i]);
-//        }
-//        MessageDigest md = null;
-//        String tmpStr = null;
-//
-//        try {
-//            md = MessageDigest.getInstance("SHA-1");
-//            // 将三个参数字符串拼接成一个字符串进行sha1加密
-//            byte[] digest = md.digest(content.toString().getBytes());
-//            tmpStr = byteToHex(digest );
-//        } catch (NoSuchAlgorithmException e) {
-//            e.printStackTrace();
-//        }
-//        // 将sha1加密后的字符串可与signature对比,标识该请求来源于微信
-//        return tmpStr != null ? tmpStr.equals(signature) : false;
-//    }
-//
-//    //十六进制字节数组转为字符串
-//    private static String byteToHex(final byte[] hash) {
-//        Formatter formatter = new Formatter();
-//        for (byte b : hash) {
-//            formatter.format("%02x", b);
-//        }
-//        String result = formatter.toString();
-//        formatter.close();
-//        return result;
-//    }
-//
-//}
+package com.care.common.util;
+
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.Arrays;
+import java.util.Formatter;
+
+public class CheckoutUtil {
+
+    // 与测试账号接口配置信息中的Token要一致
+    private static String token = "yu-an-bao-Bss734jHs-token";
+
+    /**
+     * 验证签名
+     * @param signature
+     * @param timestamp
+     * @param nonce
+     * @return
+     */
+    public static boolean checkSignature(String signature, String timestamp, String nonce) {
+        String[] arr = new String[] { token, timestamp, nonce };
+        Arrays.sort(arr);// 将token、timestamp、nonce三个参数进行字典序排序
+        StringBuilder content = new StringBuilder();
+        for (int i = 0; i < arr.length; i++) {
+            content.append(arr[i]);
+        }
+        MessageDigest md = null;
+        String tmpStr = null;
+
+        try {
+            md = MessageDigest.getInstance("SHA-1");
+            // 将三个参数字符串拼接成一个字符串进行sha1加密
+            byte[] digest = md.digest(content.toString().getBytes());
+            tmpStr = byteToHex(digest );
+        } catch (NoSuchAlgorithmException e) {
+            e.printStackTrace();
+        }
+        // 将sha1加密后的字符串可与signature对比,标识该请求来源于微信
+        return tmpStr != null ? tmpStr.equals(signature) : false;
+    }
+
+    //十六进制字节数组转为字符串
+    private static String byteToHex(final byte[] hash) {
+        Formatter formatter = new Formatter();
+        for (byte b : hash) {
+            formatter.format("%02x", b);
+        }
+        String result = formatter.toString();
+        formatter.close();
+        return result;
+    }
+
+}

+ 11 - 11
src/main/java/com/care/common/util/MessageUtil.java

@@ -1,11 +1,11 @@
-//package com.care.common.util;
-//
-//public interface MessageUtil {
-//
-//    String MSGTYPE_EVENT = "event";
-//
-//    String SUBSCIBE_EVENT = "subscribe";
-//
-//    String UNSUBSCIBE_EVENT = "unsubscribe";
-//
-//}
+package com.care.common.util;
+
+public interface MessageUtil {
+
+    String MSGTYPE_EVENT = "event";
+
+    String SUBSCIBE_EVENT = "subscribe";
+
+    String UNSUBSCIBE_EVENT = "unsubscribe";
+
+}