欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

微信模板消息开发总结——7.26

程序员文章站 2024-03-15 14:32:41
...

需求:A管理员在微信端提交用户加入群组,给B高级管理员审核。

           B管理员审核成功后,微信公众号会发送一个消息给A管理员,提示新增成功。

微信后台模板消息接口:

微信模板消息开发总结——7.26

 

官方文档:

        请求需要三个参数——

        touser:用户的微信openId

        template_id:模板消息id

        topcolor:字体颜色

        data:替换模板消息内的具体数据

微信模板消息开发总结——7.26

代码——

接口端:

            …………

            String openId = null;
            String userName = null;
            if (jsonObject.containsKey("flag") && jsonObject.getInteger("flag") == 1) {
                // 获得提交人的信息
                User user = mbUserService.searchOpenIdById(id);
                if (user == null) {
                    logger.error("系统错误");
                } else {
                    // 得到提交人的openid 用户名
                    openId = user.getOpenId();
                    userName = user.getUserName();
                }
                // 审核成功之后,发送模板消息
                Template tem = new Template();
                tem.setTemplateId("E1P3fwW5GGSFdGraAuOjcVy-6xRNC2c78LKslYoumxk");
                tem.setTopColor("#00DD00");
                tem.setToUser(openId);
                // 模板消息具体url,没找到
                tem.setUrl("");
                List<TemplateParam> paras = new ArrayList<TemplateParam>();
                paras.add(new TemplateParam("OperaUser", userName, "#0044BB"));
                paras.add(new TemplateParam("UserTel", phone, "#0044BB"));
                paras.add(new TemplateParam("Group", "出租车司机", "#0044BB"));
                paras.add(new TemplateParam("Status", "成功", "#0044BB"));
                tem.setTemplateParamList(paras);
                // 获取accessToken
                String token = null;
                try {
                    token = WeiXinUtil.getAccessToken().getToken();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                // 调用发送消息
                boolean result = sendTemplateMsg(token, tem);
                logger.info("模板消息发送结果:" + result);

工具类:



public class WeiXinUtil {
    
    @Value("${wx.appId}")
    private static String APPID;
    
    @Value("${wx.appsecret}")
    private static String APPSECRET;
    
    // 从微信后台拿到APPID和APPSECRET 并封装为常量
    // private static final String APPID = "wx93ee9c70c625f281";
    // private static final String APPSECRET = "93e787d23e2e1e5c45d1c7f5cdc6fe79";
    private static final String ACCESS_TOKEN_URL =
        "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
    
    /**
     * 编写Get请求的方法。但没有参数传递的时候,可以使用Get请求
     * 
     * @param url 需要请求的URL
     * @return 将请求URL后返回的数据,转为JSON格式,并return
     */
    public static JSONObject doGetStr(String url) throws ClientProtocolException, IOException {
        DefaultHttpClient client = new DefaultHttpClient();// 获取DefaultHttpClient请求
        HttpGet httpGet = new HttpGet(url);// HttpGet将使用Get方式发送请求URL
        JSONObject jsonObject = null;
        HttpResponse response = client.execute(httpGet);// 使用HttpResponse接收client执行httpGet的结果
        HttpEntity entity = response.getEntity();// 从response中获取结果,类型为HttpEntity
        if (entity != null) {
            String result = EntityUtils.toString(entity, "UTF-8");// HttpEntity转为字符串类型
            jsonObject = JSONObject.parseObject(result);// 字符串类型转为JSON类型
        }
        return jsonObject;
    }
    
    /**
     * 编写Post请求的方法。当我们需要参数传递的时候,可以使用Post请求
     * 
     * @param url 需要请求的URL
     * @param outStr 需要传递的参数
     * @return 将请求URL后返回的数据,转为JSON格式,并return
     */
    public static JSONObject doPostStr(String url, String outStr) throws ClientProtocolException, IOException {
        DefaultHttpClient client = new DefaultHttpClient();// 获取DefaultHttpClient请求
        HttpPost httpost = new HttpPost(url);// HttpPost将使用Get方式发送请求URL
        JSONObject jsonObject = null;
        httpost.setEntity(new StringEntity(outStr, "UTF-8"));// 使用setEntity方法,将我们传进来的参数放入请求中
        HttpResponse response = client.execute(httpost);// 使用HttpResponse接收client执行httpost的结果
        String result = EntityUtils.toString(response.getEntity(), "UTF-8");// HttpEntity转为字符串类型
        jsonObject = JSONObject.parseObject(result);// 字符串类型转为JSON类型
        return jsonObject;
    }
    
    /**
     * 获取AccessToken
     * 
     * @return 返回拿到的access_token及有效期
     */
    public static AccessToken getAccessToken() throws ClientProtocolException, IOException {
        AccessToken token = new AccessToken();
        String url = ACCESS_TOKEN_URL.replace("APPID", APPID).replace("APPSECRET", APPSECRET);// 将URL中的两个参数替换掉
        JSONObject jsonObject = doGetStr(url);// 使用刚刚写的doGet方法接收结果
        if (jsonObject != null) { // 如果返回不为空,将返回结果封装进AccessToken实体类
            token.setToken(jsonObject.getString("access_token"));// 取出access_token
            token.setExpireIn(jsonObject.getInteger("expires_in"));// 取出access_token的有效期
        }
        return token;
    }
}

发送模板消息调用方法:

 // 发送模板消息
    public static boolean sendTemplateMsg(String token, Template template) {
        
        boolean flag = false;
        
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
        requestUrl = requestUrl.replace("ACCESS_TOKEN", token);
        
        JSONObject jsonResult = CommonUtil.httpsRequest(requestUrl, "POST", template.toJSON());
        if (jsonResult != null) {
            int errorCode = jsonResult.getInteger("errcode");
            String errorMessage = jsonResult.getString("errmsg");
            if (errorCode == 0) {
                flag = true;
            } else {
                System.out.println("模板消息发送失败:" + errorCode + "," + errorMessage);
                flag = false;
            }
        }
        return flag;
    }

发送消息时需要的CommonUtil


 
public class CommonUtil {
	
	public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) { 
		
        JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();  
        try {  
            // 创建SSLContext对象,并使用我们指定的信任管理器初始化  
            TrustManager[] tm = { new MyX509TrustManager() };  
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");  
            sslContext.init(null, tm, new java.security.SecureRandom());  
            // 从上述SSLContext对象中得到SSLSocketFactory对象  
            SSLSocketFactory ssf = sslContext.getSocketFactory();  
  
            URL url = new URL(requestUrl);  
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();  
            httpUrlConn.setSSLSocketFactory(ssf);  
  
            httpUrlConn.setDoOutput(true);  
            httpUrlConn.setDoInput(true);  
            httpUrlConn.setUseCaches(false);  
            // 设置请求方式(GET/POST)  
            httpUrlConn.setRequestMethod(requestMethod);  
  
            if ("GET".equalsIgnoreCase(requestMethod)) {
            	 httpUrlConn.connect();  
            } 
               
  
            // 当有数据需要提交时  
            if (null != outputStr) {  
                OutputStream outputStream = httpUrlConn.getOutputStream();  
                // 注意编码格式,防止中文乱码  
                outputStream.write(outputStr.getBytes("UTF-8"));  
                outputStream.close();  
            }  
  
            // 将返回的输入流转换成字符串  
            InputStream inputStream = httpUrlConn.getInputStream();  
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");  
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);  
  
            String str = null;  
            while ((str = bufferedReader.readLine()) != null) {  
                buffer.append(str);  
            }  
            bufferedReader.close();  
            inputStreamReader.close();  
            // 释放资源  
            inputStream.close();  
            inputStream = null;  
            httpUrlConn.disconnect();  
            jsonObject = JSONObject.parseObject(buffer.toString());  
        } catch (ConnectException ce) {  
            ce.printStackTrace();
        } catch (Exception e) {  
            e.printStackTrace();
        }  
        return jsonObject;  
    }
	
    public static String httpRequest(String requestUrl, String requestMethod, String outputStr) { 
		
        
        StringBuffer buffer = new StringBuffer();  
        try {  
          
  
            URL url = new URL(requestUrl);  
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();  
           
  
            httpUrlConn.setDoOutput(true);  
            httpUrlConn.setDoInput(true);  
            httpUrlConn.setUseCaches(false);  
            // 设置请求方式(GET/POST)  
            httpUrlConn.setRequestMethod(requestMethod);  
  
            if ("GET".equalsIgnoreCase(requestMethod)) {
            	 httpUrlConn.connect();  
            } 
               
  
            // 当有数据需要提交时  
            if (null != outputStr) {  
                OutputStream outputStream = httpUrlConn.getOutputStream();  
                // 注意编码格式,防止中文乱码  
                outputStream.write(outputStr.getBytes("UTF-8"));  
                outputStream.close();  
            }  
  
            // 将返回的输入流转换成字符串  
            InputStream inputStream = httpUrlConn.getInputStream();  
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");  
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);  
  
            String str = null;  
            while ((str = bufferedReader.readLine()) != null) {  
                buffer.append(str);  
            }  
            bufferedReader.close();  
            inputStreamReader.close();  
            // 释放资源  
            inputStream.close();  
            inputStream = null;  
            httpUrlConn.disconnect();  
            //jsonObject = JSONObject.fromObject(buffer.toString());  
        } catch (ConnectException ce) {  
            ce.printStackTrace();
        } catch (Exception e) {  
            e.printStackTrace();
        }  
        return buffer.toString();  
    }
	public static String urlEncodeUTF8(String source){
		String result = source;
		try {
			result = java.net.URLEncoder.encode(source,"utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return result;
	}
	
    public static String httpsRequestForStr(String requestUrl, String requestMethod, String outputStr) { 
		
        String result="";
        StringBuffer buffer = new StringBuffer();  
        try {
            // 创建SSLContext对象,并使用我们指定的信任管理器初始化  
            TrustManager[] tm = { new MyX509TrustManager() };  
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");  
            sslContext.init(null, tm, new java.security.SecureRandom());  
            // 从上述SSLContext对象中得到SSLSocketFactory对象  
            SSLSocketFactory ssf = sslContext.getSocketFactory();  
  
            URL url = new URL(requestUrl);  
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();  
            httpUrlConn.setSSLSocketFactory(ssf);  
  
            httpUrlConn.setDoOutput(true);  
            httpUrlConn.setDoInput(true);  
            httpUrlConn.setUseCaches(false);  
            // 设置请求方式(GET/POST)  
            httpUrlConn.setRequestMethod(requestMethod);  
  
            if ("GET".equalsIgnoreCase(requestMethod)) {
            	 httpUrlConn.connect();  
            } 
               
  
            // 当有数据需要提交时  
            if (null != outputStr) {  
                OutputStream outputStream = httpUrlConn.getOutputStream();  
                // 注意编码格式,防止中文乱码  
                outputStream.write(outputStr.getBytes("UTF-8"));  
                outputStream.close();  
            }  
  
            // 将返回的输入流转换成字符串  
            InputStream inputStream = httpUrlConn.getInputStream();  
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");  
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);  
  
            String str = null;  
            while ((str = bufferedReader.readLine()) != null) {  
                buffer.append(str);  
            }  
            bufferedReader.close();  
            inputStreamReader.close();  
            // 释放资源  
            inputStream.close();  
            inputStream = null;  
            httpUrlConn.disconnect();  
            result=buffer.toString();  
        } catch (ConnectException ce) {  
            ce.printStackTrace();
        } catch (Exception e) {  
            e.printStackTrace();
        }  
        return result;  
    }
}

 


                                                          一入开发深似海,心怀大佬梦,管它高几重                                                                                     

                                                          时时当警醒,不做负心人

相关标签: 模板消息 微信