微信小程序订阅发布

实现微信小程序订阅发布

1.创建订阅模板

2.小程序调用订阅

小程序需要引导用户授权订阅,服务端发送订阅消息才能收到

3.服务端发送订阅消息

@Slf4j
@Api(tags="小程序")
@RestController
@RequestMapping("/app")
public class HoursAppletController {
    /**发送订阅消息*/
    @GetMapping("/send/{oprenId}")
    public Result send(@PathVariable("oprenId") String oprenId){
        String push = this.push(oprenId);
        return Result.OK(push);
    }

    /**获取小程序AccessToken*/
    //MINAPPID(小程序ID)、MAINAPPSECRET(小程序密钥)、MINAPPTEMPLATEID(订阅消息模板id  )
    public String getAccessToken() {
        RestTemplate restTemplate = new RestTemplate();
        Map<String, String> params = new HashMap<>();
        params.put("APPID", MINAPPID);
        params.put("APPSECRET", MAINAPPSECRET);
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(
                "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={APPID}&secret={APPSECRET}", String.class, params);
        String body = responseEntity.getBody();
        JSONObject object = JSON.parseObject(body);
        String Access_Token = object.getString("access_token");
        String expires_in = object.getString("expires_in");
        log.info("有效时长expires_in:" + expires_in);
        return Access_Token;
    }

      /**获取发送订阅消息*/
      public String push(String openid) {
        RestTemplate restTemplate = new RestTemplate();
        //这里简单起见我们每次都获取最新的access_token(时间开发中,应该在access_token快过期时再重新获取)
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + getAccessToken();
        //拼接推送的模版
        WxMssVo wxMssVo = new WxMssVo();
        //用户的openid(要发送给那个用户,通常这里应该动态传进来的)
        wxMssVo.setTouser(openid);
        //订阅消息模板id
        wxMssVo.setTemplate_id(MINAPPTEMPLATEID);
        wxMssVo.setPage("pages/index/index");

        Map<String, TemplateData> m = new HashMap<>(3);
        m.put("thing1", new TemplateData("工时提交"));
        m.put("date2", new TemplateData( DateUtil.format(new Date(), "yyyy-MM-dd HH:mm")));
        m.put("thing3", new TemplateData("今天工作辛苦啦,请记得提交当日工时哦"));
        wxMssVo.setData(m);
        ResponseEntity<String> responseEntity =
                restTemplate.postForEntity(url, wxMssVo, String.class);
        return responseEntity.getBody();
    }
}

posted @ 2021-11-08 16:07  Java程序位移师  阅读(263)  评论(0)    收藏  举报