在上一篇微信开发的博文中微信开发(01)之如何成为开发者,我们开启了微信开发者模式,本篇博文我们简单的处理微信关注者发给我们公众号的消息。
在开启微信开发者模式时,我们配置了一个URL地址,当我们提交开启微信开发者模式,腾讯的微信服务器会向该URL地址发送一个get请求,并且携带一些参数,让我们来验证。说到get请求,就必须说到post请求,关注我们公众号的微信粉丝发来的消息,触发的事件,腾讯的微信服务器则会像该URL地址发送一个post请求,请求的内容就是以xml文档形式的字符串。
所以该URL地址的get请求的处理方法,专门用于开启微信开发者模式;而post请求则用于处理微信粉丝发给我们的消息,或者触发的事件,所以我们后面的微信开发工作的起点就是该URL地址的post处理方法。
下面我们处理一个最简单的例子:粉丝发送任意一个文本信息给我们,我们给他回复一个消息:“你好,+ 他微信的openId”
下面直接贴代码:
URL对应的处理servlet:
public class CoreServlet extends HttpServlet { private static final long serialVersionUID = 4440739483644821986L; /** * 请求校验(确认请求来自微信服务器) */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 微信服务端发来的加密签名 String signature = request.getParameter("signature"); // 时间戳 String timestamp = request.getParameter("timestamp"); // 随机数 String nonce = request.getParameter("nonce"); // 随机字符串 String echostr = request.getParameter("echostr"); PrintWriter out = response.getWriter(); // 请求校验,若校验成功则原样返回echostr,表示接入成功,否则接入失败 if (SignUtil.checkSignature(signature, timestamp, nonce)) { out.print(echostr); } out.close(); out = null; } /** * 请求校验与处理 */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 将请求、响应的编码均设置为UTF-8(防止中文乱码) request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); // 接收参数微信加密签名、 时间戳、随机数 String signature = request.getParameter("signature"); String timestamp = request.getParameter("timestamp"); String nonce = request.getParameter("nonce"); PrintWriter out = response.getWriter(); // 请求校验 if (SignUtil.checkSignature(signature, timestamp, nonce)) { Message msgObj = XMLUtil.getMessageObject(request); // 读取微信客户端发来的消息(xml字符串),并将其转换为消息对象 if(msgObj != null){ String xml = "<xml>" + "<ToUserName><![CDATA[" + msgObj.getFromUserName() + "]]></ToUserName>" + // 接收方帐号(收到的OpenID) "<FromUserName><![CDATA[" + msgObj.getToUserName() + "]]></FromUserName>" + // 开发者微信号 "<CreateTime>12345678</CreateTime>" + "<MsgType><![CDATA[text]]></MsgType>" + "<Content><![CDATA[你好,"+ msgObj.getFromUserName() +"]]></Content>" + "</xml>"; out.write(xml); // 回复微信客户端的消息(xml字符串) out.close(); return; } } out.write(""); out.close(); } }
xml字符串的处理工具类,实现xml消息到消息对象的转换:
public class XMLUtil { /** * 从request中读取用户发给公众号的消息内容 * @param request * @return 用户发给公众号的消息内容 * @throws IOException */ public static String readRequestContent(HttpServletRequest request) throws IOException { // 从输入流读取返回内容 InputStream inputStream = request.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8"); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String str = null; StringBuilder buffer = new StringBuilder(); while ((str = bufferedReader.readLine()) != null) { buffer.append(str); } // 释放资源 bufferedReader.close(); inputStreamReader.close(); inputStream.close(); return buffer.toString(); } /** * 将xml文档的内容转换成map * @param xmlDoc * @return map */ public static Map<String, String> xmlToMap(String xmlDoc) { //创建一个新的字符串 StringReader read = new StringReader(xmlDoc); //创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入 InputSource source = new InputSource(read); //创建一个新的SAXBuilder SAXBuilder sb = new SAXBuilder(); Map<String, String> xmlMap = new HashMap<String, String>(); try { Document doc = sb.build(source); //通过输入源构造一个Document Element root = doc.getRootElement(); //取的根元素 List<Element> cNodes = root.getChildren(); //得到根元素所有子元素的集合(根元素的子节点,不包括孙子节点) Element et = null; for(int i=0;i<cNodes.size();i++){ et = (Element) cNodes.get(i); //循环依次得到子元素 xmlMap.put(et.getName(), et.getText()); } } catch (JDOMException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return xmlMap; } /** * 将保存xml内容的map转换成对象 * @param map * @return */ public static Message getMessageObject(Map<String, String> map) { if(map != null){ String MsgType = map.get("MsgType"); // 消息类型(文本消息:text, 图片消息:image, 语音消息:voice, 视频消息:video, // 地理位置消息:location, 链接消息:link) if("text".equals(MsgType)){ TextMessage msg = new TextMessage(); XMLUtil.initCommonMsg(msg, map); msg.setContent(map.get("Content")); return msg; } if("ImageMessage".equals(MsgType)){ ImageMessage msg = new ImageMessage(); XMLUtil.initCommonMsg(msg, map); msg.setPicUrl(map.get("PicUrl")); msg.setMediaId(map.get("MediaId")); return msg; } if("video".equals(MsgType)){ VideoMessage msg = new VideoMessage(); XMLUtil.initCommonMsg(msg, map); msg.setMediaId(map.get("MediaId")); msg.setThumbMediaId(map.get("ThumbMediaId")); return msg; } if("voice".equals(MsgType)){ VoiceMessage msg = new VoiceMessage(); XMLUtil.initCommonMsg(msg, map); msg.setMediaId(map.get("MediaId")); msg.setFormat(map.get("Format")); return msg; } if("location".equals(MsgType)){ LocationMessage msg = new LocationMessage(); msg.setLocation_X(map.get("Location_X")); msg.setLocation_Y(map.get("Location_Y")); msg.setScale(map.get("Scale")); msg.setLabel(map.get("Label")); return msg; } if("link".equals(MsgType)){ LinkMessage msg = new LinkMessage(); XMLUtil.initCommonMsg(msg, map); msg.setTitle(map.get("Title")); msg.setDescription(map.get("Description")); msg.setUrl(map.get("Url")); return msg; } } return null; } /** * 将保存xml内容的map转换成对象 * @param map * @return * @throws IOException */ public static Message getMessageObject(HttpServletRequest request) throws IOException { String xmlDoc = XMLUtil.readRequestContent(request); // 读取微信客户端发了的消息(xml) Map<String, String> map = XMLUtil.xmlToMap(xmlDoc); // 将客户端发来的xml转换成Map if(map != null){ String MsgType = map.get("MsgType"); // 消息类型(文本消息:text, 图片消息:image, 语音消息:voice, 视频消息:video, // 地理位置消息:location, 链接消息:link) if("text".equals(MsgType)){ TextMessage msg = new TextMessage(); XMLUtil.initCommonMsg(msg, map); msg.setContent(map.get("Content")); return msg; } /*if("ImageMessage".equals(MsgType)){ ImageMessage msg = new ImageMessage(); XMLUtil.initCommonMsg(msg, map); msg.setPicUrl(map.get("PicUrl")); msg.setMediaId(map.get("MediaId")); return msg; } if("video".equals(MsgType)){ VideoMessage msg = new VideoMessage(); XMLUtil.initCommonMsg(msg, map); msg.setMediaId(map.get("MediaId")); msg.setThumbMediaId(map.get("ThumbMediaId")); return msg; } if("voice".equals(MsgType)){ VoiceMessage msg = new VoiceMessage(); XMLUtil.initCommonMsg(msg, map); msg.setMediaId(map.get("MediaId")); msg.setFormat(map.get("Format")); return msg; } if("location".equals(MsgType)){ LocationMessage msg = new LocationMessage(); msg.setLocation_X(map.get("Location_X")); msg.setLocation_Y(map.get("Location_Y")); msg.setScale(map.get("Scale")); msg.setLabel(map.get("Label")); return msg; } if("link".equals(MsgType)){ LinkMessage msg = new LinkMessage(); XMLUtil.initCommonMsg(msg, map); msg.setTitle(map.get("Title")); msg.setDescription(map.get("Description")); msg.setUrl(map.get("Url")); return msg; }*/ } return null; } public static void initCommonMsg(Message msg, Map<String, String> map) { msg.setMsgId(map.get("MsgId")); msg.setMsgType(map.get("MsgType")); msg.setToUserName(map.get("ToUserName")); msg.setFromUserName(map.get("FromUserName")); msg.setCreateTime(map.get("CreateTime")); } }
粉丝发来的消息分为了6中类型(文本消息, 图片消息, 语音消息, 视频消息, 地理位置消息, 链接消息):
/** * 微信消息基类 * @author yuanfang * @date 2015-03-23 */ public class Message { private String MsgId; // 消息id,64位整型 private String MsgType; // 消息类型(文本消息:text, 图片消息:image, 语音消息:voice, 视频消息:video, 地理位置消息:location, 链接消息:link) private String ToUserName; //开发者微信号 private String FromUserName; // 发送方帐号(一个OpenID) private String CreateTime; // 消息创建时间 (整型) 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 String getMsgId() { return MsgId; } public void setMsgId(String msgId) { MsgId = msgId; } }
文本消息类:
package com.sinaapp.wx.msg; public class TextMessage extends Message { private String Content; // 文本消息内容 public String getContent() { return Content; } public void setContent(String content) { Content = content; } }
OK,对粉丝发送给我们公众号的任意的文本消息的最简单处理就完成,我们简单的回复他:你好,然后加上他微信的openId,类似于:你好,orJydljfkg3-r0_dj3rkdfvjl
更多微信开发之处理微信客户端发来的消息相关文章请关注PHP中文网!

PHP是一种开源的脚本语言,广泛应用于Web开发和服务器端编程,尤其在微信开发中得到了广泛的应用。如今,越来越多的企业和开发者开始使用PHP进行微信开发,因为它成为了一款真正的易学易用的开发语言。在微信开发中,消息的加密和解密是一个非常重要的问题,因为它们涉及到数据的安全性。对于没有加密和解密方式的消息,黑客可以轻松获取到其中的数据,对用户造成威胁

微信是目前全球用户规模最大的社交平台之一,随着移动互联网的普及,越来越多的企业开始意识到微信营销的重要性。在进行微信营销时,客服服务是至关重要的一环。为了更好地管理客服聊天窗口,我们可以借助PHP语言进行微信开发。一、PHP微信开发简介PHP是一种开源的服务器端脚本语言,广泛运用于Web开发领域。结合微信公众平台提供的开发接口,我们可以使用PHP语言进行微信

在微信公众号开发中,用户标签管理是一个非常重要的功能,可以让开发者更好地了解和管理自己的用户。本篇文章将介绍如何使用PHP实现微信用户标签管理功能。一、获取微信用户openid在使用微信用户标签管理功能之前,我们首先需要获取用户的openid。在微信公众号开发中,通过用户授权的方式获取openid是比较常见的做法。在用户授权完成后,我们可以通过以下代码获取用

随着微信的普及,越来越多的企业开始将其作为营销工具。而微信群发功能,则是企业进行微信营销的重要手段之一。但是,如果只依靠手动发送,对于营销人员来说是一件极为费时费力的工作。所以,开发一款微信群发工具就显得尤为重要。本文将介绍如何使用PHP开发微信群发工具。一、准备工作开发微信群发工具,我们需要掌握以下几个技术点:PHP基础知识微信公众平台开发开发工具:Sub

随着互联网和移动智能设备的发展,微信成为了社交和营销领域不可或缺的一部分。在这个越来越数字化的时代,如何使用PHP进行微信开发已经成为了很多开发者的关注点。本文主要介绍如何使用PHP进行微信开发的相关知识点,以及其中的一些技巧和注意事项。一、开发环境准备在进行微信开发之前,首先需要准备好相应的开发环境。具体来说,需要安装PHP的运行环境,以及微信公众平台提

随着微信成为了人们生活中越来越重要的一个通讯工具,其敏捷的消息传递功能迅速受到广大企业和个人的青睐。对于企业而言,将微信发展为一个营销平台已经成为趋势,而微信开发的重要性也逐渐凸显。在其中,群发功能更是被广泛使用,那么,作为PHP程序员,如何实现群发消息发送记录呢?下面将为大家简单介绍一下。1.了解微信公众号相关开发知识在了解如何实现群发消息发送记录之前,我

ThinkPHP6微信开发指南:快速搭建微信公众号应用引言:微信公众号作为一种重要的社交媒体平台,为个人和企业在市场推广、信息传播等方面提供了很大的机会。在这篇文章中,我们将介绍如何使用ThinkPHP6快速搭建一个微信公众号应用,并且提供一些常用的代码示例。环境准备在开始开发之前,我们首先需要准备好以下环境:PHP7以上版本ThinkPHP6框架微信公众号

随着移动互联网的普及,微信作为一款社交软件,越来越多的人开始使用,并且微信开放平台也给开发者带来了众多的机会。近年来,随着人工智能技术的发展,语音识别技术逐渐成为了移动端开发的热门技术之一。在微信开发中,如何实现语音识别成为很多开发者关注的问题。本文将介绍如何利用PHP开发微信应用实现语音识别功能。一、语音识别原理在介绍如何实现语音识别之前,我们先了解一下语


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

mPDF
mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

SublimeText3汉化版
中文版,非常好用

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能

VSCode Windows 64位 下载
微软推出的免费、功能强大的一款IDE编辑器