Java实现微信公众号模板消息推送

一、开发前准备

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

       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时用户授权的注意事项,文章中若有问题请指出,谢谢!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章