连小白都能看懂的微信开发之接收服务器推送消息

接收服务器推送普通消息

前言

微信接受消息流程机制图

连小白都能看懂的微信开发之接收服务器推送消息

接收普通消息

当普通微信用户向公众账号发消息时,微信服务器将POST消息的XML数据包到开发者填写的URL上。

服务器介入获取微信推送消息代码:

/**
     * 此方法用于微信回复消息
     * @param request
     * @return
     */
    @PostMapping("getToken")
    @ResponseBody
    public String getUserMessage(HttpServletRequest request){
        String responseString = "";
        try {
            //处理消息与事件推送
            Map<String, String> xmlData = RequestParamType.getXmlData(request.getInputStream());
            logger.info(xmlData.toString());//接受到的消息
             responseString = RequestParamType.dealBean2Xml(xmlData);
             logger.info("消息回复ing..." + responseString);
             return responseString;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

解析xml工具类

/**
     * 解析xml 获取key-value
     * @param inputStream
     * @return
     */
    public static Map<String,String> getXmlData(InputStream inputStream){
        Map<String,String> map =  new HashMap<>();
        //截取xml
        SAXReader reader = new SAXReader();
        try {
            Document document = reader.read(inputStream);
            Element rootElement = document.getRootElement(); //获取根节点
            List<Element>  elements = rootElement.elements(); // h获取所有的节点
            for (Element e: elements) {
                map.put(e.getName(),e.getStringValue());
            }

        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return map;
    }

处理xml消息

/**
     * 处理文本消息
     */
    public static String dealBean2Xml(Map<String,String> xmlData ){

        //获取 消息类型
        String msgType = xmlData.get("MsgType");
        BaseMsg baseMsg = null;
        switch (msgType){
            //普通文本消息
            case "text":
                baseMsg = dealText(xmlData);
                break;

            //图片消息
            case "image":
                break;

            //语音消息
            case "voice":
                break;

            //视频消息
            case "video":
                break;

            //小视频消息
            case "shortvideo":
                break;

            //地理位置消息
            case "location":
                break;
            //链接消息

            case "link":
                break;

            case "event":
                baseMsg = dealTicket(xmlData);
                break;

            default:
                break;
        }
        //把消息对象处理为xml数据包
        String xml = bean2Xml(baseMsg);
        if(xml!=null){
            return xml;
        }
        return null;
    }

处理文本工具类

/**
     * 处理文本消息
     * @param xmlData
     * @return TextMsg
     */
    private static BaseMsg dealText(Map<String, String> xmlData) {
        //获取请求聊天信息
        String content = xmlData.get("Content");
        //回复文本消息
        BaseMsg bm = new TextMsg(xmlData,"欢迎访问公众号哟!");
        return bm;
    }

将对象转为xml

/**
     *  javaBean 转xml
     * @param baseMsg
     * @return  xml
     */
    public static String bean2Xml(BaseMsg baseMsg){

        XStream xStream = new XStream();
        //若没有这句,xml中的根元素会是<包.类名>;或者说:注解根本就没生效,所以的元素名就是类的属性
        xStream.processAnnotations(BaseMsg.class);
        xStream.processAnnotations(ImageMsg.class);
        xStream.processAnnotations(LinkMsg.class);
        xStream.processAnnotations(LocationMsg.class);
        xStream.processAnnotations(SmalleVideoMsg.class);
        xStream.processAnnotations(TextMsg.class);
        xStream.processAnnotations(VideoMsg.class);
        xStream.processAnnotations(VoiceMsg.class);
        xStream.processAnnotations(ScanTicket.class);
        String xml = xStream.toXML(baseMsg);
        return xml;
    }

消息对象实体

消息实体基类

/**
 *  base模板实体类
 */
@XStreamAlias("xml") //设置根节点名
public class BaseMsg {

    //置顶别名首字母大写
    @XStreamAlias("ToUserName")
    private String toUserName;//开发者微信号
    private String FromUserName;//发送方帐号(一个OpenID)
    private String CreateTime;//消息创建时间 (整型)
    private String MsgType;//MsgType 文本类型


    public String getToUserName() {
        return toUserName;
    }

    public void setToUserName(String toUserName) {
        toUserName = toUserName;
    }

    public String getFromUserName() {
        return FromUserName;
    }

    public void setFromUserName(String fromUserName) {
        FromUserName = fromUserName;
    }

    public String getCreateTime() {
        return CreateTime;
    }

    public void setCreateTime(String createTime) {
        CreateTime = createTime;
    }

    public String getMsgType() {
        return MsgType;
    }

    public void setMsgType(String msgType) {
        MsgType = msgType;
    }

    public BaseMsg(){}
    public BaseMsg(Map<String,String> map){
        this.CreateTime=System.currentTimeMillis()/1000+"";
        this.FromUserName=map.get("ToUserName");
        this.toUserName=map.get("FromUserName");
    }

}

消息文本模板实体类

/**
 *  消息文本模板实体类
 */
@XStreamAlias("xml")
public class TextMsg extends BaseMsg {


    private String Content;//文本消息内容

    public String getContent() {
        return Content;
    }

    public void setContent(String content) {
        Content = content;
    }



    public TextMsg(Map<String,String> map, String Content){
        super(map);
        this.Content=Content;
        this.setMsgType("text");
    }

}

maven 依赖

<!-- https://mvnrepository.com/artifact/dom4j/dom4j -->
        <dependency>
            <groupId>dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>1.6.1</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.thoughtworks.xstream/xstream -->
        <dependency>
            <groupId>com.thoughtworks.xstream</groupId>
            <artifactId>xstream</artifactId>
            <version>1.4.11.1</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.53</version>
        </dependency>

相关推荐