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

#小程序端配置

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

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

2、获取appid和secret

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

3、配置模板

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

在这里插入图片描述

后端代码配置

在对应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<String,Object> 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

  • 2
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
如果您下载了本程序,但是该程序存在问题无法运行,那么您可以选择退款或者寻求我们的帮助(如果找我们帮助的话,是需要追加额外费用的)。另外,您不会使用资源的话(这种情况不支持退款),也可以找我们帮助(需要追加额外费用) 随着移动互联网技术的发展和用户需求的变化,【小程序名称】应运而生,以其轻量化、便捷化的设计理念为用户提供了一种全新的服务模式。作为一款无需下载安装即可使用的应用,【小程序名称】依托于微信庞大的生态系统,让用户在微信内就能轻松实现各种功能操作。 【小程序名称】的核心功能主要集中在【具体服务领域】,例如在线购物、本地生活服务、教育学习或健康管理等。它简化了传统APP繁琐的注册登录流程,支持微信一键授权登录,极大地提升了用户体验。用户通过搜索或扫描二维码,瞬间即可开启使用,享受快速加载、流畅运行的服务。 该小程序界面设计简洁明了,布局合理,易于上手。同时,其特色功能如实时更新的信息推送、个性化推荐以及社交分享功能,让用户能够及时获取所需信息,并方便地将优质内容分享至朋友圈或好友,实现信息的高效传播与互动。 【小程序名称】注重数据安全与隐私保护,严格遵守国家法律法规和微信平台的规定,确保用户数据的安全无虞。此外,其背后的开发团队持续迭代更新,根据用户反馈不断优化产品性能,提升服务质量,致力于打造一个贴近用户需求、充满活力的小程序生态。 总结来说,【小程序名称】凭借其小巧便携、快捷高效的特性,不仅节省了用户的手机存储空间,更为用户提供了无缝衔接的便利服务,是现代生活中不可或缺的一部分,真正实现了“触手可及”的智能生活新体验。只需轻点屏幕,无限精彩尽在掌握之中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值