Java实现微信公众号自动回复
本文最先发表于我的个人博客,为同步发布,如有需要,请访问 获取更多内容
背景
准备工作
注册完毕后需要完成认证操作
代码
<dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency> <dependency> <groupId>com.thoughtworks.xstream</groupId> <artifactId>xstream</artifactId> <version>1.4.19</version> </dependency>
自动回复内容一共需要两个接口(两个接口路由完全一致,一个为GET请求,一个为POST请求)
-
消息接收接口
消息回复service
文本回复service
/** * @author C.W * @date 2022/5/18 9:57 * @desc 文本回复 */ @Service public class TextReplyService { private static final String FROM_USER_NAME = "FromUserName"; private static final String TO_USER_NAME = "ToUserName"; private static final String CONTENT = "Content"; @Autowired private WechatKeywordDao wechatKeywordDao; @Autowired private WechatMsgRecordDao wechatMsgRecordDao; /** * 自动回复文本内容 * * @param requestMap * @return */ public String reply(Map<String, String> requestMap) { String wechatId = requestMap.get(FROM_USER_NAME); String gongzhonghaoId = requestMap.get(TO_USER_NAME); TextMessage textMessage = WechatMessageUtils.getDefaultTextMessage(wechatId, gongzhonghaoId); String content = requestMap.get(CONTENT); if (content == null) { textMessage.setContent(WechatConstants.DEFAULT_MSG); } else { Example example = new Example(WechatKeywordPO.class); example.createCriteria().andEqualTo("wechatId", gongzhonghaoId).andEqualTo("keyword", content); List<WechatKeywordPO> keywordPOList = wechatKeywordDao.selectByExample(example); if (CollectionUtils.isEmpty(keywordPOList)) { textMessage.setContent(WechatConstants.DEFAULT_MSG); } else { textMessage.setContent(keywordPOList.get(0).getReplyContent()); } } // 记录消息记录 wechatMsgRecordDao.insertSelective(WechatMsgRecordPO.builder() .fromUser(wechatId) .wechatId(gongzhonghaoId) .content(content) .replyContent(textMessage.getContent()) .build() ); return WechatMessageUtils.textMessageToXml(textMessage); } }
文本消息model
/** * @author C.W * @date 2021/11/26 22:21 * @description 文本消息 */ @Data public class TextMessage extends BaseMessage { /** * 回复的消息内容 */ private String Content; }
基础消息model
消息工具
消息类型枚举
其他内容为一些数据库相关操作,此处不再列出,仅为:查询关键词及其回复内容,存储消息记录
-
服务器配置
-
填写服务器地址
-
生成你的令牌Token
验证方法
下一篇:
python高校学生消费行为分析系统