代码实现
/**
* @description: 微信公众号模板消息推送
* @param: publicOpenId 微信公众号用户标识
* publicTemplateId 消息模板id
* dataMap 消息模板数据
*/
public static AjaxResult sendPublicMessage(String publicOpenId, String publicTemplateId, JSONObject data) {
log.info("开始推送消息");
String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + publicAppId + "&secret=" + publicSecret;//注意公众号和小程序区分
try (Response responseAccessToken = OkHttpUtil.get(accessTokenUrl)) {
if (responseAccessToken.isSuccessful()) {
JSONObject resData = JSON.parseObject(responseAccessToken.body().string());
Integer errcode = resData.getInteger("errcode");
if (errcode == null || errcode == 0) {
String access_token = resData.getString("access_token");
log.info("授权token:{}",access_token);
String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token;
JSONObject jsonObject = new JSONObject();
jsonObject.put("touser",publicOpenId); // 必须是公众号的openid注意和小程序的openid区分
jsonObject.put("template_id", publicTemplateId);
jsonObject.put("data", data);
log.info("发送参数:{}",jsonObject);
Response response = OkHttpUtil.postJson(url, null, jsonObject.toJSONString());
if (response.isSuccessful()) {
String param = response.body().string();
log.info("消息发送结果:{}", param);
}
}
}
} catch (Exception ignored) {
}
return AjaxResult.error();
}
官方文档地址:模板消息 | 微信开放文档
微信官方接口调试工具:微信公众平台接口调试工具