微信公众号开发2模板消息

自动添加模板消息,后台根据域名自动配置模板消息,菜单,工具类同上

 /**
     * 预约教室发送模板消息
     * @param dbOrder
     */
    public void sendOrderTemplateMsg(OrderRecordWx  dbOrder){
        try {
            Map map = new HashMap();
            map.put("userName",dbOrder.getCreateUser());
            AuthUser authInfo = authUserService.findUserByParam(map).get(0);
            Template template = new Template();
            SysParameter  templateIdInfo = sysParameterService.getSysParameter("order_template_id");
            String templateId = templateIdInfo.getParaValue();
            template.setTemplateId(templateId);
            template.setToUser(authInfo.getOpenId());
            template.setUrl(WeChatConfigController.cacheWxMap.get("wx_url")+"/scp/rest/third/wx/orderDetailPage?id="+dbOrder.getId());
            List paras = new ArrayList();
            String msg = "";
            if(dbOrder.getOrderStatus() == 2 ){
                msg = MessageSourceUtil.getMessage("scp_wx_template_order_room_fail",new Object[] {dbOrder.getId()});
            }else if(dbOrder.getOrderStatus() == 1 ){
                msg = MessageSourceUtil.getMessage("scp_wx_template_order_room_success",new Object[] {dbOrder.getId()});
            }else{
				msg = MessageSourceUtil.getMessage("scp_wx_template_order_room_reviewed",new Object[] {dbOrder.getId()});
			}
            paras.add(new TemplateParam("first",msg,""));
            if(dbOrder.getbClassTime().getName().equals(dbOrder.geteClassTime().getName())){
				paras.add(new TemplateParam("keyword1",DateUtil.formateDate2String(dbOrder.getScheduleDate())+
						dbOrder.getbClassTime().getName(),""));
			}else{
				paras.add(new TemplateParam("keyword1",DateUtil.formateDate2String(dbOrder.getScheduleDate())+
						dbOrder.getbClassTime().getName() + "-" + dbOrder.geteClassTime().getName(),""));
			}
            paras.add(new TemplateParam("keyword2",dbOrder.getRoom().getBuilding().getArea()+"-"+
                    dbOrder.getRoom().getBuilding().getName()+"-"+dbOrder.getRoom().getName(),""));
            paras.add(new TemplateParam("keyword3",dbOrder.getDescription(),""));
            paras.add(new TemplateParam("remark",MessageSourceUtil.getMessage("scp_wx_template_order_room_remark"),""));
            template.setTemplateParamList(paras);
            WeiXinUtils.sendTemplateMsg(template);
        } catch (Exception e) {
            logger.error("模板消息发送失败:"+e.getMessage());
        }
    }
 /**
     * 获取微信公众号配置app_id,app_secret,scp_wx_url,模板消息等
     */
    @RequestMapping(value = "/saveWxConfig", method = RequestMethod.POST)
    @ResponseBody
    public Map saveWxConfig(HttpServletRequest request) {
        Map resultMap = new HashMap();
        resultMap.put("success", false);
        resultMap.put("msg", MessageFormat.format("common_operation_fail"));
        try {
            String appId = request.getParameter("appId");
            String appSecret = request.getParameter("appSecret");
            String wxUrl = request.getParameter("wxUrl");
            String wxFileName = request.getParameter("wxFileName");
            if (StringUtils.isEmpty(appId) || StringUtils.isEmpty(appSecret) || StringUtils.isEmpty(wxUrl)) {
                return resultMap;
            }
            SysParameter appIdSys = sysParameterService.getSysParameter("app_id");
            appIdSys.setParaValue(appId);
            sysParameterService.update(appIdSys);

            SysParameter appSecretSys = sysParameterService.getSysParameter("app_secret");
            appSecretSys.setParaValue(appSecret);
            sysParameterService.update(appSecretSys);

            SysParameter wxUrlSys = sysParameterService.getSysParameter("wx_url");
            wxUrlSys.setParaValue(wxUrl);
            sysParameterService.update(wxUrlSys);

            SysParameter wxFileNameObj = sysParameterService.getSysParameter("wx_file_name");
            wxFileNameObj.setParaValue(wxFileName);
            sysParameterService.update(wxFileNameObj);
            //重新加载配置
            this.reloadWxInfo();
            //todo 域名如果有修改需要更新二维码
            String QRCodePath = request.getServletContext().getRealPath(QRCodeUtil.QRCODE_PATH);
            WeiXinUtils.deleteDirectory(QRCodePath);
            //创建微信菜单
            if (createMenu()) {
                resultMap.put("success", true);
                resultMap.put("msg", MessageFormat.format("common_operation_success"));
            } else {
                resultMap.put("success", true);
                resultMap.put("msg", MessageFormat.format("scp_wx_create_menu_fail"));
            }
            //添加模板消息
            if (!createTemplateId()) {
                logger.error("模板消息创建失败");
            }
            //生成公众号配置
            if (!createTxt(request, wxFileName)) {
                logger.error("生成公众号配置失败");
            }
        } catch (Exception e) {
            logger.error("updateWxConfig is error:" + e.getMessage());
            resultMap.put("msg", e.getMessage());
        }
        return resultMap;
    }

    private boolean createMenu() {
        //更新菜单
        JSONArray menuArr = new JSONArray();
        Map map = null;
        try {
            map = new HashMap();
            Map map1 = new HashMap();
            map.put("name", "xxxxx");
            map.put("type", "view");
            map.put("url", cacheWxMap.get("wx_url") + "/scp/rest/third/wx/authUser?menu=orderView");
            menuArr.add(map);
            map1.put("name", "xxxx");
            map1.put("type", "view");
            map1.put("url", cacheWxMap.get("wx_url") + "/scp/rest/third/wx/authUser?menu=userCenter");
            menuArr.add(map1);
            String menu = JSONArray.toJSONString(menuArr);
            String menuParam = "{\"button\":" + menu + "}";
            String token = WeiXinUtils.getToken();
            String result = WeiXinUtils.doPost(WeiXinUtils.CREATE_MENU + token, menuParam);
            JSONObject mapResult = JSONObject.parseObject(result);
            if (0 == mapResult.getInteger("errcode")) {
                logger.info("生成菜单成功" + mapResult.toJSONString());
                return true;
            } else {
                logger.error("生成菜单失败" + mapResult.toJSONString());
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    private boolean createTemplateId() {
        try {
            Map resultMap = WeiXinUtils.setTemplate();
            if (!StringUtils.isEmpty(String.valueOf(resultMap.get("msg")))) {
                String changeTemplateId = (String) resultMap.get("change_template_id");
                SysParameter changeTemplateIdObj = sysParameterService.getSysParameter("change_template_id");
                changeTemplateIdObj.setParaValue(changeTemplateId);
                sysParameterService.update(changeTemplateIdObj);
                String orderTemplateId = (String) resultMap.get("order_template_id");
                SysParameter orderTemplateIdObj = sysParameterService.getSysParameter("order_template_id");
                orderTemplateIdObj.setParaValue(orderTemplateId);
                sysParameterService.update(orderTemplateIdObj);
                return true;
            }
        } catch (Exception e) {
            logger.error("生成模板消息失败:" + e.getMessage());
        }
        return false;
    }

    private boolean createTxt(HttpServletRequest request, String fileName) {
        //String path = request.getServletContext().getRealPath(File.separator);
//        File file = new File(realPath);
//        if (!file.getParentFile().exists()) {
//            file.getParentFile().mkdirs();
//        }
        String path = System.getProperty("user.dir");
        File fileUser = new File(path);
        String strParentDirectory = fileUser.getParent();
        try {
            File file = new File(strParentDirectory + File.separator + "nginx" + File.separator + "html" + File.separator + fileName);
                if (!file.exists()) {
                    file.createNewFile();
                    FileWriter fw = new FileWriter(file, true);
                    BufferedWriter bw = new BufferedWriter(fw);
                    String[] content = fileName.split("_");
                    String[] writeContetn = content[2].split("\\.");
                    bw.write(writeContetn[0]);
                    bw.flush();
                    bw.close();
                    fw.close();
                }
                return true;
        } catch (IOException e) {
            logger.error("生成模板消息失败:" + e.getMessage());
        }
            return false;
    }
import java.util.List;

public class Template {

    // 消息接收方
    private String toUser;
    // 模板id
    private String templateId;
    // 模板消息详情链接
    private String url;
    // 消息顶部的颜色
    private String topColor;
    // 参数列表
    private List templateParamList;

    public String getToUser() {
        return toUser;
    }

    public void setToUser(String toUser) {
        this.toUser = toUser;
    }

    public String getTemplateId() {
        return templateId;
    }

    public void setTemplateId(String templateId) {
        this.templateId = templateId;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getTopColor() {
        return topColor;
    }

    public void setTopColor(String topColor) {
        this.topColor = topColor;
    }

    public String toJSON() {
        StringBuffer buffer = new StringBuffer();
        buffer.append("{");
        buffer.append(String.format("\"touser\":\"%s\"", this.toUser)).append(",");
        buffer.append(String.format("\"template_id\":\"%s\"", this.templateId)).append(",");
        buffer.append(String.format("\"url\":\"%s\"", this.url)).append(",");
        buffer.append(String.format("\"topcolor\":\"%s\"", this.topColor)).append(",");
        buffer.append("\"data\":{");
        TemplateParam param = null;
        for (int i = 0; i < this.templateParamList.size(); i++) {
            param = templateParamList.get(i);
            // 判断是否追加逗号
            if (i < this.templateParamList.size() - 1){

                buffer.append(String.format("\"%s\": {\"value\":\"%s\",\"color\":\"%s\"},", param.getName(), param.getValue(), param.getColor()));
            }else{
                buffer.append(String.format("\"%s\": {\"value\":\"%s\",\"color\":\"%s\"}", param.getName(), param.getValue(), param.getColor()));
            }

        }
        buffer.append("}");
        buffer.append("}");
        return buffer.toString();
    }

    public List getTemplateParamList() {
        return templateParamList;
    }

    public void setTemplateParamList(List templateParamList) {
        this.templateParamList = templateParamList;
    }

}
public class TemplateParam {
    // 参数名称
    private String name;
    // 参数值
    private String value;
    // 颜色
    private String color;

    public TemplateParam(String name,String value,String color){
        this.name=name;
        this.value=value;
        this.color=color;
    }
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }



}
//第一遍漏的消息类型
public class TextMessage {
    private String ToUserName;
    private String FromUserName;
    private String CreateTime;
    private String MsgType;
    private String Content;
    private String MsgId;

    public String getToUserName() {
        return ToUserName;
    }

    public void setToUserName(String toUserName) {
        ToUserName = toUserName;
    }

    public String getFromUserName() {
        return FromUserName;
    }

    public void setFromUserName(String fromUserName) {
        FromUserName = fromUserName;
    }

    public String getCreateTime() {
        return CreateTime;
    }

    public void setCreateTime(String createTime) {
        CreateTime = createTime;
    }

    public String getMsgType() {
        return MsgType;
    }

    public void setMsgType(String msgType) {
        MsgType = msgType;
    }

    public String getContent() {
        return Content;
    }

    public void setContent(String content) {
        Content = content;
    }

    public String getMsgId() {
        return MsgId;
    }

    public void setMsgId(String msgId) {
        MsgId = msgId;
    }
}

 

你可能感兴趣的:(微信公众号开发)