微信发送模板消息

  • 仿照测试示例,定义一个sendTemplateToWx方法,传递参数:用户id、模板id、跳转链接、模板内容格式
/**
     * 用于发送模板消息
     * @param String[] userId, String templateId, String detail_url, String message
     * @return
     */
    public static String sendTemplateToWx(String[] userId, String templateId, String detail_url, String message) throws Exception {
        String time = new Long(new Date().getTime()).toString();        
        String signMsg = "" + new  Random(10).nextInt();
        String signature = EncrypUtil.codedSignature("bgcloud" + signMsg + "bgcloud" + "wx" + time);
        String projCode = "bgcloud";
        StringBuffer userBuffer = new StringBuffer();
        //??
        if(userId.length > 0){
            userBuffer.append(userId[0]);
        }
        for(int i = 1; i < userId.length; i++){
            userBuffer.append("&user_id=");
            userBuffer.append(userId[i]);
        }
        HttpClient httpclient=new HttpClient();
        httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);   
        httpclient.getHttpConnectionManager().getParams().setSoTimeout(timeout);
        
        String servletUrl="http://localhost:8082/PlatWX/servlet/SendTemplateMsgService"+"?user_id="+userBuffer.toString() + "&t="+time+"&signmsg="+signMsg+"&detail_url="+detail_url+"&template_id="+templateId+"&proj_code="+projCode+"&signature="+signature;
        
        PostMethod postMethod = new PostMethod(servletUrl);
        
        
        
        RequestEntity se=new StringRequestEntity(message,"content-type","UTF-8");
        postMethod.setRequestEntity(se);
        
        String returnMessage="";
        try
        {
            int statusCode=httpclient.executeMethod(postMethod);
            if(statusCode != HttpStatus.SC_OK){
                LOGGER.error("invoke wx message servlet fail, statusCode is " + statusCode);
                return returnMessage;
            }
            returnMessage = postMethod.getResponseBodyAsString();
        }
        catch (HttpException e)
        {
            LOGGER.error("invoke wx message servlet HttpException:" + e);
        }
        catch (IOException e)
        {
            LOGGER.error("invoke wx message servlet IOException:" + e);
        }
        catch(Exception e){
            LOGGER.error("invoke wx message servlet Exception:" + e);
        }
        finally{
            postMethod.releaseConnection();
        }
        return returnMessage;
    }

    protected final static Logger LOGGER = Logger
    .getLogger(WeiXinMessageManager.class);

  • 点击发布,发送模板消息:
    分 新建并发布、新建保存后发布、编辑发布 三种情况
    第一种只有一个公告编号,后两种情况可能存在一次发布多条公告(多个公告编号),以下代码只针对第一种情况:
/**
     * 新建时直接发布公告
     * @param inInfo
     * @return
     */
    public EiInfo publish(EiInfo inInfo){
        SINT01 sint01 = new SINT01();
        inInfo.getBlock(RESULT_BLOCK).setBlockMeta(sint01.eiMetadata);
        String noticeId = dao.query("SINT01.queryNoticeId", null).get(0).toString();
        inInfo.setCell(RESULT_BLOCK, 0, "noticeId", noticeId);
        String time = StringUtil.getCurrentDateStr();
        inInfo.setCell("result", 0, "createTime", time);
        inInfo.setCell("result", 0, "status", "PUBLISH");
        String loginUser = AuthUtil.getLoginUser();     
        inInfo.setCell("result", 0, "creator", loginUser);
        inInfo.setCell("result", 0, "publisher", loginUser);
        inInfo.setCell("result", 0, "publishTime", time);
        super.insert(inInfo, "SINT01.insert");
        this.saveArea(inInfo);
        
        //组织公告信息并发送模板消息
        this.queryThisNoticAllInfos(inInfo);
        
        return inInfo;
    }

  • 组织公告信息传递参数用于发布模板消息
/**
     * 查询发布公告的相关关联信息
     * @param inInfo
     * 
     */
    public void queryThisNoticAllInfos(EiInfo eiInfo){
        // 通过 公告编号 查出关联信息(新建并发布时,只发布一条公告/ 如果保存之后在发布可能存在多条公告编号,不适用 )
        String noticeId = eiInfo.getCellStr(RESULT_BLOCK, 0, "noticeId");
        // 查询新建并发布的公告的关联信息
        Map queryMap = new HashMap();
        queryMap.put("noticeId", noticeId);
        List resultList = dao.query("SINT01.queryPublishNotice", queryMap);
        
        if(null!=resultList && resultList.size()>0){
            // 组织模板消息的  标题、内容、发布时间、公告类型
            String title = resultList.get(0).getTitle();
            String description = resultList.get(0).getDescription();
            String publishTime = resultList.get(0).getPublishTime();
            String noticeCategory = resultList.get(0).getNoticeCategory();
            
            // 通过公告类型 选择模板id 并组织contentStr
            //String contentStr = "{ \"first\": \"PSCS运行日报\",  \"keyword1\": \"2017-10-11 13:00:05\", \"keyword2\": \"宝钢采购供应链\", \"remark\": \"点击查看详情\" }";
            String templateId = "";
            String contentStr = "";
            if("故障公告".equals(noticeCategory)){
                templateId = "TM00204";
                contentStr = "0000000";
            }else if("定修公告".equals(noticeCategory)){
                templateId = "111111";
                contentStr = "111111";
            }else if("服务公告".equals(noticeCategory)){
                templateId = "222222";
                contentStr = "222222";
            }else if("活动公告".equals(noticeCategory)){
                templateId = "333333";
                contentStr = "333333";
            }else if("安全公告".equals(noticeCategory)){
                templateId = "OPENTM401535248";
                contentStr = "444444444";
            }   
            
            // 组织要发送模板消息的人
            // 1.运营团队/操作团队 下的所有用户 -- 必不可少
            // 2. 该公告的 租户范围: -1 全部租户下的所有用户; 非-1 具体租户下的所有用户(分情况: 一个租户 还是 多个租户 )
            
            //因为跳转链接中的 detail_url 涉及到 公告id 以及 customerId,所以分以下几种情况:
            // 1.1 全局租户 + 两个团队  使用同一个url  customerId = -1
            // 1.2 单个租户 + 两个团队   使用同一个url customerId = 单个租户对应的id
            // 2. 多个租户 + 两个团队   使用多个url (两个团队 任意租户id; 多个租户 各自的租户id  )
            
            
            // 获取两个团队下的所有用户
            List> operatorMemberList = AuthUtil.getMemberByRoleType("Operator");
            String[] list1 = new String[operatorMemberList.size()];
            for(int i = 0; i < operatorMemberList.size(); i++){
                //{email=null, orgCode=null, bizTel=null, orgName= , displayName=张帆, idCardNum=null, loginName=002980}
                list1[i] = operatorMemberList.get(i).get("loginName");
            }
            
            List> operationMemberList = AuthUtil.getMemberByRoleType("OperationManager");
            //{email=null, orgCode=10000, bizTel= , orgName=罗泾云计算数据中心, displayName=辛晖明, idCardNum= , loginName=035595}
            String[] list2 = new String[operationMemberList.size()];
            for(int i =0; i < operationMemberList.size(); i++){
                list2[i] = operationMemberList.get(i).get("loginName");
            }
            
            // 整合 发送给两个团队下的用户 
            int twoMemberUserLength = operatorMemberList.size()+operationMemberList.size();
            String[] twoMemberUser = new String[twoMemberUserLength];
            for(int i = 0; i < twoMemberUserLength; i++){
                if(i < operatorMemberList.size()){
                    twoMemberUser[i] = list1[i];
                }else{
                    twoMemberUser[i] = list2[i-operatorMemberList.size()];
                }
            }
            
            
            // 判断 单个租户/ 多个租户
            // sqlQueryUser字符串拼sql语句,用于xml传递参数
            String sqlQueryUser = "";
            String detail_url = "";
            // 单个租户(单个下分 全局租户 和 具体租户)
            if(resultList.size() == 1){
                // 全局租户
                if("-1".equals(resultList.get(0).getCustomerId())){
                    sqlQueryUser = "";  
                    detail_url = "zuhuid=-1";
                }else{
                    // 单个具体租户
                    sqlQueryUser = " " + "a.ENTERPRIZE_CODE" + "="  + resultList.get(0).getCustomerId();
                    detail_url = "zuhuid=resultList.get(0).getCustomerId()";
                }
                
                //查询 租户下的 用户
                Map queryUserMap = new HashMap();
                queryUserMap.put("sqlQueryUser", sqlQueryUser);
                List allCustomerList = dao.query("SINT01.queryAllUser", queryUserMap);
                
                // 取出所有用户名
                int num = allCustomerList.size();
                String[] customerName = new String[num];    
                if(null!=allCustomerList && allCustomerList.size()>0){              
                    for(int k= 0; k < allCustomerList.size(); k++){
                        customerName[k] = allCustomerList.get(k).getCustomerId();
                    }
                }
                
                // 整合所有用户(包含两个团队人员 以及 全部租户或单个具体租户下的用户)
                int allUserIdLength = operatorMemberList.size() + operationMemberList.size() + allCustomerList.size();
                String[] allUserId = new String[allUserIdLength];
                for(int i = 0; i < allUserIdLength; i++){
                    if(i< operatorMemberList.size()){
                        allUserId[i] = list1[i];
                    }else if( i < (operatorMemberList.size() + operationMemberList.size())){
                        allUserId[i] = list2[i-operatorMemberList.size()];
                    }else{
                        allUserId[i] = customerName[i-operatorMemberList.size() - operationMemberList.size()];
                    }
                }
                
                // 发送模板消息
                // 参数: 发送人员的id(string[])、 模板id、 跳转链接 、模板消息内容
                try {
                    sendTemplateToWx(allUserId, "aAyqAAbYLKkeMbiQC3W1LlGB8ginYPijn9sgl0Uu3IQ",detail_url,
                            contentStr);
                    // ("community", user_id,
                    // "UH75k_NvJ2GXkpj8NLdQ0JE2ahD_bm6hYCIEcMxwE1E",
                    // toHashMap(contentStr));
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }               
            }else{
                // 先给 两个团队发送模板消息
                try {
                    detail_url = "zuhuid=resultList.get(0).getCustomerId()";
                    sendTemplateToWx(twoMemberUser, "aAyqAAbYLKkeMbiQC3W1LlGB8ginYPijn9sgl0Uu3IQ",detail_url,
                            contentStr);
                    // ("community", user_id,
                    // "UH75k_NvJ2GXkpj8NLdQ0JE2ahD_bm6hYCIEcMxwE1E",
                    // toHashMap(contentStr));
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }       
                // 循环多个租户id 分别生成detail_url 发送模板消息
                for(int i = 0; i < resultList.size(); i++){
                    String moreCustomerId = resultList.get(i).getCustomerId();
                    sqlQueryUser = " " + "a.ENTERPRIZE_CODE" + "="  + moreCustomerId;
                    detail_url = "moreCustomerId";
                    // 单独租户id下的用户
                    Map queryUserMap = new HashMap();
                    queryUserMap.put("sqlQueryUser", sqlQueryUser);
                    List allCustomerList = dao.query("SINT01.queryAllUser", queryUserMap);
                    
                    int num = allCustomerList.size();
                    String[] customerName = new String[num];    
                    if(null!=allCustomerList && allCustomerList.size()>0){              
                        for(int k= 0; k < allCustomerList.size(); k++){
                            customerName[k] = allCustomerList.get(k).getCustomerId();
                        }
                    }
                    
                    try {
                        sendTemplateToWx(customerName, "aAyqAAbYLKkeMbiQC3W1LlGB8ginYPijn9sgl0Uu3IQ",detail_url,
                                contentStr);
                        // ("community", user_id,
                        // "UH75k_NvJ2GXkpj8NLdQ0JE2ahD_bm6hYCIEcMxwE1E",
                        // toHashMap(contentStr));
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
        
                }
                
            }
            
//       之前写的逻辑 把所有的租户下的用户全查出来,未考虑url,摒弃,逻辑重写   
//          查询出该公告所有要发布的租户id
//          int arrLength = resultList.size();
//          String[] arr = new String[arrLength];
//          for(int i=0; i< arrLength; i++){
//              String customerId = resultList.get(i).getCustomerId();
//              arr[i] = customerId;
//              
//              
//          }
//          根据租户id进行查询租户下的所有用户
//          之前每次for循环之后还要将数组复制合并,太麻烦,现在直接将所有的租户id关联用户一次性查出来放到一个数组中
//          使用sql语句 or连接所有的租户id
//          String sqlQueryUser = "";
//          if(arrLength == 1){
////                长度为1,且为全部范围
//              if("-1".equals(arr[0])){
//                  sqlQueryUser = "";
//              }else{
////                    长度为1,非全局租户
//                  sqlQueryUser =" " + "a.ENTERPRIZE_CODE" + "="  + arr[0];
//              }   
//          }else{
////                长度不为1,多个租户
//              for(int i = 0; i < arrLength; i++){
//                  sqlQueryUser += " " + "a.ENTERPRIZE_CODE"+" "+ "="  + arr[i]  + " " + "or" + "";
//              }
//              sqlQueryUser = sqlQueryUser.substring(0, sqlQueryUser.length()-3);
//          }
//          查询租户关联的用户
//          Map queryUserMap = new HashMap();
//          queryUserMap.put("sqlQueryUser", sqlQueryUser);
//          List allCustomerList = dao.query("SINT01.queryAllUser", queryUserMap);
////            取出所有用户名
//          int num = allCustomerList.size();
//          String[] customerName = new String[num];    
//          if(null!=allCustomerList && allCustomerList.size()>0){              
//              for(int k= 0; k < allCustomerList.size(); k++){
//                  customerName[k] = allCustomerList.get(k).getCustomerId();
//              }
//          }
            

            
//          有没有办法可以把几个数组快速的合并?
//          笨的方法for循环
//          int allUserIdLength = operatorMemberList.size() + operationMemberList.size() + allCustomerList.size();
//          String[] allUserId = new String[allUserIdLength];
//          for(int i = 0; i < allUserIdLength; i++){
//              if(i< operatorMemberList.size()){
//                  allUserId[i] = list1[i];
//              }else if( i < (operatorMemberList.size() + operationMemberList.size())){
//                  allUserId[i] = list2[i-operatorMemberList.size()];
//              }else{
//                  allUserId[i] = customerName[i-operatorMemberList.size() - operationMemberList.size()];
//              }
//          }
            
            
            // 调用模板消息的方法
            // 跳转链接
//          String detail_url = "http://xx.xx.xx.xx:8082/ecmp-portal-core/console/views/notice2.html?nid=31%26customerId=-1";
//          String contentStr = "{ \"first\": \"PSCS运行日报\",  \"keyword1\": \"2017-10-11 13:00:05\", \"keyword2\": \"宝钢采购供应链\", \"remark\": \"点击查看详情\" }";
//          String contentStr = "{ \"first\": \" + title + \",  \"keyword1\": \"+ publishTime +\", \"keyword2\": \"+ description +\", \"remark\": \"点击查看详情\" }";
//          String[] userId = {"sdsds"};
//          try {
//              sendTemplateToWx(userId, "aAyqAAbYLKkeMbiQC3W1LlGB8ginYPijn9sgl0Uu3IQ",detail_url,
//                      contentStr);
//              // ("community", user_id,
//              // "UH75k_NvJ2GXkpj8NLdQ0JE2ahD_bm6hYCIEcMxwE1E",
//              // toHashMap(contentStr));
//          } catch (Exception e) {
//              // TODO Auto-generated catch block
//              e.printStackTrace();
//          }

                                
        }                       
            
    }
    

  • xml中的sql语句

    

注意:
使用java字符串拼sql语句的时候,如果传递的参数可以空的时候,给参数设置为 "",这样它进不到中,之前我写的是让他等于 1=1,虽然也没有问题,建议使用第一种写法;

select * from TIAEM02 a  where 1=1
select * from TIAEM02 a 
where 1=1    AND   1=1
// 这个dbVisualizer执行是错误的,实际上如果传递的参数为空,是不会进到中的,实际上是没有AND  a.ENTERPRIZE_CODE = ""的

select * from TIAEM02 a 
where 1=1    AND  a.ENTERPRIZE_CODE = ""

... Physical database connection acquired for: ecmp_23
 22:27:26  [SELECT - 0 row(s), 0.000 secs]  [Error Code: 1741, SQL State: 42000]  ORA-01741: illegal zero-length identifier
... 1 statement(s) executed, 0 row(s) affected, exec/fetch time: 0.000/0.000 sec  [0 successful, 0 warnings, 1 errors]

你可能感兴趣的:(微信发送模板消息)