基于 Spring Boot 的项目中使用微信服务号实现订阅通知的发送

基于 Spring Boot 的项目中使用微信服务号实现订阅通知的发送

文章目录

上一篇文章介绍的是使用模板消息进行消息的推送,本文使用微信服务号订阅通知来推送消息;因为随着微信的发展,转向使用“订阅通知”是大势所趋。

使用微信服务号的订阅通知功能,可以向用户发送定制化的消息。本文给出 Spring Boot 的完整示例,演示如何在微信服务号中实现订阅通知的发送。

1. 准备工作

  • 公众号类型:确保你使用的是已认证的服务号。
  • 模板申请:你需要先在微信公众平台上为你的服务号申请相应的订阅通知模板,并获取到模板ID。
  • 权限配置:确保你的服务器公网IP已经添加到公众号后台的“IP白名单”中。
  • 依赖库:我们将使用 WxJava (Weixin Java Tools) 来简化开发过程。

2. 添加 Maven 依赖

首先,在你的 pom.xml 文件中加入 WxJava 相关依赖:

<dependency><groupId>com.github.binarywang</groupId><artifactId>weixin-java-mp</artifactId><version>4.5.0</version></dependency>

3. 配置文件

在 application.yml 中添加微信公众号的相关配置:

wx:mp:app-id: your_appid secret: your_secret token: your_token aes-key: your_aes_key # 如果启用了消息加解密,则需要配置此参数

4. 创建配置类

创建一个配置类来初始化微信服务:

importme.chanjar.weixin.mp.api.WxMpService;importme.chanjar.weixin.mp.api.impl.WxMpServiceImpl;importme.chanjar.weixin.mp.config.WxMpConfigStorage;importme.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;@ConfigurationpublicclassWxMpConfiguration{@Value("${wx.mp.app-id}")privateString appId;@Value("${wx.mp.secret}")privateString secret;@Value("${wx.mp.token}")privateString token;@Value("${wx.mp.aes-key}")privateString aesKey;@BeanpublicWxMpServicewxMpService(){WxMpService wxMpService =newWxMpServiceImpl();WxMpDefaultConfigImpl configStorage =newWxMpDefaultConfigImpl(); configStorage.setAppId(appId); configStorage.setSecret(secret); configStorage.setToken(token); configStorage.setAesKey(aesKey);// 如果启用了消息加解密,则需要设置此参数 wxMpService.setWxMpConfigStorage(configStorage);return wxMpService;}}

5. 发送订阅通知

创建一个服务类用于发送订阅通知:

importme.chanjar.weixin.common.error.WxErrorException;importme.chanjar.weixin.mp.api.WxMpService;importme.chanjar.weixin.mp.bean.template.WxMpSubscribeMessage;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Service;@ServicepublicclassWxMessageService{@AutowiredprivateWxMpService wxMpService;/** * 发送订阅通知 * @param openid 用户的OpenID * @param templateId 模板ID * @param page 跳转的小程序页面路径 * @param data 消息数据 */publicvoidsendSubscribeMsg(String openid,String templateId,String page,String... data)throwsWxErrorException{WxMpSubscribeMessage message =WxMpSubscribeMessage.builder().toUser(openid).templateId(templateId).page(page).build();// 假设模板中有两个数据字段,分别为 "thing1" 和 "time2" message.addData(newWxMpSubscribeMessage.Data("thing1", data[0],"#000000")); message.addData(newWxMpSubscribeMessage.Data("time2", data[1],"#173177")); wxMpService.getMsgService().sendSubscribeMsg(message);}}

6. 控制器

6.1. 接收消息 & 获取 OpenID 的 Controller

@RestController@RequestMapping("/wx/portal")@Slf4jpublicclassWxPortalController{@AutowiredprivateWxMpService wxMpService;// GET:微信服务器验证 URL@GetMappingpublicStringverifyUrl(@RequestParamString signature,@RequestParamString timestamp,@RequestParamString nonce,@RequestParamString echostr){if(wxMpService.checkSignature(timestamp, nonce, signature)){return echostr;// 验证成功}return"fail";}// POST:接收用户消息和事件@PostMappingpublicStringhandleMessage(@RequestBodyString xmlData,@RequestParamString signature,@RequestParamString timestamp,@RequestParamString nonce,HttpServletResponse response)throwsException{if(!wxMpService.checkSignature(timestamp, nonce, signature)){return"";}WxMpXmlMessage inMessage =WxMpXmlMessage.fromXml(xmlData);String openid = inMessage.getFromUser();// 👈 获取 OpenID! log.info("收到用户消息,OpenID: {}", openid);// 示例:用户发“绑定”,我们就记录他的 OpenIDif("event".equals(inMessage.getMsgType())&&"subscribe".equals(inMessage.getEvent())){// 用户关注事件 log.info("新用户关注,OpenID: {}", openid);// TODO: 保存到数据库}elseif("text".equals(inMessage.getMsgType())&&"绑定".equals(inMessage.getContent())){// 用户手动发“绑定” log.info("用户主动绑定,OpenID: {}", openid);// TODO: 保存到数据库}// 自动回复(可选)WxMpXmlOutMessage outMessage =WxMpXmlOutMessage.TEXT().content("您好!您的OpenID已记录。").fromUser(inMessage.getToUser()).toUser(openid).build();return outMessage.toXml();}}

6.2. 发送订阅通知(使用已保存的 OpenID)

创建一个控制器来触发消息发送:

importme.chanjar.weixin.common.error.WxErrorException;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.RequestParam;importorg.springframework.web.bind.annotation.RestController;@RestControllerpublicclassWxMessageController{@AutowiredprivateWxMessageService wxMessageService;/** * 触发发送订阅通知 */@GetMapping("/sendMsg")publicStringsendMsg(@RequestParamString openid,@RequestParamString templateId,@RequestParamString page,@RequestParamString thing1,@RequestParamString time2){try{ wxMessageService.sendSubscribeMsg(openid, templateId, page, thing1, time2);return"发送成功";}catch(WxErrorException e){ e.printStackTrace();return"发送失败:"+ e.getError().getErrorMsg();}}}

7. 注意事项

  • 在实际项目中,openid 可以从数据库中查询得到,或者从前端传入。
  • templateId 是你在微信公众平台申请的具体模板的消息ID。
  • 数据字段(如 thing1, time2)应与模板中的字段相匹配。
  • 确保你的服务器能够访问微信接口服务器,并且网络稳定。

通过以上步骤,完成了一个简单的微信服务号订阅通知发送功能。根据业务需求的不同,可以调整和扩展这个基础示例,例如增加更多的消息模板、优化消息发送逻辑等。

在这里插入图片描述

“人的一生会经历很多痛苦,但回头想想,都是传奇”。


Read more

OpenCode 完全使用指南:开源 AI 编程助手入门到精通

OpenCode 完全使用指南:开源 AI 编程助手入门到精通 本教程基于 OpenCode 官方文档(https://opencode.ai/docs)和 GitHub 仓库(https://github.com/anomalyco/opencode)编写,适合零基础新手入门。 📚 目录 1. 什么是 OpenCode 2. 安装指南 3. 快速开始 4. 配置文件详解 5. Provider 配置 6. TUI 终端界面使用 7. Agent 系统 8. 自定义命令 9. 快捷键配置 10. MCP 服务器 11. LSP

By Ne0inhk
学生党申请github教育优惠到获取github-copilot pro一条龙教程

学生党申请github教育优惠到获取github-copilot pro一条龙教程

25年9月最新 申请GitHub教育优惠 到 获取GitHub co-pilot pro 一条龙教程(需要自备edu教育邮箱) 2025.9.4 博主亲测有效,可申请到两年教育优惠,无论您是否为在校学生,只要有一个可用的教育邮箱即可申请 by ZEEKLOG:Rem丶昕 注意:本教程的所有填写全部用英文! 一、前期准备 1. 需要自备自己学校的 edu 教育邮箱,例如博主的教育邮箱格式为 [email protected],准备的 edu 邮箱得搜索到对应的学校 2. 想申请教育邮箱的GitHub账号不能是新号,至少注册时间3天以上 二、绑定 edu 教育邮箱 2.1 在GitHub设置中添加自己的教育邮箱 登录 GitHub,点击右上方头像,在下拉列表中选 Settings

By Ne0inhk
2024年中最新!鸿蒙4.2成功开启无线调试

2024年中最新!鸿蒙4.2成功开启无线调试

前言 鸿蒙4.2支持“开发人员选项”,但根本没有“无线调试”的按钮可以选,只有USB调试和ADB。 无法使用Shizuku,也无法安装VMOS。 是否能开启“无线调试” 用不了,但是可以用电脑连接手机,打开ADB调试,然后可以使用Shizuku,也可以用adb的命令行安装“User rejected permissions”的应用/APP。 操作步骤 1、电脑上下载并配置ADB ADB全称Android Debug Bridge,是Android SDK中的一个工具, 使用ADB可以直接操作管理Android模拟器或者真实的Andriod设备,就是起到调试桥的作用。 安卓官方网址可以下载最新版的adb,提供了Windows、Mac和Linux版本 下载链接:官方adb下载地址 ADB不需要安装,只需将其路径添加到系统环境变量中,不同操作系统的配置方法可以查看这篇文章:ADB详细下载安装及使用教程 2、打开手机的“开发人员选项” 设置》关于手机》版本号,连续点击版本号的位置7次,即可打开开发人员选项 3、

By Ne0inhk