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時用戶授權的注意事項,文章中若有問題請指出,謝謝!

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