java小程序发送模板消息

小程序:

wxml:

 <form bind:submit="testSubmit" report-submit="true">
      <button formType="submit" class='modelButton'>发送模板消息</button>
 </form>

wxss:

.modelButton{
    margin-top:50%;
    width: 50%;
}

js前端发送模板消息:

注意:每个小程序的openid都是不一样的,这里使用的是我的小程序的openid,应替换为自己小程序的openid。

关于解密openid参考我的另一篇博客:https://blog.csdn.net/LONG_Yi_1994/article/details/82977603

    testSubmit: function(e) {
        console.log(e);
        var self = this;
        let method = 'GET';
        let openid = 'obk-W5Fq76sHfAnnC_8L_6xEew0M';
        let _access_token = '14_Z_mmRqZ8F0LSoYphxhXLcY1qYQbiArASnTyRChBQtKnWDL3co46eXwQsL8Qr58yZ01XmE6shkLGNGkz1zhX0zqPNNsXJlGljdLejCR_qerPP76H-4ZodZT4XTPqEAywHtNB_m-djIzoN3AyHZZJjAFASSC';
        let url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=' + _access_token;

        let _jsonData = {
            access_token: _access_token,
            touser: 'oK_7b4mGyt6L9DRXWINxjEeCb_no',
            template_id: 'PZ-QULr4atCAgBacoMjh09u0bAVA_St-lNCp5jV7Pcs',
            form_id: e.detail.formId,
            page: "pages/index/index",
            data: {
                "keyword1": {
                    "value": "测试数据一",
                    "color": "#173177"
                },
                "keyword2": {
                    "value": "测试数据二",
                    "color": "#173177"
                },
                "keyword3": {
                    "value": "测试数据三",
                    "color": "#173177"
                },
                "keyword4": {
                    "value": "测试数据四",
                    "color": "#173177"
                },
                "keyword5": {
                    "value": "测试数据五",
                    "color": "#173177"
                },
                "keyword6": {
                    "value": "测试数据六",
                    "color": "#173177"
                }
            }
        };

        wx.request({
            url: "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token="+_access_token,
            data: _jsonData,
            method: method,
            success: function(res) {
                console.log(res)
                wx.showToast({
                    title: '发送成功',
                })
            },
            fail: function(err) {
                console.log('request fail ', err);
            },
            complete: function(res) {
                console.log("request completed!");
            }

        })

    }

java代码后台发送模板消息:

后端发送模板消息需要获取前端表单提交的formid

controller:

    @GetMapping("/publishModelMessage")
    public String publishModelMessage(@RequestParam(required = false) String formId,@RequestParam(required = false) String openId,HttpServletResponse response){
        openId = "oK_7b4mGyt6L9DRXWINxjEeCb_no";
        Token token = CommonUtil.getToken("你的小程序appid","你的小程序密钥");
        System.out.println(token.getAccessToken());
        WxMssVo wxMssVo = new WxMssVo();
        wxMssVo.setTemplate_id("PZ-QULr4atCAgBacoMjh09u0bAVA_St-lNCp5jV7Pcs");
        wxMssVo.setTouser(openId);
        wxMssVo.setPage("pages/index/index");
        wxMssVo.setRequest_url("https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" + token.getAccessToken());
        wxMssVo.setForm_id(formId);
        List<TemplateData> list = new ArrayList<>();
        list.add(new TemplateData("通知","#ffffff"));
        list.add(new TemplateData("李银龙","#ffffff"));
        list.add(new TemplateData("发布成功","#ffffff"));
        list.add(new TemplateData(new Date().toString(),"#ffffff"));
        list.add(new TemplateData("日常加班","#ffffff"));
        list.add(new TemplateData("深圳市方寸科技服务有限公司","#ffffff"));
        wxMssVo.setParams(list);
        CommonUtil.sendTemplateMessage(wxMssVo);
        return null;
    }

工具类CommonUtil:

public class CommonUtil {    
    public final static String token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
//获取小程序token
    public static Token getToken(String appid, String appsecret) {
        Token token = null;
        String requestUrl = token_url.replace("APPID", appid).replace("APPSECRET", appsecret);
        // 发起GET请求获取凭证
        JSONObject jsonObject = httpsRequest(requestUrl, "GET", null);

        if (null != jsonObject) {
            try {
                token = new Token();
                token.setAccessToken(jsonObject.getString("access_token"));
                token.setExpiresIn(jsonObject.getInteger("expires_in"));
            } catch (JSONException e) {
                token = null;
                // 获取token失败
                log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInteger("errcode"), jsonObject.getString("errmsg"));
            }
        }
        return token;
    }
//发送模板消息
    public static String sendTemplateMessage(WxMssVo wxMssVo) {
        String info = "";
        try {
            //创建连接
            URL url = new URL(wxMssVo.getRequest_url());
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Content-Type", "utf-8");
            connection.connect();
            //POST请求
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            JSONObject obj = new JSONObject();

            obj.put("access_token", wxMssVo.getAccess_token());
            obj.put("touser", wxMssVo.getTouser());
            obj.put("template_id", wxMssVo.getTemplate_id());
            obj.put("form_id", wxMssVo.getForm_id());
            obj.put("page", wxMssVo.getPage());

            JSONObject jsonObject = new JSONObject();

            for (int i = 0; i < wxMssVo.getParams().size(); i++) {
                JSONObject dataInfo = new JSONObject();
                dataInfo.put("value", wxMssVo.getParams().get(i).getValue());
                dataInfo.put("color", wxMssVo.getParams().get(i).getColor());
                jsonObject.put("keyword" + (i + 1), dataInfo);
            }

            obj.put("data", jsonObject);
            out.write(obj.toString().getBytes());
            out.flush();
            out.close();

            //读取响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String lines;
            StringBuffer sb = new StringBuffer("");
            while ((lines = reader.readLine()) != null) {
                lines = new String(lines.getBytes(), "utf-8");
                sb.append(lines);
            }
            info = sb.toString();
            System.out.println(sb);
            reader.close();
            // 断开连接
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return info;
    }

    /**
     * 发送 https 请求
     * 
     * @param requestUrl 请求地址
     * @param requestMethod 请求方式(GET、POST)
     * @param outputStr 提交的数据
     * @return JSONObject(通过 JSONObject.get(key) 的方式获取 JSON 对象的属性值)
     */
    public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
        
        JSONObject jsonObject = null;
        
        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 conn = (HttpsURLConnection) url.openConnection();
            conn.setSSLSocketFactory(ssf);
            
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            
            // 设置请求方式(GET/POST)
            conn.setRequestMethod(requestMethod);
            
            // 当 outputStr 不为 null 时,向输出流写数据
            if (null != outputStr) {
                OutputStream outputStream = conn.getOutputStream();
                
                // 注意编码格式
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }
            
            // 从输入流读取返回内容
            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            
            // 释放资源
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            conn.disconnect();
            jsonObject = JSONObject.parseObject(buffer.toString());
        } catch (ConnectException ce) {
            log.error(" 连接超时:{}", ce);
        } catch (Exception e) {
            log.error("https 请求异常:{}", e);
        }
        
        return jsonObject;
    }


}

Token类:

public class Token {
    //接口访问凭证
    private String accessToken;
    //接口有效期,单位:秒
    private int expiresIn;
    
    public String getAccessToken() {
        return accessToken;
    }
    public void setAccessToken(String accessToken) {
        this.accessToken = accessToken;
    }
    public int getExpiresIn() {
        return expiresIn;
    }
    public void setExpiresIn(int expiresIn) {
        this.expiresIn = expiresIn;
    }
}

模板消息请求参数封装类WxMssVo :

public class WxMssVo {
   private String touser;
   private String template_id;
   private String page;
   private String form_id;
   private String access_token;
   private String request_url;
   private List<TemplateData> params = new ArrayList<>();
}

模板消息详细参数封装TemplateData :

public class TemplateData {
    private String key;
    private String value;
    private String color;

    public TemplateData(String value, String color) {
        this.value = value;
        this.color = color;
    }
}

关注公众号:小诸葛的博客 回复091可获取项目源码

 

评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值