近期写了个消息推送,代码挺简单的,分享一下!
前期准备工作:
直接上代码吧
实体类
@Data @Accessors(chain = true) public class WxPushMessageVo implements Serializable { /** * 推送用户openid */ private String touser; /** * 模板id */ private String template_id; /** * 小程序跳转页面 */ private String page; /** * 数据模板内容,格式形如 { "key1": { "value": any }, "key2": { "value": any } } */ private Map<String,TemplateData> data; } @Data @Accessors(chain = true) public class TemplateData implements Serializable { private String value; }
业务代码
/** * 获取小程序access_token * appid和appsecret到小程序后台获取,当然也可以让小程序开发人员给你传过来 */ public String getAccess_token() { //获取access_token String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" + "&appid=" + "" + "&secret=" + ""; String json = restTemplate.getForObject(url, String.class); JSONObject jsonObject = JSON.parseObject(json); Object access_token = jsonObject.get("access_token"); return access_token.toString(); } public void wxPushMessage(String openid) { try { //建议把accessToken存到redis里,而且这个东西会过期的,我就不多赘述了 String accessToken = getAccess_token(); //发布订阅消息url路径 String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken; WxPushMessageVo wxPushMessageVo = new WxPushMessageVo(); wxPushMessageVo.setTouser(openid).setTemplate_id("模板id").setPage("index"); Map<String, TemplateData> data = new HashMap<>(2); TemplateData thing1 = new TemplateData(); //这里根据你们定义的模板字段来填写值,可以看一下文档的接口 thing1.setValue(""); data.put("thing1", thing1); TemplateData time2 = new TemplateData(); time2.setValue(DateUtils.getTime()); data.put("time2", time2); wxPushMessageVo.setData(data); RestTemplate restTemplate = new RestTemplate(); ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, wxPushMessageVo, String.class); System.out.println("小程序推送消息返回信息:" + responseEntity.getBody()); Map<String, Object> map = objectMapper.readValue(responseEntity.getBody(), Map.class); int errcode = (int) map.get("errcode"); //我这里做了一个返回结果的判断,主要是为了防止accessToken过期导致消息推送失败 if (errcode == 40001 || errcode == 42001) { log.info("消息订阅的accessToken到期了"); //可以自己写一个方法来重新生成新的accessToken,不多赘述 setGloAccessToken(); wxPushMessage(openid); } } catch (Exception e) { e.printStackTrace(); } }
基本上就可以了,测试一下就行,前提得是用户同意接收订阅消息哈!