1.创建模板 ID
-
登陆微信公众平台
-
菜单栏点击订阅消息
-
选用模板。如果没有合适的模板,可以申请添加新模板
2.获取下发权限
小程序端调用requestSubscribeMessage
使用方法:
wx.requestSubscribeMessage({ tmplIds: [''], success (res) { } })
3.调用接口下发订阅消息
-
下发消息的核心在于发送POST请求:
subscribeMessage.send
,通过此条请求我们将获得下发能力:
@Log4j2 public class TemplateUtils { /** * 小程序推送模版消息 * @param weChatTemplate 微信操作对象 * @param redisTemplate redis操作对象 * @param openId 接收者openId * @param page 小程序页面路径 * @param templateId 推送模版id * @param data 模版参数 * @return */ public static boolean weChatSendOfPeople(WeChatTemplate weChatTemplate, RedisTemplate<String, Object> redisTemplate , String openId, String page, HashMap data,String templateId) { String token = getToken(weChatTemplate, redisTemplate); String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + token; Map param = new HashMap(); param.put("touser", openId); param.put("template_id", templateId); if (Objects.nonNull(page)) { param.put("page", page); } param.put("data", data); // param.put("miniprogram_state","developer");// 上线注掉 developer为开发版 log.error(openId); log.error(page); log.error(data); String result = HttpUtil.post(url, JSONUtil.toJsonStr(param)); log.error(result); JSONObject jsonObject = JSONUtil.parseObj(result); if (0 == jsonObject.getInt("errcode")) { return true; } return false; } public static String getToken(WeChatTemplate weChatTemplate, RedisTemplate<String, Object> redisTemplate) { String token = (String) redisTemplate.opsForValue().get("djfy_mini_access_token"); if (Objects.isNull(token)) { TecentAccessTokenResult tecentAccessTokenResult = weChatTemplate.opsForMini().getAccessToken(); token = tecentAccessTokenResult.getAccessToken(); redisTemplate.opsForValue().set("djfy_mini_access_token", token, 7000, TimeUnit.SECONDS); } return token; } }
请求实例
private void sedMessAge(Long regionId){ //推送审批--待处理 new Thread(()->{ //构建对应模板数据 HashMap<Object, Object> data = new HashMap<>(); //信息来源 HashMap<Object, Object> thing1 = new HashMap<>(); thing1.put("value", "官方消息"); data.put("thing6", thing1); //通知时间 HashMap<Object, Object> date3 = new HashMap<>(); date3.put("value", DateUtil.now()); data.put("thing8", date3); //重要提示 HashMap<Object, Object> thing4 = new HashMap<>(); thing4.put("value", "请点击详情进行查看"); data.put("thing9", thing4); //获取接受人 RentalRegion rentalRegion = regionMapper.selectByPrimaryKey(regionId); TemplateUtils.weChatSendOfPeople(weChatTemplate, redisTemplate, rentalRegion.getOpenId() , "pages/examine/examine", data,"Ibp-rUCGWxxxxxx-xxb9MiFh9nFvR-NiM5xGdjSVg"); }).start(); }
-
请求并不复杂,重要的是参数的获取,发送请求我们至少需要这些参数:
-
access_token接口调用凭证
-
touser用户的 openid
-
所需下发的订阅模板id
注意数据包的参数规则
-