zoukankan      html  css  js  c++  java
  • 微信公众号开发基础篇(六)

    一、之前实现了关注后的消息回复,现在实现按照关键字回复

    二、查看消息类型

           

    三、关注微信号的时候,会出发关注事件

    四、修改代码

           1、书写一些常量(修改MessageUtils )

     1 public class MessageUtils {
     2 
     3     // 书写一些常量(会经常用到)
     4     // 文本消息
     5     public static final String MESSAGE_TEXT = "text";
     6     // 图片消息
     7     public static final String MESSAGE_IMAGE = "image";
     8     // 语音消息
     9     public static final String MESSAGE_VOICE = "voice";
    10     // 视频消息
    11     public static final String MESSAGE_VIDEO = "video";
    12     // 链接消息
    13     public static final String MESSAGE_LINK = "link";
    14     // 地理位置消息
    15     public static final String MESSAGE_LOCATION = "location";
    16     // 事件推送
    17     public static final String MESSAGE_EVENT = "event";
    18     // 关注
    19     public static final String MESSAGE_SUBSCRIBE = "subscribe";
    20     // 取消关注
    21     public static final String MESSAGE_UNSUBSCRIBE = "unsubscribe";
    22     // 菜单点击
    23     public static final String MESSAGE_CLICK = "click";
    24     // 菜单查看
    25     public static final String MESSAGE_VIEW = "view";

              2、text换为MessageUtils.MESSAGE_TEXT常量(修改WeXinServlet)

     1 if (MessageUtils.MESSAGE_TEXT.equals(msgType)) {
     2 
     3      //原来的消息代码
     4 
     5 }// 事件推送的逻辑处理
     6             else if (MessageUtils.MESSAGE_EVENT.equals(msgType)) {
     7 
     8         // 获取事件
     9         String eventType = map.get("event");
    10         // 关注后的逻辑处理
    11         if (MessageUtils.MESSAGE_SUBSCRIBE.equals(eventType)) {
    12 
    13                     
    14         }
    15 }

          3、修改MessageUtils,添加方法

     1 /**
     2      * // 1.拼接一个主菜单(这个是消息菜单,在关注微信公众号后,自动回复一个消息)
     3      */
     4     public static String menuText() {
     5         StringBuffer stringBuffer = new StringBuffer();
     6         stringBuffer.append("欢迎您的关注,请按照菜单提示进行操作:
    
    ");
     7         stringBuffer.append("1、公司介绍 
    ");
     8         stringBuffer.append("2、主营产品介绍
    
    ");
     9         stringBuffer.append("**回复?调出此菜单。**");
    10         return stringBuffer.toString();
    11 }

          4、添加另一个方法

     1 /**
     2      * 2.拼接文本消息的
     3      */
     4     public static String initText(String toUserName, String fromUserName,
     5             String content) {
     6         TextMessage textMessage = new TextMessage();
     7         textMessage.setFromUserName(toUserName);
     8         textMessage.setToUserName(fromUserName);
     9         // 换成常量
    10         textMessage.setMsgType(MessageUtils.MESSAGE_TEXT);
    11         textMessage.setCreateTime(new Date().getTime());
    12         textMessage.setContent("您发送的消息是 :" + content);
    13         return textMessageToXml(textMessage);
    14 }

         5、添加到WeXinServlet

    1 // 关注后的逻辑处理
    2                 if (MessageUtils.MESSAGE_SUBSCRIBE.equals(eventType)) {
    3                     //消息的位置
    4                     message = MessageUtils.initText(toUserName, fromUserName,
    5                             MessageUtils.menuText());
    6 }

        6、判断消息回复(规则设置,红色为添加部分)

     1 // 如果是文本消息,就进行回复
     2             if (MessageUtils.MESSAGE_TEXT.equals(msgType)) {
     3 
     4                 // 判断消息回复(规则设置)
     5                 if ("1".equals(content)) {
     6                     message = MessageUtil.initText(toUserName, fromUserName,
     7                             MessageUtil.firstMenu());
     8                 } else if ("2".equals(content)) {
     9                     message = MessageUtil.initNewsMessage(toUserName,
    10                             fromUserName);
    11                 } else if (("?".equals(content)) || ("?".equals(content))) {
    12                     message = MessageUtils.initText(toUserName, fromUserName,
    13                             MessageUtils.menuText());
    14                 }
    15 
    16 }

    7、添加规则回复(MessageUtils中增加)

     1 /**
     2      * 添加新的规则,当输入1的时候返回的数据
     3      */
     4 
     5     public static String firstMenu() {
     6         StringBuffer stringBuffer = new StringBuffer();
     7         stringBuffer
     8                 .append("总部杭州。
    
    ");
     9         return stringBuffer.toString();
    10     }
    11 
    12     /**
    13      * 添加新的规则,当输入2的时候返回的数据
    14      * 
    15      * @return
    16      */
    17     public static String secondMenu() {
    18         StringBuffer stringBuffer = new StringBuffer();
    19         stringBuffer
    20                 .append("公司主要产品为技术开发、技术服务等。
    
    ");
    21         return stringBuffer.toString();
    22     }

    8、WeXinServlet中判断

     1 // 如果是文本消息,就进行回复
     2             if (MessageUtils.MESSAGE_TEXT.equals(msgType)) {
     3 
     4                 // 判断消息回复(规则设置)
     5                 if ("1".equals(content)) {
     6                     message = MessageUtils.initText(toUserName, fromUserName,
     7                             MessageUtils.firstMenu());
     8                 } else if ("2".equals(content)) {
     9                     message = MessageUtils.initText(toUserName, fromUserName,
    10                             MessageUtils.secondMenu());
    11                 } else if (("?".equals(content)) || ("?".equals(content))) {
    12                     message = MessageUtils.initText(toUserName, fromUserName,
    13                             MessageUtils.menuText());
    14                 }
    15 
    16             }
    17             // 事件推送的逻辑处理
    18             else if (MessageUtils.MESSAGE_EVENT.equals(msgType)) {
    19 
    20 }

    9、重新启动Tomcat

    10、公众号测试

           (1)规则验证

                   

         (2)取消关注,验证关注后消息自动回复

    11、完全版WeXinServlet

                  

      1 package com.my.servlet;
      2 
      3 import java.io.IOException;
      4 import java.io.PrintWriter;
      5 import java.util.Date;
      6 import java.util.Map;
      7 
      8 import javax.servlet.ServletException;
      9 import javax.servlet.http.HttpServlet;
     10 import javax.servlet.http.HttpServletRequest;
     11 import javax.servlet.http.HttpServletResponse;
     12 
     13 import com.my.pojo.TextMessage;
     14 import com.my.utils.CheckUtil;
     15 import com.my.utils.MessageUtils;
     16 
     17 /**
     18  * 
     19  * @author liuya
     20  * 
     21  * 
     22  *         //微信连接
     23  * 
     24  *         微信消息的接收与发送
     25  * 
     26  */
     27 
     28 public class WeXinServlet extends HttpServlet {
     29 
     30     /**
     31      * 随机生成的版本id
     32      */
     33     private static final long serialVersionUID = 1L;
     34 
     35     /**
     36      * 开发文档第一部分与微信的连接方式代码
     37      */
     38     @Override
     39     protected void doGet(HttpServletRequest request,
     40             HttpServletResponse response) throws ServletException, IOException {
     41 
     42         System.out.println("request.getRequestURL()返回的结果:"
     43                 + request.getRequestURL());
     44 
     45         // 跟微信平台比较的参数
     46         String signature = request.getParameter("signature");
     47         String timestamp = request.getParameter("timestamp");
     48         String nonce = request.getParameter("nonce");
     49         String echostr = request.getParameter("echostr");
     50 
     51         PrintWriter pWriter = response.getWriter();
     52         // 微信get后进行比较
     53         if (CheckUtil.checkSignature(signature, timestamp, nonce)) {
     54             pWriter.print(echostr);
     55         }
     56 
     57     }
     58 
     59     /**
     60      * // 1、将XML转换成集合类型 (因为微信后台发过来的消息是一个XML类型,为了方便处理,需要把微信发来的消息,转化成集合类型)
     61      * 
     62      * 
     63      * // 2、对象类型转化成XML类型(因为我们这边发送消息,也需要把数据转化成XML类型给微信服务后台接收)
     64      * 
     65      * 
     66      * // 3、书写一个公共类型的类,进行消息类型的转换
     67      * 
     68      * 文本消息类型的接收与响应
     69      * 
     70      */
     71 
     72     @Override
     73     protected void doPost(HttpServletRequest requset,
     74             HttpServletResponse response) throws ServletException, IOException {
     75 
     76         // 设置消息发来的格式
     77         requset.setCharacterEncoding("UTF-8");
     78         // 设置接收的消息格式
     79         response.setCharacterEncoding("UTF-8");
     80 
     81         // 通过此方法进行消息返回
     82         PrintWriter outPrintWriter = response.getWriter();
     83 
     84         // 1.微信消息的接收 集合获取
     85         Map<String, String> map;
     86         try {
     87             map = MessageUtils.xmlToMap(requset);
     88 
     89             // 2.获取集合中的属性
     90             // 开发者微信号
     91             String toUserName = (String) map.get("ToUserName");
     92             // 发送方账号(一个OpenID)
     93             String fromUserName = (String) map.get("FromUserName");
     94             // 消息类型
     95             String msgType = (String) map.get("MsgType");
     96             // 文本消息内容
     97             String content = (String) map.get("Content");
     98 
     99             // 3.根据messageType判断消息是不是文本消息
    100             // 设置消息回复变量
    101             String message = null;
    102 
    103             // 如果是文本消息,就进行回复
    104             if (MessageUtils.MESSAGE_TEXT.equals(msgType)) {
    105 
    106                 // 判断消息回复(规则设置)
    107                 if ("1".equals(content)) {
    108                     message = MessageUtils.initText(toUserName, fromUserName,
    109                             MessageUtils.firstMenu());
    110                 } else if ("2".equals(content)) {
    111                     message = MessageUtils.initText(toUserName, fromUserName,
    112                             MessageUtils.secondMenu());
    113                 } else if (("?".equals(content)) || ("?".equals(content))) {
    114                     message = MessageUtils.initText(toUserName, fromUserName,
    115                             MessageUtils.menuText());
    116                 }
    117 
    118             }
    119             // 事件推送的逻辑处理
    120             else if (MessageUtils.MESSAGE_EVENT.equals(msgType)) {
    121 
    122                 // 获取事件
    123                 String eventType = map.get("event");
    124                 // 关注后的逻辑处理
    125                 if (MessageUtils.MESSAGE_SUBSCRIBE.equals(eventType)) {
    126                     // 消息的位置
    127                     message = MessageUtils.initText(toUserName, fromUserName,
    128                             MessageUtils.menuText());
    129                 }
    130             }
    131 
    132             // 打印消息到控制台
    133             System.out.print(message);
    134             
    135             // 消息返回
    136             outPrintWriter.print(message);
    137 
    138         } catch (Exception e) {
    139             e.printStackTrace();
    140         } finally {
    141             // 关闭流
    142             outPrintWriter.close();
    143         }
    144 
    145     }
    146 
    147 }

    12、完全版MessageUtils

      1 package com.my.utils;
      2 
      3 import java.io.InputStream;
      4 import java.util.Date;
      5 import java.util.HashMap;
      6 import java.util.List;
      7 import java.util.Map;
      8 
      9 import javax.servlet.http.HttpServletRequest;
     10 
     11 import org.dom4j.Document;
     12 import org.dom4j.Element;
     13 import org.dom4j.io.SAXReader;
     14 
     15 import com.my.pojo.TextMessage;
     16 import com.thoughtworks.xstream.XStream;
     17 
     18 /**
     19  * 
     20  * // @author liuya
     21  * 
     22  * // 后端接收,微信公众号发过来的消息功能
     23  * 
     24  * 
     25  * // 1、将XML转换成集合类型 (因为微信后台发过来的消息是一个XML类型,为了方便处理,需要把微信发来的消息,转化成集合类型)
     26  * 
     27  * // 2、对象类型转化成XML类型(因为我们这边发送消息,也需要把数据转化成XML类型给微信服务后台接收)
     28  */
     29 
     30 public class MessageUtils {
     31 
     32     // 书写一些常量(会经常用到)
     33     // 文本消息
     34     public static final String MESSAGE_TEXT = "text";
     35     // 图片消息
     36     public static final String MESSAGE_IMAGE = "image";
     37     // 语音消息
     38     public static final String MESSAGE_VOICE = "voice";
     39     // 视频消息
     40     public static final String MESSAGE_VIDEO = "video";
     41     // 链接消息
     42     public static final String MESSAGE_LINK = "link";
     43     // 地理位置消息
     44     public static final String MESSAGE_LOCATION = "location";
     45     // 事件推送
     46     public static final String MESSAGE_EVENT = "event";
     47     // 关注
     48     public static final String MESSAGE_SUBSCRIBE = "subscribe";
     49     // 取消关注
     50     public static final String MESSAGE_UNSUBSCRIBE = "unsubscribe";
     51     // 菜单点击
     52     public static final String MESSAGE_CLICK = "click";
     53     // 菜单查看
     54     public static final String MESSAGE_VIEW = "view";
     55 
     56     /**
     57      * 需要导入dom4j---jar包 //
     58      * 
     59      * //1、将XML转换成集合类型 (因为微信后台发过来的消息是一个XML类型,为了方便处理,需要把微信发来的消息,转化成集合类型)//
     60      * 
     61      * @param request
     62      * @return
     63      * @throws Exception
     64      */
     65     @SuppressWarnings("unchecked")
     66     public static Map<String, String> xmlToMap(HttpServletRequest request)
     67             throws Exception {
     68 
     69         Map<String, String> map = new HashMap<String, String>();
     70         SAXReader sReader = new SAXReader();
     71 
     72         // 从request中获取输入流
     73         InputStream inStream = request.getInputStream();
     74         Document document = sReader.read(inStream);
     75 
     76         // 获取xml中的根元素
     77         Element rootElement = document.getRootElement();
     78 
     79         // 得到根元素的所有子节点,把它放在list的集合中
     80         List<Element> list = rootElement.elements();
     81 
     82         // 遍历list对象,获取单个元素的数据
     83         for (Element element : list) {
     84 
     85             // 遍历的结果保存到集合中
     86             map.put(element.getName(), element.getText());
     87         }
     88 
     89         // 关闭流
     90         inStream.close();
     91 
     92         return map;
     93     }
     94 
     95     /**
     96      * 导入xsream---jar包
     97      * 
     98      * // 2、对象类型转化成XML类型(因为我们这边发送消息,也需要把数据转化成XML类型给微信服务后台接收)
     99      * 
    100      * // 3、创建文本消息需要的实体类
    101      * 
    102      * @param textMessage
    103      * @return
    104      */
    105     public static String textMessageToXml(TextMessage textMessage) {
    106         XStream xstream = new XStream();
    107 
    108         // 打印出根节点的<xml>
    109         xstream.alias("xml", textMessage.getClass());
    110         // 返回发来的消息到控制台
    111         return xstream.toXML(textMessage);
    112     }
    113 
    114     /**
    115      * // 1.拼接一个主菜单(这个是消息菜单,在关注微信公众号后,自动回复一个消息)
    116      */
    117     public static String menuText() {
    118         StringBuffer stringBuffer = new StringBuffer();
    119         stringBuffer.append("欢迎您的关注,请按照菜单提示进行操作:
    
    ");
    120         stringBuffer.append("1、公司介绍 
    ");
    121         stringBuffer.append("2、主营产品介绍
    
    ");
    122         stringBuffer.append("**回复?调出此菜单。**");
    123         return stringBuffer.toString();
    124     }
    125 
    126     /**
    127      * 2.拼接文本消息的
    128      */
    129     public static String initText(String toUserName, String fromUserName,
    130             String content) {
    131         TextMessage textMessage = new TextMessage();
    132         textMessage.setFromUserName(toUserName);
    133         textMessage.setToUserName(fromUserName);
    134         // 换成常量
    135         textMessage.setMsgType(MessageUtils.MESSAGE_TEXT);
    136         textMessage.setCreateTime(new Date().getTime());
    137         textMessage.setContent("您发送的消息是 :" + content);
    138         return textMessageToXml(textMessage);
    139     }
    140 
    141     /**
    142      * 添加新的规则,当输入1的时候返回的数据
    143      */
    144 
    145     public static String firstMenu() {
    146         StringBuffer stringBuffer = new StringBuffer();
    147         stringBuffer
    148                 .append("总部杭州。
    
    "); 
    149 return stringBuffer.toString();
    150 }
    151
    152 /**
    153 * 添加新的规则,当输入2的时候返回的数据
    154 *
    155 * @return
    156 */
    157 public static String secondMenu() {
    158 StringBuffer stringBuffer = new StringBuffer();
    159 stringBuffer
    160 .append("总部杭州。 ");
    161 return stringBuffer.toString();
    162 }
    163 }
  • 相关阅读:
    jquery配合Bootstrap中的表单验证插件bootstrapValidator使用方法
    mysql限制update和delete必须加上where限制条件
    Node的express配置使用ejs模板
    mysql8用户管理
    c语言编译四大步
    windows系统安装gcc编译器----c/c++语言编译器
    c/c++语言开发工具Dev-cpp【推荐】
    c语言指针
    cmd切换代码页,切换字体,cmd不能输入中文
    windows8.1全角与半角切换快捷键
  • 原文地址:https://www.cnblogs.com/liuyangfirst/p/7955870.html
Copyright © 2011-2022 走看看