java实现微信小程序订阅和推送订阅信息

#小程序端配置

1、进入微信公众平台,扫码登录

    https://mp.weixin.qq.com/

2、获取appid和secret

    小程序后台->开发->开发管理->开发设置->开发者 ID(需要配置在yml文件中)

3、配置模板

    小程序后台->功能->订阅消息->我的模板->搜索需要模板(企业主体可以添加模板)->点击模板后面选用->选择关键词并填写场景->提交->点击详情->可以看到模板的详细信息->模板id需要配置在yml中。
    需要注意的是thing最多接收20个字符,如果字符过多可配置character_string类型,该类型最多32个字符

java实现微信小程序订阅和推送订阅信息_第1张图片

后端代码配置

在对应yml中配置

spring-boot-plus:
  wechat:
    secret: 微信小程序中的secret
    appid: 微信小程序中的appid
    host: https://api.weixin.qq.com   固定配置
    templateId1: 需要使用的模板id  该配置的key的值自定义,可配置多个
    templateId2: xxx
    path1: /xxx/index/tagview/meeting/meeting?id=   点击通知详情后的跳转路径,可配置多个
    path2: /xxx/index/activity/activity?id=

增加订阅次数

前端调用弹出是否订阅时调用后台服务
1、controller

    /**
     * 订阅模板消息
     */
    @PostMapping("/addSubscribe")
    @ApiOperation(value = "订阅模板消息", notes = "订阅模板消息")
    public ApiResult<Boolean> addSubscribe(@Valid @RequestBody AddSinosoftWxSubscribeParam addSinosoftWxSubscribeParam) throws Exception {
        wxSubscribeServiceImpl.subscribe(addSinosoftWxSubscribeParam);
        return ApiResult.ok();
    }

2、后端接参AddSinosoftWxSubscribeParam

@Data
@Accessors(chain = true)
@ApiModel(value = "添加小程序订阅对象", description = "小程序订阅")
public class AddSinosoftWxSubscribeParam extends BaseEntity {

    private static final long serialVersionUID = 1L;


    @ApiModelProperty(value = "消息模板id集合")
    private List<String> templateIds;

    @ApiModelProperty(value = "openid")
    private String openid;

    @ApiModelProperty(value = "是否永久订阅 1:否 2:是")
    private String isForever;

}

3、service

   /**
     * 增加订阅次数
     *
     * @param addSinosoftWxSubscribeParam
     */
    public void subscribe(AddSinosoftWxSubscribeParam addSinosoftWxSubscribeParam) {

        log.info("开始===微信增加订阅次数,addSinosoftWxSubscribeParam:[{}]", addSinosoftWxSubscribeParam);
        // 获取当前登录
        String loginUserId = RequestContext.getLoginUserId();
        //String loginUserId = "1";
        //获取用户openId
        String openId = addSinosoftWxSubscribeParam.getOpenid();
        //判断是否永久订阅
        int isForever = Integer.parseInt(addSinosoftWxSubscribeParam.getIsForever());
        //批量存库list
        List<WxSubscribe> wxSubscribeList = new ArrayList<>();
        //是否永久订阅
        int isforever = Integer.parseInt(SubscribeTypeEnum.FOREVER.getValue());
        //int isForever = 1;
        for (String templateId : addSinosoftWxSubscribeParam.getTemplateIds()) {
            //查找数据库中是否有该用户的记录
            WxSubscribe wxSubscribe = wxSubscribeRepository.selectOne(templateId, loginUserId);
            log.info("用户信息,wxSubscribe:[{}]", wxSubscribe);
            //如果没有则新建用户
            if (wxSubscribe == null) {
                wxSubscribe = new WxSubscribe();
                wxSubscribe.setUserId(Long.parseLong(loginUserId));
                wxSubscribe.setTemplateId(templateId);
                wxSubscribe.setWeChatOpenid(openId);

                if (isForever == isforever) {
                    wxSubscribe.setIsForever(isforever);
                } else {
                    wxSubscribe.setTotal(1);
                }

                //保存到数据库
                //wxSubscribeMapper.insert(wxSubscribe);
            } else {
                log.info("[old-openid]" + wxSubscribe.getWeChatOpenid());
                log.info("[new-openid]" + openId);
                //判断是否永久订阅
                if (isForever == isforever) {
                    wxSubscribe.setIsForever(isforever);
                } else {
                    wxSubscribe.setTotal(wxSubscribe.getTotal() + 1);
                }
                // 更新openid
                wxSubscribe.setWeChatOpenid(openId);
                //保存到数据库
                //wxSubscribeMapper.updateById(wxSubscribe);
            }
            wxSubscribeList.add(wxSubscribe);
        }
        wxSubscribeRepository.saveOrUpdateBatch(wxSubscribeList);
        log.info("结束===微信增加订阅次数");
    }

推送订阅信息

一般时通过时间或者调度进行调用服务,以下只进行服务实现展示
1、在domain层写send方法

    public void send(String tempId, Map<String, Object> data, Long userId, String path) {
        this.send(tempId, data, Collections.singletonList(userId), path);
    }
    /**
     * 小程序通知发送
     *
     * @param tempId  通知模板
     * @param data    模板参数 其中key对应模板thing、time等值   value对应值
     * @param userIds 要发送的id
     * @param path    点击消息后打开的小程序页面
     */
    public void send(String tempId, Map<String, Object> data, List<Long> userIds, String path) {
        log.info("开始===微信通知发送业务处理,tempId:[{}],data:[{}],userIds:[{}],path:[{}]", tempId, data, userIds, path);
        //拼接模板参数
        Map<String, Object> outMap = new HashMap<>();
        for (Map.Entry<String, Object> entry : data.entrySet()) {
            Map<String, Object> inMap = new HashMap<>();
            inMap.put("value", entry.getValue());
            outMap.put(entry.getKey(), inMap);
        }
        log.info("[userIds]" + userIds);
        //是否永久订阅
        int notForever = Integer.parseInt(SubscribeTypeEnum.NOTFOREVER.getValue());
        int forever = Integer.parseInt(SubscribeTypeEnum.FOREVER.getValue());
        //查找数据库中所有订阅了该模板的用户
        List<WxSubscribe> tmpSinosoftWxSubscribes = wxSubscribeRepository.selectWxSubscribeList(tempId, userIds);
        List<WxSubscribe> wxSubscribes = tmpSinosoftWxSubscribes.stream().filter(x -> (x.getIsForever() == forever || (x.getIsForever() == notForever && x.getTotal() > 0))).collect(Collectors.toList());
        log.info("[wxSubscribes]" + wxSubscribes);
        //订阅用户为空则不往下执行
        if (CollectionUtil.isEmpty(wxSubscribes)) {
            return;
        }

        //获取微信api调用token
        String token = this.getToken();
        //批量更新微信发送通知记录表
        List<WxSendNoticeRecord> wxSendNoticeRecordList = new ArrayList<>();
        //遍历订阅用户,逐一推送消息
        for (WxSubscribe subscribeMessage : wxSubscribes) {
            //模板id
            String templateId = subscribeMessage.getTemplateId();
            //构建消息实体
            //Map resultMap = new HashMap<>();
            JSONObject resultMap = new JSONObject();
            //接收用户的openid
            resultMap.put("touser", subscribeMessage.getWeChatOpenid());
            //消息模板id(从小程序后台获取)
            resultMap.put("template_id", templateId);
            //点击消息后打开的小程序页面
            resultMap.put("page", path);
            log.info("[path]" + path);
            resultMap.put("data", outMap);
            //推送消息
            JSONObject wxNoticeResult = this.sendMessage(token, resultMap.toString());
            //数据库中的订阅次数-1
            //如果是永久不需-1  非永久-1
            int isForever = subscribeMessage.getIsForever();
            if (isForever == notForever) {
                subscribeMessage.setTotal(subscribeMessage.getTotal() - 1);
            }
            //拼接发送记录表
            WxSendNoticeRecord wxSendNoticeRecord = new WxSendNoticeRecord();
            wxSendNoticeRecord
                    .setUserId(subscribeMessage.getUserId())
                    .setTemplateId(templateId)
                    .setNoticemsg(data.toString())
                    .setErrcode(wxNoticeResult.getString("errcode"))
                    .setErrmsg(wxNoticeResult.getString("errmsg"));
            wxSendNoticeRecordList.add(wxSendNoticeRecord);
            //wxSubscribeMapper.updateById(subscribeMessage);
        }
        //批量更新剩余发送条数
        wxSubscribeRepository.updateBatchById(wxSubscribes);
        //批量更新发送记录
        wxSendNoticeRecordRepository.saveBatch(wxSendNoticeRecordList);
        log.info("结束===微信通知发送业务处理");

    }
    /**
     * 发送消息
     *
     * @param token
     * @param body
     */
    private JSONObject sendMessage(String token, String body) {
        log.info("开始===微信订阅推送,token:[{}],body:[{}]", token, body);
        String url = this.host + "/cgi-bin/message/subscribe/send?access_token=" + token;
        HttpRequest request = HttpRequest.post(url);
        log.info("[body]" + body);
        if (body != null) {
            request.body(body);
        }
        request.contentType("application/json");
        HttpResponse httpResponse = request.execute();
        httpResponse.charset(StandardCharsets.UTF_8);
        String result = httpResponse.body();
        JSONObject object = JSON.parseObject(result);
        log.info("开始===微信订阅推送,result:[{}]" + result);
        return object;
    }

    /**
     * 获取微信api凭证
     *
     * @return
     */
    private String getToken() {
        log.info("开始===微信获取token");
        String url = this.host + "/cgi-bin/token?grant_type=client_credential&appid=" + this.appid + "&secret=" + this.secret;
        HttpRequest req = HttpRequest.get(url);
        HttpResponse resp = req.execute();
        resp.charset(StandardCharsets.UTF_8);
        String respBody = resp.body();
        log.info("[respBody]" + respBody);
        log.info("结束===微信获取token,result:[{}]", respBody);
        JSONObject object = JSON.parseObject(respBody);
        return object.getString("access_token");
    }

前端也需进行调用接口(以下简单写)

1、首先小程序授权登陆获取 code
2、将 code 传给服务端 获取用户唯一标识 openId
3、通过代码起小程序消息订阅界面、用户点击确定ok,小程序工作结束

本文具体实现参考其他博客见链接

https://www.cnblogs.com/bxmm/archive/2023/04/03/17283908.html

你可能感兴趣的:(java,微信小程序,微信小程序订阅消息)