springboot实现微信模板消息推送

在上一篇文章我们已经知道了怎么获取openid

还不知道的可以查看我的上一篇文章springboot+微信小程序用codeid换取openid

这次我们不光要准备AppID(小程序ID)和AppSecret(小程序密钥)

还需要准备模板消息的id

(*如果没有模板消息这个功能,可能是你没有开通,自己开通一下就好)

springboot定时发送企业微信 springboot发送微信消息_json


我们随便添加一个模板就行,我们需要这个模板ID,然后我们查看一下详情看一下模板消息的格式

springboot定时发送企业微信 springboot发送微信消息_json_02


很明显是json格式准备好了就开始写后台了

1.新建一个springboot项目

2.controller类

springboot定时发送企业微信 springboot发送微信消息_json_03


我们需要传入2个参数:openid和formid

先要换取token!

然后拼接模板消息的内容

springboot定时发送企业微信 springboot发送微信消息_springboot实现微信模板消息推送_04


最后统一进行推送

springboot定时发送企业微信 springboot发送微信消息_json_05


3.推送工具类

public static boolean setPush(String params, String accessToken) {
        boolean flag = false;
        String url = PUSH_URL + accessToken;
        OutputStream outputStream = null;
        InputStreamReader inputStreamReader = null;
        InputStream inputStream = null;
        BufferedReader bufferedReader = null;
        HttpsURLConnection connection = null;
        try {
            // 创建URL对象
            URL realUrl = new URL(url);
            // 打开连接 获取连接对象
            connection = (HttpsURLConnection) realUrl.openConnection();
            // 设置请求编码
            connection.addRequestProperty("encoding", "UTF-8");
            // 设置允许输入
            connection.setDoInput(true);
            // 设置允许输出
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
            // 当outputStr不为null时向输出流写数据
            if (null != params) {
                outputStream = connection.getOutputStream();
                // 注意编码格式
                outputStream.write(params.getBytes("UTF-8"));
                outputStream.close();
            }
            // 从输入流读取返回内容
            inputStream = connection.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            JSONObject jsonObject = JSONObject.parseObject(buffer.toString());
            int errorCode = jsonObject.getInteger("errcode");
            String errorMessage = jsonObject.getString("errmsg");
            if (errorCode == 0) {
                flag = true;
            } else {
                logger.info("模板消息发送失败:" + errorCode + "," + errorMessage);
                flag = false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 依次关闭打开的输入流
            try {
                connection.disconnect();
                bufferedReader.close();
                inputStreamReader.close();
                inputStream.close();
                // 依次关闭打开的输出流
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return flag;
    }

4.获取token工具类

public static JSONObject getAccessToken() {
        String url = ACCESS_TOKEN_URL + "appid=" + APP_ID + "&secret=" + SECRET;
        PrintWriter out = null;
        BufferedReader in = null;
        String line;
        StringBuffer sb = new StringBuffer();
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();

            // 设置通用的请求属性 设置请求格式
            //设置返回类型
            conn.setRequestProperty("contentType", "text/plain");
            //设置请求类型
            conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
            //设置超时时间
            conn.setConnectTimeout(1000);
            conn.setReadTimeout(1000);
            conn.setDoOutput(true);
            conn.connect();
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应    设置接收格式
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), "UTF-8"));
            while ((line = in.readLine()) != null) {
                sb.append(line);
            }
            // 将获得的String对象转为JSON格式
            JSONObject jsonObject = JSONObject.parseObject(sb.toString());
            return jsonObject;
        } catch (Exception e) {
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return null;
    }

微信端

index.wxml文件添加如下:

springboot定时发送企业微信 springboot发送微信消息_springboot定时发送企业微信_06


index.js添加如下

springboot定时发送企业微信 springboot发送微信消息_json_07


这里的openid是根据上篇文章请求成功后返回给前端的。

这样我们就算写完了。

*要想获取formid就必须在真机上才行,也不能是localhost来请求!

我们可以进行真机调试

springboot定时发送企业微信 springboot发送微信消息_输出流_08

运行结果图:

springboot定时发送企业微信 springboot发送微信消息_springboot定时发送企业微信_09


springboot定时发送企业微信 springboot发送微信消息_输出流_10


springboot定时发送企业微信 springboot发送微信消息_springboot定时发送企业微信_11

好了大功告成,你还在等什么赶快动手试一下吧!

觉得不错的可以关注支持一下!!!!!!!

最后附赠完整源码demo

博客地址

博客地址

码云代码地址

代码地址