前言 因为微信接口的改版 无法获得用户的信息 只能通过用户注册拿到openid进行模板消息推送
首先查看文档 模板消息接口文档
如文档所示,我们需要的参数有access_tocken,template_id.to_user,data中的参数是必传的,所以我们先要在自己申请的测试公众号里新增模板消息
简单实现
新建TemplateData
public class TemplateData {
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;
}
}
新建WxTemplate
import java.util.Map;
public class WxTemplate {
private String template_id;//模板ID
private String touser;//目标客户
private String url;//用户点击模板信息的跳转页面
private String topcolor;//字体颜色
private Map<String,TemplateData> data;//模板里的数据
public String getTemplate_id() {
return template_id;
}
public void setTemplate_id(String template_id) {
this.template_id = template_id;
}
public String getTouser() {
return touser;
}
public void setTouser(String touser) {
this.touser = touser;
}
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 Map<String, TemplateData> getData() {
return data;
}
public void setData(Map<String, TemplateData> data) {
this.data = data;
}
}
工具包
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.net.URI;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
/**
* Created with IntelliJ IDEA.
*
* @author: lenovo
* @createTime: 2022/2/21
* @Time: 9:17
* Description: No Description
*/
public class GetOpenIdAct {
/******************************************************************获取关注用户信息****************************************************/
public JSONObject getUrlResponse(String url) {
CharsetHandler handler = new CharsetHandler("UTF-8");
try {
HttpGet httpget = new HttpGet(new URI(url));
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
//HttpClient
CloseableHttpClient client = httpClientBuilder.build();
client = (CloseableHttpClient) wrapClient(client);
return new JSONObject(client.execute(httpget, handler));
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static HttpClient wrapClient(HttpClient base) {
try {
SSLContext ctx = SSLContext.getInstance("TLSv1");
X509TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] xcs,
String string) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] xcs,
String string) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
ctx.init(null, new TrustManager[]{tm}, null);
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(ctx, new String[]{"TLSv1"}, null,
SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
return httpclient;
} catch (Exception ex) {
return null;
}
}
public class CharsetHandler implements ResponseHandler<String> {
private String charset;
public CharsetHandler(String charset) {
this.charset = charset;
}
public String handleResponse(HttpResponse response)
throws ClientProtocolException, IOException {
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() >= 300) {
throw new HttpResponseException(statusLine.getStatusCode(),
statusLine.getReasonPhrase());
}
HttpEntity entity = response.getEntity();
if (entity != null) {
if (!StringUtils.isBlank(charset)) {
return EntityUtils.toString(entity, charset);
} else {
return EntityUtils.toString(entity);
}
} else {
return null;
}
}
}
}
首先获取access_tocken
/**
* 获取access_token
* @return
*/
public String getToken() {
String tokenGetUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";//微信提供获取access_token接口地址
String appid =;
String secret = ;
System.out.println("~~~~~appid:" + appid);
System.out.println("~~~~~secret:" + secret);
org.json.JSONObject tokenJson = new org.json.JSONObject();
if (StringUtils.isNotBlank(appid) && StringUtils.isNotBlank(secret)) {
tokenGetUrl += "&appid=" + appid + "&secret=" + secret;
tokenJson = new GetOpenIdAct().getUrlResponse(tokenGetUrl);
System.out.println("~~~~~tokenJson:" + tokenJson.toString());
try {
return (String) tokenJson.get("access_token");
} catch (JSONException e) {
System.out.println("报错了");
return null;
}
} else {
System.out.println("appid和secret为空");
return null;
}
}
然后我们可以发送模板消息
/**
* 发送模板消息
* @param t
* @return
*/
public static int sendMessage(WxTemplate t) {
String accessToken = new WeixinUtil().getToken();
JSONObject result = null;
// 拼装创建菜单的url
String url = Config.template_send_url;
url+="?access_token="+accessToken;
// 将菜单对象转换成json字符串
String jsonMenu = JSONObject.toJSONString(t);
// 调用接口创建菜单
try {
String string = HttpClientUtils.sendPostJsonStr(url, jsonMenu);
result = JSON.parseObject(string);
} catch (IOException e) {
e.printStackTrace();
}
int errcode = result.getIntValue("errcode");
switch (errcode){
case -1: throw new ServiceException("系统繁忙");
case 40001: throw new ServiceException("验证失败");
case 40002: throw new ServiceException("不合法的凭证类型");
case 40003: throw new ServiceException("不合法的OpenID");
case 40004: throw new ServiceException("不合法的媒体文件类型");
case 40005: throw new ServiceException("不合法的文件类型");
case 40006: throw new ServiceException("不合法的文件大小");
case 40007: throw new ServiceException("不合法的媒体文件id");
case 40008: throw new ServiceException("不合法的消息类型");
case 40009: throw new ServiceException("不合法的图片文件大小");
case 40010: throw new ServiceException("不合法的语音文件大小");
case 40011: throw new ServiceException("不合法的视频文件大小");
case 40012: throw new ServiceException("不合法的缩略图文件大小");
case 40013: throw new ServiceException("不合法的APPID");
case 41001: throw new ServiceException("缺少access_token参数");
case 41002: throw new ServiceException("缺少appid参数");
case 41003: throw new ServiceException("缺少refresh_token参数");
case 41004: throw new ServiceException("缺少secret参数");
case 41005: throw new ServiceException("缺少多媒体文件数据");
case 41006: throw new ServiceException("access_token超时");
case 43004: throw new ServiceException("当前有用户未关注公众号");
case 45002: throw new ServiceException("消息内容超过限制");
case 45003: throw new ServiceException("标题字段超过限制");
case 45004: throw new ServiceException("描述字段超过限制");
case 45005: throw new ServiceException("链接字段超过限制");
case 45006: throw new ServiceException("图片链接字段超过限制");
case 45009: throw new ServiceException("接口调用超过限制");
}
return errcode;
}
/**
* 发送模板消息前获取
*/
public static void sendMessageBefore(){
WxTemplate template = new WxTemplate();
template.setTouser("ozOAS6ZzjncFDqI5Pl-enth9bFnQ");
template.setTopcolor("#000000");
template.setTemplate_id("NliU01xug5MdobiANLkgqmsSqb1YfOz27GL5YuJogeo");
Map<String,TemplateData> m = new HashMap<String,TemplateData>();
TemplateData first = new TemplateData();
first.setColor("#000000");
first.setValue("您好,您有一条待确认订单。");
m.put("first", first);
TemplateData keyword1 = new TemplateData();
keyword1.setColor("#328392");
keyword1.setValue("大龙虾");
m.put("keyword1", keyword1);
TemplateData keyword2 = new TemplateData();
keyword2.setColor("#328392");
keyword2.setValue("1500");
m.put("keyword2", keyword2);
TemplateData keyword3 = new TemplateData();
keyword3.setColor("#328392");
keyword3.setValue("2022/2/21 11:43");
m.put("keyword3", keyword3);
TemplateData remark = new TemplateData();
remark.setColor("#929232");
remark.setValue("请及时确认订单!");
m.put("remark", remark);
template.setData(m);
WeixinUtil.sendMessage(template);
}
public static void main(String[] args) {
sendMessageBefore();
}