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 param = new HashMap();
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 map) throws Exception {
if (map != null) {
StringBuilder param = new StringBuilder("?");
for (Map.Entry 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 map) {
if (map != null) {
Iterator> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry 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 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 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的获取在用户绑定公众号的时候能够获取得到