【Java】Java实现微信小程序发送服务通知

淡淡的烟草味﹌ 2023-10-13 19:44 106阅读 0赞

文章目录

  • 前言
  • 一、文档来源
  • 二、JAR包引入
  • 三、后端工作
  • 四、编写配置文件
    • 配置一:WxConfig
    • 配置二:WxProperties
  • 五、代码编写

前言

在上个月接到一个需求,大概是需要计算一条数据的最大办理时间从而发送任务超期的微信小程序服务通知,也是第一次接触到需要调用微信的API去进行发送消息,该博客记录此次功能开发的过程。

一、文档来源

本身微信的官方文档是提供了采用http调用的方式去进行调用微信的API微信小程序官方文档
但是俺想着都已经是什么年代了,于是找到了GitHub上的一个资料GitHub地址

我们可以看到几乎涵盖了所有微信相关的API
在这里插入图片描述

可以理解为不同的jar包对应引入了不从的SDK库,使调用的更方便,更简洁,下面就来依次讲解吧:

二、JAR包引入

  1. <dependency>
  2. <groupId>com.github.binarywang</groupId>
  3. <artifactId>weixin-java-miniapp</artifactId>
  4. <version>4.0.0</version>
  5. </dependency>

准备工作当然不止后端的JAR包引入,我们还需要选择一个将要发送消息通知的模板,此步如果是全栈大怨种就看该官方文档,很详细选择服务通知模板,如果是后端好哥们,就让前端自己研究,宗旨是需要拿到模板ID很重要!!见下图,为我圈中的那个ID,需要被后端拿到。

在这里插入图片描述

三、后端工作

我们先看我们所需要的所有配置,笔者均写到了yml中,可能不是太好看,见谅~

  1. wx:
  2. miniapp:
  3. #上面拿到的很重要的那个模板ID
  4. template-id: g19lTFku79jXC58CDzTnoIeazJC8HHvbW82apat_vgs
  5. configs:
  6. #微信小程序的appid 开发者工具拿到
  7. appid: wx05e2612sfav212bddev12
  8. #开发者工具拿到Secret
  9. secret: 91b5a9e5645e8cf2123213safasfgwgf
  10. #微信小程序消息服务器配置的token
  11. token: 123
  12. #微信小程序消息服务器配置的EncodingAESKey
  13. aesKey:
  14. msgDataFormat: JSON

四、编写配置文件

该配置文件笔者这里为两个,大家也可以只写一个,主要目的是为了注入引入的JAR包中的WxMaService,只有用这个,我们才能进行调用API

配置一:WxConfig

这里需要注意的是笔者的WxProperties是写的另一个配置文件,如果大家觉得写配置文件很麻烦,也可以写一个,采用手动注入值的放肆,这个WxProperties见下一个配置文件:

  1. @Slf4j
  2. @Configuration
  3. @EnableConfigurationProperties(WxProperties.class)
  4. public class WxConfig {
  5. private final WxProperties properties;
  6. @Autowired
  7. public WxConfig(WxProperties properties) {
  8. this.properties = properties;
  9. }
  10. @Bean
  11. public WxMaService getService() {
  12. if (properties == null || properties.getAppid() == null || properties.getSecret() == null) {
  13. throw new WxRuntimeException("required wechat param not found");
  14. }
  15. WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
  16. config.setAppid(properties.getAppid());
  17. config.setSecret(properties.getSecret());
  18. config.setToken(properties.getToken());
  19. config.setAesKey(properties.getAesKey());
  20. config.setMsgDataFormat(properties.getMsgDataFormat());
  21. WxMaService service = new WxMaServiceImpl();
  22. service.setWxMaConfig(config);
  23. return service;
  24. }

配置二:WxProperties

采用配置类注入的方式,如果大家不想写配置,可以采用手动设置值,目的是为了让上面的配置中的service注入到容器里面。

  1. @Data
  2. @ConfigurationProperties(prefix = "wx.miniapp.configs")
  3. public class WxProperties {
  4. /**
  5. * 设置微信小程序的appid
  6. */
  7. private String appid;
  8. /**
  9. * 设置微信小程序的Secret
  10. */
  11. private String secret;
  12. /**
  13. * 设置微信小程序消息服务器配置的token
  14. */
  15. private String token;
  16. /**
  17. * 设置微信小程序消息服务器配置的EncodingAESKey
  18. */
  19. private String aesKey;
  20. /**
  21. * 消息格式,XML或者JSON
  22. */
  23. private String msgDataFormat;
  24. }

五、代码编写

  1. @RestController
  2. @Slf4j
  3. @Api(tags = "测试接口")
  4. public class ZbSendDemoController {
  5. @Autowired
  6. private WxMaService wxService;
  7. @Value("${wx.miniapp.template-id}")
  8. private String templteId;
  9. @Resource
  10. public RabbitTemplate rabbitTemplate;
  11. /**
  12. * 跳转的小程序页面
  13. */
  14. private static final String PAGES_ZP = "pages/draft-review/list/list";
  15. @GetMapping("/api/zphs/sendZbhsMsg")
  16. @ApiOperation("传openId发送微信服务通知")
  17. public ApiResult<Boolean> sendMsg(String openID) {
  18. sendSmallMsg(openID);
  19. return ApiResult.success(true);
  20. }
  21. private void sendSmallMsg(String openId) {
  22. Map<String, String> map = new HashMap<>();
  23. map.put("phrase1","测试");
  24. map.put("thing3", "您收到了应征公民测试测试的任务提醒消息");
  25. map.put("time12", LocalDateTimeUtil.formatNormal(LocalDateTime.now()));
  26. WxMaSubscribeMessage wxMaSubscribeMessage = WxMaSubscribeMessage.builder()
  27. .toUser(openId)
  28. .templateId(templteId)
  29. .page(PAGES_ZP)
  30. .build();
  31. // 设置将推送的消息
  32. map.forEach((k, v) -> {
  33. wxMaSubscribeMessage.addData(new WxMaSubscribeMessage.Data(k, v));
  34. });
  35. try {
  36. log.info("开始发送消息!!!!");
  37. wxService.getMsgService().sendSubscribeMsg(wxMaSubscribeMessage);
  38. log.info("消息发送成功!!!!");
  39. } catch (WxErrorException e) {
  40. e.printStackTrace();
  41. }
  42. }
  43. @GetMapping("/api/zphs/sendMqDemo")
  44. @ApiOperation("消息队列发送微信服务通知测试")
  45. public ApiResult<Boolean> sendMqDemo(String taskId,String time,String state,String id ) {
  46. sendMessage( taskId, time, state,id);
  47. return ApiResult.success(true);
  48. }
  49. public void sendMessage(String taskId,String time,String state,String id) {
  50. //发送延时队列消息
  51. Map<String, Object> map = new HashMap<>(10);
  52. map.put("taskId", taskId);
  53. map.put("state", state);
  54. map.put("bzpId",id);
  55. String message = JSON.toJSONString(map);
  56. log.info("开始发送!!!");
  57. rabbitTemplate.convertAndSend(RabbitMqSendMsgConfig.DELAYED_EXCHANGE_NAME, RabbitMqSendMsgConfig.DELAYED_ROUTING_KEY,
  58. message, msg -> {
  59. msg.getMessageProperties().setDelay(Integer.parseInt(time));
  60. return msg;
  61. });
  62. log.info("发送消息成功!!!");
  63. }

笔者这里的Controller很乱,因为里面不仅有发送消息的代码,也有RabbitMq的代码,当然这都是和具体业务相关,我们的重点是sendSubscribeMsg到这一步,消息就发送成功了,我们可以看到实例:
在这里插入图片描述

到这里,我们需要有几个地方注意:

  1. 模板中当前状态,温馨提示,工单创建时间均为参数对应值,代码是为发送前的Map里面
  2. Controller最上面有一行:

    1. private static final String PAGES_ZP = "pages/draft-review/list/list";

    对应为点击进入小程序跳转的页面,为具体业务所定

  3. OpenId是个很重要的东西,是登录微信小程序都会获取到的,唯一性的,微信的API就是通过OpenId给具体的用户发送消息,所以第一个方法内我的参数就为OpenId,这个OpenId是前端传输到后端的,我在这里仅仅是一个Demo接口,切记

一定要和微信小程序模板上的保持一致,个数及参数名(模板的参数可以在微信开发者工具上看),注意部分参数有字数限制,具体限制要求可以查看微信开发者工具上的具体描述。

发表评论

表情:
评论列表 (有 0 条评论,106人围观)

还没有评论,来说两句吧...

相关阅读