微信发送模版消息

1.微信官方文档:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140183

2.根据文档获取access_token

 public String getAccessToken() {
        String accessToken = redisOperateUtil.get("key");//将token放入redis中
        if (accessToken != null) {
            return accessToken;
        } else {
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("grant_type", "client_credential");
            param.put("appid", appid);//第三方用户唯一凭证
            param.put("secret", secret);//第三方用户唯一凭证密钥
            String result = "";
            try {
                result = UrlUtil.openUrl("https://api.weixin.qq.com/cgi-bin/token", param);//发送一个get请求
            } catch (Exception e) {
                LOGGER.error("获取accessToken失败", e);
            }
            if (!Strings.isNullOrEmpty(result)) {
                JSONObject jsonObject = JSONObject.parseObject(result);
                accessToken = jsonObject.getString("access_token");
                if (!Strings.isNullOrEmpty(accessToken)) {
                    redisOperateUtil.setValueAndLifeCycle("key", 1000, accessToken);//accesstoken的有效时间是2个小时
                } else {
                    LOGGER.warn("accessToken获取url返回空串");
                }
                return Strings.nullToEmpty(accessToken);
            }
            return "";
        }

    }
3.发送get以及post请求的工具类
public class UrlUtil {
    public static String openUrl(String urlStr, Map<String, Object> map) throws Exception {
        if (map != null) {
            StringBuilder param = new StringBuilder("?");
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                if (RegexUtil.isContainsChinese(entry.getKey() + "")) {
                    param.append(entry.getKey()).append("=").append(URLEncoder.encode((String) entry.getValue(), "UTF-8")).append("&");
                } else {
                    param.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
                }
            }
            urlStr = urlStr + param.substring(0, param.length() - 1);
        }
        URL url = new URL(urlStr);
        URLConnection connection = url.openConnection();
        connection.setReadTimeout(20 * 1000);
        connection.setConnectTimeout(20 * 1000);
        InputStream in = connection.getInputStream();
        ByteArrayOutputStream outstream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = -1;
        while ((len = in.read(buffer)) != -1) {
            outstream.write(buffer, 0, len);
        }
        String result = new String(outstream.toByteArray(), "utf-8");
        outstream.close();
        return result;
    }


    public static void decodeMap(Map<String, Object> map) {
        if (map != null) {
            Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, Object> e = it.next();
                try {
                    if (e.getValue() != null) {
                        map.put(e.getKey(), URLDecoder.decode(e.getValue().toString(), "utf-8"));
                    }
                } catch (UnsupportedEncodingException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

    public static String getRemoteData(String url, String param, String encoding)
            throws Exception, IOException {
        System.out.println(url);
        HttpURLConnection con = (HttpURLConnection) new URL(url)
                .openConnection();
        con.setConnectTimeout(10000);
        con.setRequestMethod("POST");
        con.setDoOutput(true);
        con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        byte[] entity = param.getBytes("UTF-8");
        con.setRequestProperty("Content-Length", String.valueOf(entity.length));// entity为要传输的数据格式为
        // title=hello&time=20//可以对该数据编码
        OutputStream outStream = con.getOutputStream();
        outStream.write(entity);
        BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(), encoding));
        String line = null;
        StringBuffer sb = new StringBuffer();
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        reader.close();
        con.disconnect();
        return sb.toString();
    }

   
}
public class RegexUtil {
    public static boolean isContainsChinese(String str)
    {
        Pattern pat = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher matcher = pat.matcher(str);
        boolean flg = false;
        if (matcher.find())    {
            flg = true;
        }
        return flg;
    }
}

4.发送模版消息:根据官方文档发送到接口

https://api.weixin.qq.com/cgi-bin/message/template/send,需要的参数,并且access_token是必须的

参数是否必填说明
touser接收者openid
template_id模板ID
url模板跳转链接
miniprogram跳小程序所需数据,不需跳小程序可不用传该数据
appid所需跳转到的小程序appid(该小程序appid必须与发模板消息的公众号是绑定关联关系)
pagepath所需跳转到小程序的具体页面路径,支持带参数,(示例index?foo=bar)
data模板数据
color模板内容字体颜色,不填默认为黑色
 private JSONObject postMsg(Map<String, String> param) throws Exception {
        String access_token= getAccessToken();
        String body;
        String lang = (String) (param.get("lang") != null ? param.get("lang") : "zh_CN");
        if (Strings.isNullOrEmpty(param.get("body"))) {
            throw new IllegalArgumentException("body不能为空");
        } else {
            body = param.get("body");
        }
        String result = UrlUtil.getRemoteData("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token, body, "UTF-8");
//        System.out.println(result);
        return JSON.parseObject(result);
    }

    public void sendBindSuccessMsg(String userName,String toOpenId,String userTypeDesc) {
        Map<String, String> requestMap = new HashMap<>();
        requestMap.put("body","{\"touser\":\""+toOpenId+"\"," +
                "\"template_id\":\"××××\"," +
                "\"url\":\"××××"," +
                "\"topcolor\": \"#FF0000\","+
                "\"data\":{\"first\":{\"value\":\""+userName+",您好,您已成功×××\",\"color\":\"#173177\"}," +
                "\"keyword1\":{\"value\":\""+userName+"\",\"color\":\"#173177\"}," +
                "\"keyword2\":{\"value\":\""+userTypeDesc+"\",\"color\":\"#173177\"}," +
                "\"keyword3\":{\"value\":\""+ DateUtils.getDateTimeFormatString(new Date())+"\",\"color\":\"#173177\"}," +
                "\"remark\":{\"value\":\"感谢您的使用,如有疑问,请联系客服人员,点击查看详情进入首页吧\",\"color\":\"#173177\"}}}");
        JSONObject jsonObject= JSONObject.parseObject(requestMap.get("body"));
        try {
            postMsg(requestMap);
        } catch (Exception e) {
            logger.error("推送出错的json数据:{}",jsonObject);
            logger.error("推送消息出错",e);
        }
    }
5.注意事项:模版id是需要申请的,用户的openid的获取在用户绑定公众号的时候能够获取得到





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值