当前位置:网站首页>微信公共号开发,发送消息回复文本
微信公共号开发,发送消息回复文本
2022-06-29 15:29:00 【种豆走天下】
微信公共号开发,发送消息回复文本
TextMessage.java:
package com.qfjy.project.weixin.bean.req;
/** * 文本消息 */
public class TextMessage extends BaseMessage {
// 消息内容
private String Content;
public String getContent() {
return Content;
}
public void setContent(String content) {
Content = content;
}
}
CoreServlet.java:
package com.qfjy.project.weixin.servlet;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.qfjy.project.weixin.main.MenuManager;
import com.qfjy.project.weixin.service.CoreService;
import com.qfjy.project.weixin.util.SignUtil;
@Controller
@RequestMapping("weixin")
public class CoreServlet {
private static final long serialVersionUID = 4440739483644821986L;
/** * 确认请求来自微信服务器 */
@RequestMapping(value="weixin",method=RequestMethod.GET) // weixin/weixinOpe
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();
// 通过检验signature对请求进行校验,若校验成功则原样返回echostr,表示接入成功,否则接入失败
if (SignUtil.checkSignature(signature, timestamp, nonce)) {
out.print(echostr);
}
out.close();
out = null;
}
/** * 处理微信服务器发来的消息 * doPost方法有两个参数,request中封装了请求相关的所有内容,可以从request中取出微信服务器发来的消息; * 而通过response我们可以对接收到的消息进行响应,即发送消息。 * 那么如何解析请求消息的问题也就转化为如何从request中得到微信服务器发送给我们的xml格式的消息了。 * 这里我们借助于开源框架dom4j去解析xml(这里使用的是dom4j-1.6.1.jar),然后将解析得到的结果存入HashMap,解析请求消息的方法如下: */
@Autowired
CoreService coreService;
@RequestMapping(value="weixin",method=RequestMethod.POST)
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 将请求、响应的编码均设置为UTF-8(防止中文乱码)
//微信服务器POST消息时用的是UTF-8编码,在接收时也要用同样的编码,否则中文会乱码;
//在响应消息(回复消息给用户)时,也将编码方式设置为UTF-8,原理同上;
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
// 调用核心业务类接收消息、处理消息
String respMessage = coreService.processRequest(request);
//MenuManager.main(null);
// 响应消息
PrintWriter out = response.getWriter();
out.print(respMessage);
out.close();
}
}
CoreService.java:
package com.qfjy.project.weixin.service;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import com.qfjy.project.weixin.api.UserInfo.UserInfoUtil;
import com.qfjy.project.weixin.api.accessToken.AccessTokenRedis;
import com.qfjy.project.weixin.api.hitokoto.HitokotoUtil;
import com.qfjy.project.weixin.api.tuling.TulingUtil;
import com.qfjy.project.weixin.api.tuling.dev.WangXiang;
import com.sun.media.jfxmedia.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.qfjy.project.weixin.util.MessageUtil;
import com.qfjy.project.weixin.bean.resp.Article;
import com.qfjy.project.weixin.bean.resp.NewsMessage;
import com.qfjy.project.weixin.bean.resp.TextMessage;
@Service
public class CoreService {
@Autowired
private TulingUtil tuLingUtil;
@Autowired
private HitokotoUtil hitokotoUtil;
@Autowired
private WangXiang wangXiang;
/**Redis 解决access_token*/
@Autowired
private AccessTokenRedis accessTokenRedis;
private String URL="https://api.weixin.qq.com/cgi-bin/material/add_news?access_token=ACCESS_TOKEN";
public final static String appId="wxe4325a93f6dacc7b";
public final static String appSecret = "e754d645a9d14a2fd497aa065e9ec6b6";
@Autowired
private RedisTemplate<String,Object> redisTemplate;
private String title;
private String key = "mkc";
/**收集微信个人信息*/
@Autowired
private UserInfoUtil userInfoUtil;
/** * 处理微信发来的请求 * * @param request * @return */
public String processRequest(HttpServletRequest request) {
String respMessage = null;
try {
// 默认返回的文本消息内容
String respContent = "请求处理异常,请稍候尝试!";
// xml请求解析 调用消息工具类MessageUtil解析微信发来的xml格式的消息,解析的结果放在HashMap里;
Map<String, String> requestMap = MessageUtil.parseXml(request);
// 发送方帐号(open_id) 下面三行代码是: 从HashMap中取出消息中的字段;
String fromUserName = requestMap.get("FromUserName");
// 公众帐号
String toUserName = requestMap.get("ToUserName");
// 消息类型
String msgType = requestMap.get("MsgType");
// 回复文本消息 组装要返回的文本消息对象;
TextMessage textMessage = new TextMessage();
textMessage.setToUserName(fromUserName);
textMessage.setFromUserName(toUserName);
textMessage.setCreateTime(new Date().getTime());
textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
textMessage.setFuncFlag(0);
// 由于href属性值必须用双引号引起,这与字符串本身的双引号冲突,所以要转义
// textMessage.setContent("欢迎访问<a
// href=\"http://www.baidu.com/index.php?tn=site888_pg\">百度</a>!");
// 将文本消息对象转换成xml字符串
respMessage = MessageUtil.textMessageToXml(textMessage);
/** * 演示了如何接收微信发送的各类型的消息,根据MsgType判断属于哪种类型的消息; */
// 接收用户发送的文本消息内容
String content = requestMap.get("Content");
// 创建图文消息
NewsMessage newsMessage = new NewsMessage();
newsMessage.setToUserName(fromUserName);
newsMessage.setFromUserName(toUserName);
newsMessage.setCreateTime(new Date().getTime());
newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
newsMessage.setFuncFlag(0);
// 文本消息
if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {
respContent = "您发送的是文本消息!";
}
// 图片消息
else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)) {
respContent = "您发送的是图片消息!";
}
// 地理位置消息
else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)) {
respContent = "您发送的是地理位置消息!";
}
// 链接消息
else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)) {
respContent = "您发送的是链接消息!";
}
// 音频消息
else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)) {
respContent = "您发送的是音频消息!";
}
// 事件推送
else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {
// 事件类型
String eventType = requestMap.get("Event");
// 订阅
if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {
userInfoUtil.weixinUserInfoUtil(fromUserName);
System.out.println(fromUserName);
respContent = "欢迎关注微信公众号";
}
// 取消订阅
else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {
// TODO 取消订阅后用户再收不到公众号发送的消息,因此不需要回复消息
}
// 自定义菜单点击事件
else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {
// 事件KEY值,与创建自定义菜单时指定的KEY值对应
String eventKey = requestMap.get("EventKey");
if (eventKey.equals("11")) {
respContent = "菜单项被点击!";
}
else if (eventKey.equals("70")) {
List<Article> articleList = new ArrayList<Article>();
// 单图文消息
Article article = new Article();
article.setTitle("标题");
article.setDescription("描述内容");
article.setPicUrl(
"图片");
article.setUrl("跳转连接");
articleList.add(article);
// 设置图文消息个数
newsMessage.setArticleCount(articleList.size());
// 设置图文消息
newsMessage.setArticles(articleList);
// 将图文消息对象转换为XML字符串
respMessage = MessageUtil.newsMessageToXml(newsMessage);
return respMessage;
}
}
}
// 组装要返回的文本消息对象;
textMessage.setContent(respContent);
// 调用消息工具类MessageUtil将要返回的文本消息对象TextMessage转化成xml格式的字符串;
respMessage = MessageUtil.textMessageToXml(textMessage);
} catch (Exception e) {
e.printStackTrace();
}
return respMessage;
}
}
至此设置好微信接口的连接,对公共号发送信息就可以自动回复了。
下节我们说使用一言堂和图灵机器人智能回复信息。
边栏推荐
猜你喜欢
随机推荐
无意发现的【TiDB缓存表】,竟能解决读写热点问题
【力扣10天SQL入门】Day7+8 计算函数
Create an API rapid development platform, awesome!
File common tool class, stream related application (record)
89.(cesium篇)cesium聚合图(自定义图片)
Building SQL statements in Excel
Take another picture of cloud redis' improvement path
MCS: multivariate random variable - discrete random variable
小程序判断数据为不为空
LeetCode-64-最小路径和
Rust Basics
three.js和高德地图结合引入obj格式模型-效果演示
Classe d'outils commune de fichier, application liée au flux (enregistrement)
The role of each layer in convolutional neural network
阿里云体验有奖:使用PolarDB-X与Flink搭建实时数据大屏
Cmake learning-2
如何用好数据科学?
13.TCP-bite
Render follows, encapsulating a form and adding data to the table
Knowledge points: what are the know-how of PCB wiring?









