微信公众号自动回复_Java

先声明一下,这是一个maven工程pom文件需要的依赖:
 1 <dependency>
 2     <groupId>dom4j</groupId>
 3     <artifactId>dom4j</artifactId>
 4     <version>1.6</version>
 5 </dependency>
 6 <dependency>
 7     <groupId>commons-io</groupId>
 8     <artifactId>commons-io</artifactId>
 9     <version>2.5</version>
10 </dependency>
11 <dependency>
12     <groupId>com.thoughtworks.xstream</groupId>
13     <artifactId>xstream</artifactId>
14     <version>1.4.9</version>
15 </dependency>
16 <dependency>
17     <groupId>javax.servlet</groupId>
18     <artifactId>javax.servlet-api</artifactId>
19     <version>3.1.0</version>
20 </dependency>

微信消息都是基于xml文件进行接收发送的

微信文本消息的参数:

<xml>
    <ToUserName><![CDATA[toUser]]></ToUserName>
    <FromUserName><![CDATA[fromUser]]></FromUserName>
    <CreateTime>1348831860</CreateTime>
    <MsgType><![CDATA[text]]></MsgType>
    <Content><![CDATA[this is a test]]></Content>
    <MsgId>1234567890123456</MsgId>
</xml>
        <!--参数              描述
            ToUserName       开发者微信号
            FromUserName     发送方帐号(一个OpenID)
            CreateTime       消息创建时间 (整型)
            MsgType          text
            Content          文本消息内容
            MsgId            消息id,64位整型
        -->

微信回复文本消息的参数

<xml>
    <ToUserName><![CDATA[toUser]]></ToUserName>
    <FromUserName><![CDATA[fromUser]]></FromUserName>
    <CreateTime>12345678</CreateTime>
    <MsgType><![CDATA[text]]></MsgType>
    <Content><![CDATA[你好]]></Content>
</xml>
<!--参数             是否必须        描述
    ToUserName          是            接收方帐号(收到的OpenID)
    FromUserName        是            开发者微信号
    CreateTime          是            消息创建时间 (整型)
    MsgType             是            text
    Content             是            回复的消息内容(换行:在content中能够换行,微信客户端就支持换行显示)
 -->

我会在相应的代码上加上注释,其他对应图片消息参数,以及回复图片消息参数、图文消息参数等等 请参考微信开发文档。

附上微信公众号接口文档链接:点击这里

二话不说 先附上主代码:

注:  xml解析:本文使用的是xtream进行xml与java对象之间的转换;对于xml解析还可以使用其他方法 如:dom4j等等 我这里就不一一列举了

import com.replymessage.*;
import com.requestmessage.RequestTextMessage;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.util.Articles;
import com.util.Item;
import com.util.Music;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 微信回复消息
 */
public class WbChat extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public WbChat() {
        super();
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        //这里没有对发送信息者进行验证,直接返回了,要加验证的话自己去百度吧
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        String echostr = request.getParameter("echostr");
        echostr = new String(echostr.getBytes("ISO-8859-1"),"UTF-8");
        writer.println(echostr);
        //当你提交成为开发者的URL和Token时,微信服务器将发送GET请求到填写的URL上,
        //只有你返回参数echostr时,他才会认为你这个接口是通的,才会提交成功
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        //当你用微信给平台发送信息时就会到这里
        //回复音乐和图文消息,都写死了,自己可以根据自己的需要加相应的处理
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter pw = response.getWriter();
        String wxMsgXml = IOUtils.toString(request.getInputStream(),"utf-8");
        RequestTextMessage textMsg = null;
        try {
            textMsg = getRequestTextMessage(wxMsgXml);
        } catch (Exception e) {
            e.printStackTrace();
        }
        StringBuffer replyMsg = new StringBuffer();
        String receive = textMsg.getContent().trim();
        String returnXml = null;

        if (textMsg != null&&!receive.equals("")) {
            if (receive.equals("?")||receive.equals("?")) {

                replyMsg.append("欢迎使用微信平台!");
                replyMsg.append("\r\n1、当前时间");
                replyMsg.append("\r\n2、听音乐");
                replyMsg.append("\r\n3、看图文");
                replyMsg.append("\r\n其他、请直接输入文字信息等待管理员回复");

                returnXml = getReplyTextMessage(replyMsg.toString(), textMsg.getFromUserName(),textMsg.getToUserName());

            } else  if (receive.equals("2")) {
                //回复音乐信息
                returnXml = getReplyMusicMessage(textMsg.getFromUserName(),textMsg.getToUserName());

            } else  if (receive.equals("3")) {
                //回复图文
                returnXml = getReplyTuwenMessage(textMsg.getFromUserName(),textMsg.getToUserName());

            }  else if (receive.equals("1")) {
                //回复时间
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                replyMsg.append("当前时间\r\n"+df.format(new Date()));
                returnXml = getReplyTextMessage(replyMsg.toString(), textMsg.getFromUserName(),textMsg.getToUserName());

            } else {
                replyMsg.append("收到: " + textMsg.getContent());
                returnXml = getReplyTextMessage(replyMsg.toString(), textMsg.getFromUserName(),textMsg.getToUserName());

            }
        } else {
            replyMsg.append("别闹了,这谁看得懂啊!");
            returnXml = getReplyTextMessage(replyMsg.toString(), textMsg.getFromUserName(),textMsg.getToUserName());

        }
        pw.println(returnXml);
    }

    //获取推送文本消息
    private RequestTextMessage getRequestTextMessage(String xml){

        XStream xstream = new XStream(new DomDriver());

        xstream.alias("xml", RequestTextMessage.class);
        xstream.aliasField("ToUserName", RequestTextMessage.class, "toUserName");
        xstream.aliasField("FromUserName", RequestTextMessage.class, "fromUserName");
        xstream.aliasField("CreateTime", RequestTextMessage.class, "createTime");
        xstream.aliasField("MsgType", RequestTextMessage.class, "messageType");
        xstream.aliasField("Content", RequestTextMessage.class, "content");
        xstream.aliasField("MsgId", RequestTextMessage.class, "msgId");

        RequestTextMessage requestTextMessage = (RequestTextMessage)xstream.fromXML(xml);
        return requestTextMessage;
    }
    //回复文本消息
    private String getReplyTextMessage(String content, String fromUserName,String toUserName){

        ReplyTextMessage we = new ReplyTextMessage();
        we.setMessageType("text");
        we.setFuncFlag("0");
        we.setCreateTime(new Long(new Date().getTime()).toString());
        we.setContent(content);
        we.setToUserName(fromUserName);
        we.setFromUserName(toUserName);
        XStream xstream = new XStream(new DomDriver());
        xstream.alias("xml", ReplyTextMessage.class);
        xstream.aliasField("ToUserName", ReplyTextMessage.class, "toUserName");
        xstream.aliasField("FromUserName", ReplyTextMessage.class, "fromUserName");
        xstream.aliasField("CreateTime", ReplyTextMessage.class, "createTime");
        xstream.aliasField("MsgType", ReplyTextMessage.class, "messageType");
        xstream.aliasField("Content", ReplyTextMessage.class, "content");
        xstream.aliasField("FuncFlag", ReplyTextMessage.class, "funcFlag");
        String xml =xstream.toXML(we);
        return xml;
    }
    //回复音乐消息
    private String getReplyMusicMessage(String fromUserName,String toUserName){

        ReplyMusicMessage we = new ReplyMusicMessage();
        Music music = new Music();

        we.setMessageType("music");
        we.setCreateTime(new Long(new Date().getTime()).toString());
        we.setToUserName(fromUserName);
        we.setFromUserName(toUserName);
        we.setFuncFlag("0");

        music.setTitle("home");
        music.setDescription(" family 想家了吗");

        String url = "http://bcs.duapp.com/yishi-music/%E5%9B%9E%E5%AE%B6.mp3?sign=MBO:97068c69ccb2ab230a497c59d528dcce:LdYZ%2FLXohKa6YCy9gbxL%2B1mZ4Co%3D";
        String url2 = "http://bcs.duapp.com/yishi-music/X-man.mp3?sign=MBO:97068c69ccb2ab230a497c59d528dcce:cYV%2B%2Fq2Tlv2de6gqecZynCyIm3k%3D";
        music.setMusicUrl(url);
        music.setHqMusicUrl(url2);

        we.setMusic(music);

        XStream xstream = new XStream(new DomDriver());
        xstream.alias("xml", ReplyMusicMessage.class);
        xstream.aliasField("ToUserName", ReplyMusicMessage.class, "toUserName");
        xstream.aliasField("FromUserName", ReplyMusicMessage.class, "fromUserName");
        xstream.aliasField("CreateTime", ReplyMusicMessage.class, "createTime");
        xstream.aliasField("MsgType", ReplyMusicMessage.class, "messageType");
        xstream.aliasField("FuncFlag", ReplyMusicMessage.class, "funcFlag");
        xstream.aliasField("Music", ReplyMusicMessage.class, "Music");

        xstream.aliasField("Title", Music.class, "title");
        xstream.aliasField("Description", Music.class, "description");
        xstream.aliasField("MusicUrl", Music.class, "musicUrl");
        xstream.aliasField("HQMusicUrl", Music.class, "hqMusicUrl");

        String xml =xstream.toXML(we);
        return xml;
    }

    //回复图文消息
    private String getReplyTuwenMessage(String fromUserName,String toUserName){

        ReplyTuwenMessage we = new ReplyTuwenMessage();

        Articles articles = new Articles();

        Item item = new Item();

        we.setMessageType("news");
        we.setCreateTime(new Long(new Date().getTime()).toString());
        we.setToUserName(fromUserName);
        we.setFromUserName(toUserName);
        we.setFuncFlag("0");
        we.setArticleCount(1);

        item.setTitle("二哈");
        item.setDescription("二哈(SHUNSUKE)是Twitter上现在最流行的偶像犬,是一条傻狗,因为在网上装疯扮傻而走红网络。");
        item.setPicUrl("http://bcs.duapp.com/yishi-music/111.jpg?sign=MBO:97068c69ccb2ab230a497c59d528dcce:hmzcBYxgI4yUaTd9GvahO1GvE%2BA%3D");
        item.setUrl("http://baike.baidu.com/view/6300265.htm");

        articles.setItem(item);
        we.setArticles(articles);

        XStream xstream = new XStream(new DomDriver());
        xstream.alias("xml", ReplyTuwenMessage.class);
        xstream.aliasField("ToUserName", ReplyTuwenMessage.class, "toUserName");
        xstream.aliasField("FromUserName", ReplyTuwenMessage.class, "fromUserName");
        xstream.aliasField("CreateTime", ReplyTuwenMessage.class, "createTime");
        xstream.aliasField("MsgType", ReplyTuwenMessage.class, "messageType");
        xstream.aliasField("Articles", ReplyTuwenMessage.class, "Articles");

        xstream.aliasField("ArticleCount", ReplyTuwenMessage.class, "articleCount");
        xstream.aliasField("FuncFlag", ReplyTuwenMessage.class, "funcFlag");

        xstream.aliasField("item", Articles.class, "item");

        xstream.aliasField("Title", Item.class, "title");
        xstream.aliasField("Description", Item.class, "description");
        xstream.aliasField("PicUrl", Item.class, "picUrl");
        xstream.aliasField("Url", Item.class, "url");

        String xml =xstream.toXML(we);
        return xml;
    }

}

当你看到这里 说明你成功一半了,下面我们继续来完成这些小瑕疵

这时候需要:根据xml标签创建对应的实体类

实体类一:音乐消息

import com.util.Music;

/**
 * 音乐消息实体类
 */
public class ReplyMusicMessage {

    private String toUserName;
    private String fromUserName;
    private String createTime;
    private String messageType;
    private com.util.Music Music;
    private String funcFlag;
//这里的funcFlag,微信平台接口文档里没有,但是必须写上,不然会收不到返回的信息

    public String getToUserName() {
        return toUserName;
    }

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

    public String getFromUserName() {
        return fromUserName;
    }

    public void setFromUserName(String fromUserName) {
        this.fromUserName = fromUserName;
    }

    public String getCreateTime() {
        return createTime;
    }

    public void setCreateTime(String createTime) {
        this.createTime = createTime;
    }

    public String getMessageType() {
        return messageType;
    }

    public void setMessageType(String messageType) {
        this.messageType = messageType;
    }

    public Music getMusic() {
        return Music;
    }

    public void setMusic(Music music) {
        Music = music;
    }

    public String getFuncFlag() {
        return funcFlag;
    }

    public void setFuncFlag(String funcFlag) {
        this.funcFlag = funcFlag;
    }
}

实体类二:文本消息(常用)

/**
 * 文本消息实体类
 */
public class ReplyTextMessage {

    private String toUserName;
    private String fromUserName;
    private String createTime;
    private String messageType;
    private String content;
    private String funcFlag;

    public String getToUserName() {
        return toUserName;
    }

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

    public String getFromUserName() {
        return fromUserName;
    }

    public void setFromUserName(String fromUserName) {
        this.fromUserName = fromUserName;
    }

    public String getCreateTime() {
        return createTime;
    }

    public void setCreateTime(String createTime) {
        this.createTime = createTime;
    }

    public String getMessageType() {
        return messageType;
    }

    public void setMessageType(String messageType) {
        this.messageType = messageType;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getFuncFlag() {
        return funcFlag;
    }

    public void setFuncFlag(String funcFlag) {
        this.funcFlag = funcFlag;
    }
}

实体类三:图文消息(常用)

import com.util.Articles;

/**
 * 图文消息实体类
 */
public class ReplyTuwenMessage {

    private String toUserName;
    private String fromUserName;
    private String createTime;
    private String messageType;
    private int articleCount;

    private Articles articles;
    private String funcFlag;

    public String getToUserName() {
        return toUserName;
    }

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

    public String getFromUserName() {
        return fromUserName;
    }

    public void setFromUserName(String fromUserName) {
        this.fromUserName = fromUserName;
    }

    public String getCreateTime() {
        return createTime;
    }

    public void setCreateTime(String createTime) {
        this.createTime = createTime;
    }

    public String getMessageType() {
        return messageType;
    }

    public void setMessageType(String messageType) {
        this.messageType = messageType;
    }

    public int getArticleCount() {
        return articleCount;
    }

    public void setArticleCount(int articleCount) {
        this.articleCount = articleCount;
    }

    public Articles getArticles() {
        return articles;
    }

    public void setArticles(Articles articles) {
        this.articles = articles;
    }

    public String getFuncFlag() {
        return funcFlag;
    }

    public void setFuncFlag(String funcFlag) {
        this.funcFlag = funcFlag;
    }
}

请求消息实体类

/**
 * 请求消息实体类
 */
public class RequestTextMessage {
    private String toUserName;
    private String fromUserName;
    private String createTime;
    private String messageType;
    private String content;
    private String msgId;
//getters,setters

    public String getToUserName() {
        return toUserName;
    }

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

    public String getFromUserName() {
        return fromUserName;
    }

    public void setFromUserName(String fromUserName) {
        this.fromUserName = fromUserName;
    }

    public String getCreateTime() {
        return createTime;
    }

    public void setCreateTime(String createTime) {
        this.createTime = createTime;
    }

    public String getMessageType() {
        return messageType;
    }

    public void setMessageType(String messageType) {
        this.messageType = messageType;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getMsgId() {
        return msgId;
    }

    public void setMsgId(String msgId) {
        this.msgId = msgId;
    }
}

音乐消息实体类

/**
 * 音乐消息实体类
 */
public class Music {

    private String title;
    private String description;
    private String musicUrl;
    private String hqMusicUrl;
//getters,setters

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getMusicUrl() {
        return musicUrl;
    }

    public void setMusicUrl(String musicUrl) {
        this.musicUrl = musicUrl;
    }

    public String getHqMusicUrl() {
        return hqMusicUrl;
    }

    public void setHqMusicUrl(String hqMusicUrl) {
        this.hqMusicUrl = hqMusicUrl;
    }
}

xml嵌套标签实体类

/**
 * xml嵌套标签实体类
 */
public class Articles {

    private Item item;

    public Item getItem() {
        return item;
    }

    public void setItem(Item item) {
        this.item = item;
    }

}

xml嵌套标签实体类

/**
 * xml嵌套标签实体类
 */
public class Item {

    private String title;
    private String description;
    private String picUrl;
    private String url;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getPicUrl() {
        return picUrl;
    }

    public void setPicUrl(String picUrl) {
        this.picUrl = picUrl;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}

当你看到这里 恭喜你  微信公众号自动回复的基础操作你已经学会了

后续还会有 在公众号基础上进行小活动开发 后续更新...

原文地址:https://www.cnblogs.com/wusiwee/p/10240359.html

时间: 2024-10-07 08:04:29

微信公众号自动回复_Java的相关文章

微信公众号自动回复

首先,应该建立一个消息与图片的实体,看一下微信公众号的文档: 原网址 回复文本消息<xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName><![CDATA[fromUser]]></FromUserName> <CreateTime>12345678</CreateTime> <MsgType><![CDATA

微信公众号自动回复多图文(php)

作者:方倍工作室原文:http://www.cnblogs.com/txw1958/p/weixin-97-news.html 在这篇微信公众平台开发教程中,我们将介绍如何灵活的使用图文消息功能.我们将只介绍被动回复消息中的图文消息,发送客服消息及高级群发消息接口的发送的图文消息与本文介绍的图文消息的各情况基本一致. 本文分为以下四个部分: 图文消息的定义 图文消息的实现 图文消息的类型 图文消息的回复 一.图文消息的定义 在微信公众平台消息中,发送被动响应消息中的图文消息的XML结构如下所示.

微信公众号自动回复加超链接最新可用实现方案

你在管理微信号时是否会有自动回复或者在关键字触发自动回复加一个超链接的需求呢?例如下图像王者荣耀这样: 很多有开发经验的朋友都知道微信管理平台会类似富文本编辑器,第一想到的解决方案会是在编辑框中加<a href='网址' >显示文字</a>. 没错,实现的方式的确如此,可是此方法在几个月前就被微信官方给屏蔽了,加了超链接代码,出来还是普通文字,这个时候运营者便开始急眼了,难道真的无法实现该需求了么? 如果真的没有解决方案,我也不会在此分享这个方案了.稍安勿躁,接着往下看! 亲试可用

微信公众号自动回复示例代码

<?php define("TOKEN", "weixin"); $wechatObj = new wechatCallbackapiTest(); $wechatObj->responseMsg(); class wechatCallbackapiTest { public function responseMsg() { //get post data, May be due to the different environments $postSt

微信公众号开发之网页授权(获取用户信息)

这次暑假留在学校参与工作室的项目,对微信公众号比较感兴趣,所以参与这方面的学习研究. 昨天完成了关于网页授权,获取用户信息方面的功能,所以乘热打铁,写上一篇.实现本篇涉及的 功能,还需要完成一些基础.在写完这篇博客后,我会尽快补上. -------------------------废话不多说直入正题 需要的工具: 微信公众号(可以申请,但做开发的,可以申请测试号,申请详细不多说了) 服务器(可以自行购买,我使用的是新浪的sae.) 编辑器(随意,不做推荐) 微信公众号开发文档(地址) ----

C#微信公众号开发 -- (三)用户关注之后自动回复

通过了上一篇文章之后的微信开发者验证之后,我们就可以做微信公众号的代码开发了. 当我们点击关注某个公众号的时候,有时候会发现他会自动给我们回复一条消息,比如欢迎关注XXX公众号.这个功能其实是在点击关注的时候,用户触发了微信定义的事件,同时微信会返回给我们一个XML数据包,微信官方的解释如下: 推送XML数据包示例: <xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName>&

Python快速搭建自动回复微信公众号

Python快速搭建自动回复微信公众号 在之前的一篇文章 Python利用 AIML 和 Tornado 搭建聊天机器人微信订阅号 中用 aiml 实现了一个简单的英文聊天机器人订阅号.但是只能处理英文消息,现在用 图灵机器人 来实现一个中文的聊天机器人订阅号. 这里主要介绍如何利用 Python 的 Tornado Web框架以及wechat-python-sdk 微信公众平台 Python 开发包来快速搭建微信公众号. 完整的公众号代码 GitHub 地址:green ,由于目前此公众号有一

[.NET] 简单接入微信公众号开发:实现自动回复

简单接入微信公众号开发:实现自动回复 一.前提 先申请微信公众号的授权,找到或配置几个关键的信息(开发者ID.开发者密码.IP白名单.令牌和消息加解密密钥等). 二.基本配置信息解读 开发者ID:固定的: 开发者密码:自己扫一下就可以看到: IP白名单:设置自己配置服务器的地址: 服务器地址(URL):稍后详解: 令牌:随便写,按规则: 消息加解密密钥:随便写,或者随机生成: 三.配置服务器地址(URL) 服务器地址(URL)应该怎么配置呢?图片上的配置的地址是:http://www.nidie

Java微信公众号开发----关键字自动回复消息

在配置好开发者配置后,本人第一个想要实现的是自动回复消息的功能,说明以下几点: 1. url 仍然不变,还是开发配置里的url 2. 微信采用 xml 格式传输数据 3.微信服务器传给我们的参数主要有(如图): 附上解析xml类的依赖: 1 <!-- dom对象读取写入xml文件 --> 2 <dependency> 3 <groupId>dom4j</groupId> 4 <artifactId>dom4j</artifactId>