文章目录
- 1. 准备工作
- 2. 添加 Maven 依赖
- 3. 配置文件
- 4. 创建配置类
- 5. 发送订阅通知
- 6. 控制器
- 6.1. 接收消息 & 获取 OpenID 的 Controller
- 6.2. 发送订阅通知(使用已保存的 OpenID)
- 7. 注意事项
上一篇文章介绍的是使用模板消息进行消息的推送,本文使用微信服务号订阅通知来推送消息;因为随着微信的发展,转向使用“订阅通知”是大势所趋。
使用微信服务号的订阅通知功能,可以向用户发送定制化的消息。本文给出 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_appidsecret:your_secrettoken:your_tokenaes-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}")privateStringappId;@Value("${wx.mp.secret}")privateStringsecret;@Value("${wx.mp.token}")privateStringtoken;@Value("${wx.mp.aes-key}")privateStringaesKey;@BeanpublicWxMpServicewxMpService(){WxMpServicewxMpService=newWxMpServiceImpl();WxMpDefaultConfigImplconfigStorage=newWxMpDefaultConfigImpl();configStorage.setAppId(appId);configStorage.setSecret(secret);configStorage.setToken(token);configStorage.setAesKey(aesKey);// 如果启用了消息加解密,则需要设置此参数wxMpService.setWxMpConfigStorage(configStorage);returnwxMpService;}}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{@AutowiredprivateWxMpServicewxMpService;/** * 发送订阅通知 * @param openid 用户的OpenID * @param templateId 模板ID * @param page 跳转的小程序页面路径 * @param data 消息数据 */publicvoidsendSubscribeMsg(Stringopenid,StringtemplateId,Stringpage,String...data)throwsWxErrorException{WxMpSubscribeMessagemessage=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{@AutowiredprivateWxMpServicewxMpService;// GET:微信服务器验证 URL@GetMappingpublicStringverifyUrl(@RequestParamStringsignature,@RequestParamStringtimestamp,@RequestParamStringnonce,@RequestParamStringechostr){if(wxMpService.checkSignature(timestamp,nonce,signature)){returnechostr;// 验证成功}return"fail";}// POST:接收用户消息和事件@PostMappingpublicStringhandleMessage(@RequestBodyStringxmlData,@RequestParamStringsignature,@RequestParamStringtimestamp,@RequestParamStringnonce,HttpServletResponseresponse)throwsException{if(!wxMpService.checkSignature(timestamp,nonce,signature)){return"";}WxMpXmlMessageinMessage=WxMpXmlMessage.fromXml(xmlData);Stringopenid=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: 保存到数据库}// 自动回复(可选)WxMpXmlOutMessageoutMessage=WxMpXmlOutMessage.TEXT().content("您好!您的OpenID已记录。").fromUser(inMessage.getToUser()).toUser(openid).build();returnoutMessage.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{@AutowiredprivateWxMessageServicewxMessageService;/** * 触发发送订阅通知 */@GetMapping("/sendMsg")publicStringsendMsg(@RequestParamStringopenid,@RequestParamStringtemplateId,@RequestParamStringpage,@RequestParamStringthing1,@RequestParamStringtime2){try{wxMessageService.sendSubscribeMsg(openid,templateId,page,thing1,time2);return"发送成功";}catch(WxErrorExceptione){e.printStackTrace();return"发送失败:"+e.getError().getErrorMsg();}}}7. 注意事项
- 在实际项目中,openid 可以从数据库中查询得到,或者从前端传入。
- templateId 是你在微信公众平台申请的具体模板的消息ID。
- 数据字段(如 thing1, time2)应与模板中的字段相匹配。
- 确保你的服务器能够访问微信接口服务器,并且网络稳定。
通过以上步骤,完成了一个简单的微信服务号订阅通知发送功能。根据业务需求的不同,可以调整和扩展这个基础示例,例如增加更多的消息模板、优化消息发送逻辑等。
“人的一生会经历很多痛苦,但回头想想,都是传奇”。