利用微信公众平台实现自动回复消息—java版

时间:2021-07-22 09:55:02

最近公司需要拿微信公众平台做个东西,所以就开始了最基本学习,网上很多是php版的,对于我这个只会java,不会php的就只能在网上找点只言片语来一点一点学习了。不费话了直接贴图看效果(很简单的)。

利用微信公众平台实现自动回复消息—java版

不会做关注时就回复信息,所以必须先发送“?”,才能出现提示。回复“1”和“其他”都是返回文字信息,“2”是音乐信息,“3”是图文信息。

好了,下面进入正题。

1、首先必须开通微信公中平台,还得申请到高级功能的(这个点比较坑,我等了两天才申请到的),关于申请公众平台我就不说了,网上很多介绍,自己看吧。

2、必须有自己的服务器资源,因为公众平台开发者模式开启时,必须填写接口配置信息(成为开发者)。

利用微信公众平台实现自动回复消息—java版

服务器资源我是用的是百度开发者中心来创建自己的应用。百度开发者中心:http://developer.baidu.com/

成为微信公众平台开发者前必须发布好自己的服务器资源,因为微信服务器将发送GET请求到填写的URL上(后面详细介绍)。

3、创建自己的应用。

利用微信公众平台实现自动回复消息—java版

这是整个项目结构。

下面逐一介绍:

 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 pw = response.getWriter();
String echo = request.getParameter("echostr");
echo = new String(echo.getBytes("ISO-8859-1"),"UTF-8");
pw.println(echo);
//当你提交成为开发者的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("回家|X-man");
music.setDescription("萨克斯 回家 勾起你想家的愁思..."); 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;
} }

WbChat

 public class ReplyMusicMessage {

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

ReplyMusicMessage

 public class ReplyTextMessage {

         private String toUserName;
private String fromUserName;
private String createTime;
private String messageType;
private String content;
private String funcFlag;
// getters,setters
}

ReplyTextMessage

 public class ReplyTuwenMessage {

     private String toUserName;
private String fromUserName;
private String createTime;
private String messageType;
private int articleCount; private Articles Articles;
private String funcFlag;
//getters,setters
}

ReplyTuwenMessage

 public class RequestTextMessage {
private String toUserName;
private String fromUserName;
private String createTime;
private String messageType;
private String content;
private String msgId;
//getters,setters
}

RequestTextMessage

 public class Articles {

     private Item item;

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

Articles

 public class Item {

     private String title;
private String description;
private String picUrl;
private String url;
//getters,setters
}

Item

 public class Music {

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

Music

 <servlet>
<servlet-name>Test</servlet-name>
<servlet-class>com.main.WbChat</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Test</servlet-name>
<url-pattern>/wbchat</url-pattern>
</servlet-mapping>

web.xml配置

还要加四个jar包:利用微信公众平台实现自动回复消息—java版

利用MyEclipse直接把工程打为war包,上传到百度开发者中心,并上线该应用。

4、成为开发者,开启开发模式。

利用微信公众平台实现自动回复消息—java版

将百度开发者中心中的当前域名+/wbchat 添加到微信平台的URL处,Token可以随便填(因为我没有判断Token)。

5、大功告成,可以在微信上添加该公众账号聊天了。

小提示:

1、调试时,微信发送消息却没有受到信息,可以去看看百度开发者中心,在应用版本管理中找到该应用,然后点击高级下的日志,查看日志来看出什么问题了

2、下载jar包地址:http://jarfiles.pandaidea.com/

3、不要听百度开发者中心说的那个”如何提交代码“,它是使用svn,它给的下载svn地址下的是svn1.8的,根本就checkout不了工程,如果想使用svn的话,就得去下载svn1.6的版本来使用。我是使用上传更新war包来更新工程的,这样在自己的MyEclipse中直接编写。