微信公众号模板消息文档
微信公众号测试号管理平台
关键信息
:appid,appsecret,templateId,openid可根据个人的需要自定义微信消息模板
模板消息接口文档
模板消息调用时主要需要模板ID和模板中各参数的赋值内容。请注意:
1. 模板中参数内容必须以".DATA"结尾,否则视为保留字;
2. 模板保留符号"{{ }}"
发送模板消息时,发送的是POST请求,链接为:
https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN;
请求包是一个json:
"touser":"OPENID",
"template_id":"ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY",
"url":"http://weixin.qq.com/download",
"topcolor":"#FF0000",
"data":"JSON字符串",
定义微信消息模板实体类:
/**
* 微信消息模板
*
* @author : HP
* @date : 2022/8/22
*/
public class WxTemplateMessage implements Serializable {
private static final long serialVersionUID = 522516428719928671L;
/**
* 接收者openId
*/
private String touser;
/**
* 模板id
*/
private String template_id;
/**
* 模板跳转链接
*/
private String url;
/**
* 消息头颜色
*/
private String topcolor;
/**
* 消息data
*/
private TreeMap<String, TreeMap<String, String>> data;
public static TreeMap<String, String> item(String value, String color) {
TreeMap<String, String> params = new TreeMap<>();
params.put("value", value);
params.put("color", color);
return params;
}
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 String getTopcolor() {
return topcolor;
}
public void setTopcolor(String topcolor) {
this.topcolor = topcolor;
}
public TreeMap<String, TreeMap<String, String>> getData() {
return data;
}
public void setData(TreeMap<String, TreeMap<String, String>> data) {
this.data = data;
}
}
/**
* 微信模板消息常量
*
* @author : HP
* @date : 2022/8/22
*/
public interface WxConstant {
/**
* wxAppID
*/
String WX_APPID = "wx1b96083a11590564";
/**
* wxAppsecret
*/
String WX_APPSECRET = "716393f3c83f41ec0e08bd4e33f989f0";
/**
* accessTokenUrl
*/
String WX_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";
/**
* sendMessageUrl
*/
String WX_SEND_MESSAGE_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=";
}
/**
* get请求
*
* @param url 目标url
* @return result
*/
public static String get(String url) {
try {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("Content-Type", "application/json;charset=UTF-8");
httpGet.setHeader("Accept", "application/json");
// 连接主机服务超时时间
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10000)
// 请求超时时间
.setConnectionRequestTimeout(10000)
// 数据读取超时时间
.setSocketTimeout(10000)
.build();
httpGet.setConfig(requestConfig);
CloseableHttpResponse response = httpClient.execute(httpGet);
String resStr = null;
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
if (entity != null) {
resStr = EntityUtils.toString(entity, "UTF-8");
}
log.info("get调用返回:" + resStr);
httpClient.close();
response.close();
}
return resStr;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* post请求
*
* @param url 目标url
* @param jsonstr 请求参数
* @return result
*/
public static String httpPost(String url,String jsonstr){
// post请求返回结果
String response = null;
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost method = new HttpPost(url);
try {
if (null != jsonstr && !"".equals(jsonstr)) {
//解决中文乱码问题
StringEntity entity = new StringEntity(jsonstr, "utf-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
method.setEntity(entity);
}
HttpResponse result = httpClient.execute(method);
url = URLDecoder.decode(url, "UTF-8");
if (result != null) {
int statusCode = result.getStatusLine().getStatusCode();
if (statusCode == 200) {
HttpEntity httpEntity = result.getEntity();
if (httpEntity != null) {
response = EntityUtils.toString(httpEntity, "UTF-8");
return response;
}
} else {
return "" + statusCode;
}
}
} catch (Exception e) {
log.info("post请求提交失败:" + url, e);
}
return response;
}
获取Access_Token开发文档
接口调用地址:
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
https请求方式: GET
请求参数:
正常情况返回参数:{"access_token":"ACCESS_TOKEN","expires_in":7200}
异常情况返回参数:{"errcode":40013,"errmsg":"invalid appid"}
private String getWxAccessToken(String appid, String appSecret) {
String accessTokenUrl = WxConstant.WX_ACCESS_TOKEN_URL;
String url = String.format("%s?grant_type=client_credential&appid=%s&secret=%s", accessTokenUrl, appid, appSecret);
String result = HttpUtils.get(url);
JSONObject jsonObject = JSON.parseObject(result);
String accessToken = jsonObject.getString("access_token");
// TODO: 2022/8/22 redis缓存-将access_token保存在redis,不用重复请求
return accessToken;
}
public String sendTemplateMessage(String data) {
// 获取Access_token
String wxAccessToken = "";
// TODO: 2022/8/22 redis 缓存- 如果redis里面有则从redis获取
String appSecret = WxConstant.WX_APPSECRET;
String appid = WxConstant.WX_APPID;
// 获取Access_Token
wxAccessToken = getWxAccessToken(appid, appSecret);
String requestUrl = WxConstant.WX_SEND_MESSAGE_URL + wxAccessToken;
String result = HttpUtils.httpPost(requestUrl, data);
return result;
}
7.1 定义的微信消息模板:
工作任务提醒
{{first.DATA}}
员工名称:{{keyword1.DATA}}
提醒时间:{{keyword2.DATA}}
任务内容:{{keyword3.DATA}}
{{remark.DATA}}
7.2 编写Controller
/**
* @author : HP
* @date : 2022/8/22
*/
@RestController
@RequestMapping("/wxThird")
@Slf4j
public class WxThirdController {
@Autowired
private IWxThirdService wxThirdService;
@PostMapping("/sendWxMessage")
public BaseResponse<?> sendWxMessage() {
// 模板id
String templateId = "xxxxxxxxx";
// 发送的目标用户
String touser = "xxxxxxxxx";
// 要跳转的url
String url = "https://www.baidu.com";
// 模板消息内容
WxTemplateMessage message = new WxTemplateMessage();
message.setTouser(touser);
message.setTemplate_id(templateId);
message.setUrl(url);
message.setTopcolor("#FF0000");
String time = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
TreeMap<String, TreeMap<String, String>> params = new TreeMap<>();
params.put("first", WxTemplateMessage.item("紧急任务开发", "#173177"));
params.put("keyword1", WxTemplateMessage.item("xxxxxxxx", "#173177"));
params.put("keyword2", WxTemplateMessage.item(time, "#173177"));
params.put("keyword3", WxTemplateMessage.item("xxxxxxxx-微信模板消息", "#173177"));
params.put("remark", WxTemplateMessage.item("2022-08-31是最后截止时间,请注意", "#173177"));
message.setData(params);
String data = JSON.toJSONString(message);
// 发送模板消息
String result = wxThirdService.sendTemplateMessage(data);
return ResultUtils.success(result);
}
}
微信公众号发送模板消息