SpringBoot项目实现微信公众号模板消息推送

一、开发前准备

       需要到微信公众号平台获取几个必要的参数:

       appId,appSecret,templateId(消息模板id),openId(用户访问时授权获取)

       消息模板选择一个适合自己业务的,然后拿到模板id,再将数据格式填充就可以了。

二、微信模板消息推送代码

       下边的是pom中需要导入的依赖,版本可以自己选择。

<!--微信模版消息推送三方sdk-->
<dependency>
    <groupId>com.github.binarywang</groupId>
    <artifactId>weixin-java-mp</artifactId>
    <version>3.3.0</version>
</dependency>

        代码中的SystemConstant类为我自己定义的系统常量类,引用的推送消息需要的参数。

public void sendApproveMsg(PurchaseOrder order, String openId) {
        //1-配置
        WxMpInMemoryConfigStorage wxStorage = new WxMpInMemoryConfigStorage();
        wxStorage.setAppId(SystemConstant.APP_ID);
        wxStorage.setSecret(SystemConstant.APP_SECRET);
        WxMpService wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(wxStorage);
        String color = "#FFA500";//橙色
        //color = "#001EFF";蓝色
        //color = "#FF0000";红色
        //color = "#FFFF00";黄色

        //2-推送消息
        WxMpTemplateMessage templateMessage = new WxMpTemplateMessage();
        //消息模板id
        templateMessage.setTemplateId(SystemConstant.MSG_TEMPLATE_ID);
        //点击模版消息要访问的网址
        String alarmPath = "https://www.qinwutong.com/approve/code";
        templateMessage.setUrl(alarmPath);
        List<WxMpTemplateData> wxMpTemplateData = new ArrayList<>();
        // {{first.DATA}}
        wxMpTemplateData.add(new WxMpTemplateData("first", "您有新的采购单需要审批,请尽快处理", color));
        //单号:{{keyword1.DATA}}
        wxMpTemplateData.add(new WxMpTemplateData("keyword1", order.getId(), color));
        //金额:{{keyword2.DATA}}\
        wxMpTemplateData.add(new WxMpTemplateData("keyword2", MathUtils.getPrice(order.getLastPrice()), color));
        //采购人:{{keyword3.DATA}}
        wxMpTemplateData.add(new WxMpTemplateData("keyword3", order.getPurchaseName(), color));
        //供应商:{{keyword4.DATA}}
        wxMpTemplateData.add(new WxMpTemplateData("keyword4", "京东商城", color));
        //采购时间:{{keyword5.DATA}}
        wxMpTemplateData.add(new WxMpTemplateData("keyword5", MathUtils.getTime(order.getCreateTimestamp()), color));
        //{{remark.DATA}}
        wxMpTemplateData.add(new WxMpTemplateData("remark", "如有问题请拨打110", color));
        templateMessage.setData(wxMpTemplateData);
        try {
            //要推送的用户openid
            templateMessage.setToUser(openId);
            wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
        } catch (Exception e) {
            //System.out.println("推送失败:" + e.getMessage());
            e.printStackTrace();
        }
    }

三、备注

      开发微信消息推送功能之前先去看看官方的文档,包括获取openId时用户授权的注意事项,文章中若有问题请指出,谢谢!

评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值