微信公众号发送模板消息
1.创建模板,拿到模板ID
2.创建发送消息工具类
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Component
public class WeixinUtil {
private static Logger logger = LoggerFactory.getLogger(WeixinUtil.class);
private static final String WEIXIN_PREFIX = "https://api.weixin.qq.com/cgi-bin";
@Value("${wx.appID}")
private String appID;
@Value("${wx.secret}")
private String secret;
@Value("${wx.domainName}")
private String domainName;
private static String PARAM_ACCESS_TOKEN = "";
private static long TOKEN_START = 0;
private static int expiresIn = 7200;
/**
* 做一个缓存的access_token
*/
private String getAccessToken() {
if (TOKEN_START == 0) {
PARAM_ACCESS_TOKEN = getNormalAccessToken();
TOKEN_START = System.currentTimeMillis();
} else if (System.currentTimeMillis() - TOKEN_START > expiresIn) {
PARAM_ACCESS_TOKEN = getNormalAccessToken();
TOKEN_START = System.currentTimeMillis();
}
return PARAM_ACCESS_TOKEN;
}
/**
* 发送信息
*
* @param params
*/
private void sendInfo(String params) {
String url = WEIXIN_PREFIX + "/message/template/send?access_token=" + getAccessToken();
String result = HttpUtil.post(url, params);
logger.info(">>>发送消息:" + result);
System.out.println(">>>发送消息:" + result);
}
private static String getNormalAccessTokenURL() {
return WEIXIN_PREFIX + "/token";
}
/**
* 获取普通的AccessToken
*/
private String getNormalAccessToken() {
Map<String, Object> map = new HashMap<>();
map.put("grant_type", "client_credential");
map.put("appid", appID);
map.put("secret", secret);
String result = HttpUtil.get(getNormalAccessTokenURL(), map);
if (result != null) {
JSONObject jsonObject = JSONObject.parseObject(result);
PARAM_ACCESS_TOKEN = jsonObject.getString("access_token");
expiresIn = jsonObject.getInteger("expires_in");
}
return PARAM_ACCESS_TOKEN;
}
public void sendMessage(String toUser, String templateID, String subURL, String first,
List<String> keywordList, String remark) {
MessageEntity messageEntity = new MessageEntity();
messageEntity.setTouser(toUser);
messageEntity.setTemplate_id(templateID);
messageEntity.setUrl(domainName + subURL);
messageEntity.setData(getMapData(first, keywordList, remark));
sendInfo(messageEntity.toString());
}
private static Map<String, Map<String, String>> getMapData(String f1, List<String> keywordList, String rmk) {
Map<String, Map<String, String>> data = new HashMap<>(5);
Map<String, String> first = new HashMap<>(2);
first.put("color", "#173177");
first.put("value", f1);
for (int i = 1; i <= keywordList.size(); i++) {
Map<String, String> subMap = new HashMap<>(2);
subMap.put("color", "#173177");
subMap.put("value", keywordList.get(i - 1));
data.put("keyword" + i, subMap);
}
Map<String, String> remark = new HashMap<>(2);
remark.put("color", "#173177");
remark.put("value", rmk);
data.put("first", first);
data.put("remark", remark);
return data;
}
/**
* 获取关注当前公共号人数,还可以获取光柱公众号的openid列表
*
* @return
*/
public int getConcernedPeople() {
String url = WEIXIN_PREFIX + "/user/get?access_token=" + getAccessToken();
try {
String result = HttpUtil.get(url);
if (result != null) {
JSONObject jsonObject = JSONObject.parseObject(result);
return (int) jsonObject.get("total");
}
} catch (Exception e) {
logger.error(e.getMessage());
return 0;
}
return 0;
}
}
/**
* 消息的发送需要json格式
*/
class MessageEntity {
private String touser;
private String template_id;
private String url;
private Map<String, Map<String, String>> data;
public String getTouser() {
return touser;
}
public void setTouser(String touser) {
this.touser = touser;
}
public String getTemplate_id() {
return template_id;
}
public void setTemplate_id(String template_id) {
this.template_id = template_id;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Map<String, Map<String, String>> getData() {
return data;
}
public void setData(Map<String, Map<String, String>> data) {
this.data = data;
}
@Override
public String toString() {
return JSONObject.toJSONString(this);
}
}
在springboot中可以直接使用。其中appID和secret是微信公众号基础信息,domainName是网站域名(如果域名修改便于改动,也利于测试和生成环境部署)
用户点击消息查看详情,如果网址是http://www.xxx.com/a/p/123.html,这时候domainName就可以设置为http://www.xxx.com,如果后期域名改动或者测试生成环境切换,都可以通过配置文件进行修改,比较简单方便。
3.构建发送的信息并发送
// 微信通知:先获取WeixinUtil对象,然后组织发送消息的信息
String openid="openid";
String templateID="templateID";
String subURL = "/wx.html/p/detail?id=109&number=1591953944402";
String first = "您的请假已被驳回";
String remark = "备注消息";
List<String> keywordList = new ArrayList<>(2);
keywordList.add("已驳回");
keywordList.add("请假时间过长");
weixinUtil.sendMessage(openid, templateID, subURL, first, keywordList, remark);