Browse Source

fix:处理微信公众号请求信息

wrj 1 year ago
parent
commit
a6bd815174

+ 104 - 0
nightFragrance-admin/src/main/java/com/ylx/web/controller/massage/WeChatController.java

@@ -36,9 +36,15 @@ import org.springframework.web.bind.annotation.*;
 import org.springframework.web.multipart.MultipartFile;
 
 import javax.annotation.Resource;
+import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
+import java.io.BufferedReader;
 import java.io.File;
+import java.io.InputStream;
+import java.io.InputStreamReader;
 import java.util.Arrays;
+import java.util.Date;
+import java.util.HashMap;
 import java.util.Map;
 
 import static com.ylx.massage.utils.OtherUtil.verification;
@@ -137,6 +143,104 @@ public class WeChatController extends BaseController {
 
     }
 
+    /**
+     * 处理微信公众号请求信息
+     * @param request
+     * @return
+     */
+    @RequestMapping("/verifyToken")
+    @ResponseBody
+    @Log(title = "处理微信公众号请求信息", businessType = BusinessType.OTHER)
+    public String handlePublicMsg(HttpServletRequest request) throws Exception {
+        log.info("处理微信公众号请求信息:{}", request.toString());
+        // 获得微信端返回的xml数据
+        InputStream is = null;
+        InputStreamReader isr = null;
+        BufferedReader br = null;
+        try {
+            is = request.getInputStream();
+            isr = new InputStreamReader(is, "utf-8");
+            br = new BufferedReader(isr);
+            String str = null;
+            StringBuffer returnXml= new StringBuffer();
+            while ((str = br.readLine()) != null) {
+                //返回的是xml数据
+                returnXml.append(str);
+            }
+            log.info("微信端返回的xml数据:{}", returnXml.toString());
+            Map<String, String> encryptMap = WeChatUtil.xmlToMap(returnXml.toString());
+            // 得到公众号传来的加密信息并解密,得到的是明文xml数据
+//            String decryptXml = WXPublicUtils.decrypt(encryptMap.get("Encrypt"));
+            // 将xml数据转换为map
+//            Map<String, String> decryptMap = WeChatUtil.xmlToMap(decryptXml);
+
+            // 区分消息类型
+            String msgType = encryptMap.get("MsgType");
+            // 普通消息
+            if ("text".equals(msgType)) { // 文本消息
+                // todo 处理文本消息
+            } else if ("image".equals(msgType)) { // 图片消息
+                // todo 处理图片消息
+            } else if ("voice".equals(msgType)) { //语音消息
+                // todo 处理语音消息
+            } else if ("video".equals(msgType)) { // 视频消息
+                // todo 处理视频消息
+            } else if ("shortvideo".equals(msgType)) { // 小视频消息
+                // todo 处理小视频消息
+            } else if ("location".equals(msgType)) { // 地理位置消息
+                // todo 处理地理位置消息
+            } else if ("link".equals(msgType)) { // 链接消息
+                // todo 处理链接消息
+            }
+            // 事件推送
+            else if ("event".equals(msgType)) { // 事件消息
+                // 区分事件推送
+                String event = encryptMap.get("Event");
+                if ("subscribe".equals(event)) { // 订阅事件 或 未关注扫描二维码事件
+                    // 返回消息时ToUserName的值与FromUserName的互换
+                    Map<String, String> returnMap = new HashMap<>();
+                    returnMap.put("ToUserName", encryptMap.get("FromUserName"));
+                    returnMap.put("FromUserName", encryptMap.get("ToUserName"));
+                    returnMap.put("CreateTime", new Date().getTime()+"");
+                    returnMap.put("MsgType", "text");
+                    returnMap.put("Content", "https://www.baidu.com");
+                    String encryptMsg = weChatUtil.mapToXml(returnMap).toString();
+                    return encryptMsg;
+                }  else if ("unsubscribe".equals(event)) { // 取消订阅事件
+                    // todo 处理取消订阅事件
+                } else if ("SCAN".equals(event)) { // 已关注扫描二维码事件
+                    // 返回消息时ToUserName的值与FromUserName的互换
+                    Map<String, String> returnMap = new HashMap<>();
+                    returnMap.put("ToUserName", encryptMap.get("FromUserName"));
+                    returnMap.put("FromUserName", encryptMap.get("ToUserName"));
+                    returnMap.put("CreateTime", new Date().getTime()+"");
+                    returnMap.put("MsgType", "text");
+                    returnMap.put("Content", "https://www.baidu.com");
+                    String encryptMsg = WeChatUtil.mapToXml(returnMap).toString();
+                    return encryptMsg;
+                } else if ("LOCATION".equals(event)) { // 上报地理位置事件
+                    // todo 处理上报地理位置事件
+                } else if ("CLICK".equals(event)) { // 点击菜单拉取消息时的事件推送事件
+                    // todo 处理点击菜单拉取消息时的事件推送事件
+                } else if ("VIEW".equals(event)) { // 点击菜单跳转链接时的事件推送
+                    // todo 处理点击菜单跳转链接时的事件推送
+                }
+            }
+        } catch (Exception e) {
+            logger.error("处理微信公众号请求信息,失败", e);
+        } finally {
+            if (null != is) {
+                is.close();
+            }
+            if (null != isr) {
+                isr.close();
+            }
+            if (null != br) {
+                br.close();
+            }
+        }
+        return null;
+    }
     /**
      * 获取微信code
      *

+ 90 - 0
nightFragrance-massage/src/main/java/com/ylx/massage/utils/WeChatUtil.java

@@ -11,10 +11,23 @@ import com.ylx.common.config.WechatAccountConfig;
 import com.ylx.common.exception.ServiceException;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.stereotype.Component;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
 
 import javax.annotation.Resource;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
+import java.io.StringWriter;
 import java.io.UnsupportedEncodingException;
 import java.net.URLEncoder;
+import java.util.HashMap;
 import java.util.Map;
 
 
@@ -173,4 +186,81 @@ public class WeChatUtil {
         return map;
 
     }
+
+
+    /**
+     * XML格式字符串转换为Map
+     *
+     * @param strXML XML字符串
+     * @return XML数据转换后的Map
+     * @throws Exception
+     */
+    public static Map<String, String> xmlToMap(String strXML) throws Exception {
+        try {
+            Map<String, String> data = new HashMap<>();
+            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
+            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
+            InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
+            org.w3c.dom.Document doc = documentBuilder.parse(stream);
+            doc.getDocumentElement().normalize();
+            NodeList nodeList = doc.getDocumentElement().getChildNodes();
+            for (int idx = 0; idx < nodeList.getLength(); ++idx) {
+                Node node = nodeList.item(idx);
+                if (node.getNodeType() == Node.ELEMENT_NODE) {
+                    org.w3c.dom.Element element = (org.w3c.dom.Element) node;
+                    data.put(element.getNodeName(), element.getTextContent());
+                }
+            }
+            try {
+                stream.close();
+            } catch (Exception ex) {
+                // do nothing
+            }
+            return data;
+        } catch (Exception ex) {
+            log.error("Invalid XML, can not convert to map. Error message: {}. XML content: {}", ex.getMessage(), strXML);
+            throw ex;
+        }
+    }
+
+    /**
+     * 将Map转换为XML格式的字符串
+     *
+     * @param data Map类型数据
+     * @return XML格式的字符串
+     * @throws Exception
+     */
+    public static String mapToXml(Map<String, String> data) throws Exception {
+        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
+        DocumentBuilder documentBuilder= documentBuilderFactory.newDocumentBuilder();
+        org.w3c.dom.Document document = documentBuilder.newDocument();
+        org.w3c.dom.Element root = document.createElement("xml");
+        document.appendChild(root);
+        for (String key: data.keySet()) {
+            String value = data.get(key);
+            if (value == null) {
+                value = "";
+            }
+            value = value.trim();
+            org.w3c.dom.Element filed = document.createElement(key);
+            filed.appendChild(document.createTextNode(value));
+            root.appendChild(filed);
+        }
+        TransformerFactory tf = TransformerFactory.newInstance();
+        Transformer transformer = tf.newTransformer();
+        DOMSource source = new DOMSource(document);
+        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
+        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
+        StringWriter writer = new StringWriter();
+        StreamResult result = new StreamResult(writer);
+        transformer.transform(source, result);
+        String output = writer.getBuffer().toString(); //.replaceAll("\n|\r", "");
+        try {
+            writer.close();
+        } catch (Exception ex) {
+
+        }
+        return output;
+    }
+
 }

+ 1 - 1
nightFragrance-massage/src/main/resources/mapper/massage/CouponReceiveMapper.xml

@@ -38,7 +38,7 @@
 
 
     <sql id="selectCouponReceiveVo">
-        a.id, a.openid, a.coupon_id, a.expiration_time, a.create_time, a.update_time, a.is_delete,a.use_state
+        a.id, a.openid, a.coupon_id, a.expiration_time, a.create_time, a.update_time, a.is_delete,a.use_state,
          b.name, b.type, b.discount_type, b.discount_value, b.threshold_amount, b.obtain_way, b.term_days, b.status, b.used_num, b.user_limit, b.ext_param
     </sql>
     <!-- 批量插入 -->