1、封装模板数据类
public class TemplatData {
private String value;
private String color;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
2、业务处理
/**
* 统一服务消息
* 公众号模板消息,发送公众号通知
* @param token 小程序ACCESS_TOKEN
* @param touser 用户openid,可以是小程序的openid,也可以是公众号的openid
* @param appid 公众号appid
* @param template_id 公众号模板消息模板id
* @param url 公众号模板消息所要跳转的url
* @param data 公众号模板消息的数据
* @return
* @author HGL
*/
// 获取基础支持的access_token 小程序
String access_token = WeiXinConfig.getAccessToken();
List<official_userEntity> offlist = officialuserDao.selectUsers();
String openid = null;
String linkurl =null;
for (int i = 0; i < offlist.size(); i++) {
openid = offlist.get(i).getOpenid();
linkurl = offlist.get(i).getLinkurl();
JSONObject json1 = new JSONObject(new LinkedHashMap<>());
JSONObject mp_template_msg = new JSONObject(new LinkedHashMap<>());
// 发送模板消息
String url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send?access_token="+access_token;
// 封装基础数据
json1.put("touser", openid);
mp_template_msg.put("appid", WeiXinConfig.APPID2);
mp_template_msg.put("template_id", "ElQglLppK2KR4BRaa74bGPzO76v0q-NOHD2pbSGJKMI");
mp_template_msg.put("url", linkurl);
Map<String, TemplatData> mapdata = new LinkedHashMap<>();
// 封装模板数据
TemplatData first = new TemplatData();
first.setValue("尊敬的小主,你已成为尊贵的xx会员");
first.setColor("#173177");
mapdata.put("first", first);
TemplatData keyword1 = new TemplatData();
keyword1.setValue(offlist.get(i).getNickname());
keyword1.setColor("#173177");
mapdata.put("keyword1", keyword1);
TemplatData keyword2 = new TemplatData();
keyword2.setValue("0");
first.setColor("#173177");
mapdata.put("keyword2", keyword2);
TemplatData keyword3 = new TemplatData();
keyword3.setValue(offlist.get(i).getCreatetime());
first.setColor("#173177");
mapdata.put("keyword3", keyword3);
TemplatData keyword4 = new TemplatData();
keyword4.setValue("如有疑问,请致电客服。xxxxx");
keyword4.setColor("#173177");
mapdata.put("remark", keyword4);
mp_template_msg.put("data", mapdata);
json1.put("mp_template_msg", mp_template_msg);
HttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
try {
//此处应设定参数的编码格式,不然中文会变乱码
StringEntity s = new StringEntity(json1.toString(), "UTF-8");
s.setContentEncoding("UTF-8");
s.setContentType("application/json");
post.setEntity(s);
post.addHeader("content-type", "application/json");
HttpResponse res = client.execute(post);
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String result = EntityUtils.toString(res.getEntity());// 返回json格式
System.out.println("推送成功" + result);
} else {
System.out.println("推送失败");
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
3、效果图