1、获取Access_token-微信开发文档
2、模板消息接口-微信开发文档
首先需要在微信公众号后台模板消息中申请模板id,申请好以后可以在模板消息–>我的模板–>模板详情中查看到具体模板id和模板样式
例如:
下面就可以开始写代码了(就是封装好具体参数然后,调用微信开放的接口即可):
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
import com.phjr.service.huifu.util.HttpClientUtil;
import weixn.Demo;
public class TuiSongTest {
private static Logger logger = LoggerFactory.getLogger(TuiSongTest.class);
//微信模板接口
private final String SEND_TEMPLAYE_MESSAGE_URL ="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
private final String APPID = "";
private final String SECRET = "";
//获取微信ACCESS_TOKEN接口
private final String aturl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APPID
+ "&secret=" + SECRET;
//openId
private static String fromUserName="";
//模板ID
private static String template_id="";
//模板消息详情跳转URL
private static String url="";
public static void main(String[] args) {
TuiSongTest tuiSongTest = new TuiSongTest();
Demo demo = tuiSongTest.getAccess_token();
String access_token=demo.getAccess_token();
logger.info("为模板消息接口获取的accessToken是"+access_token);
WechatTemplate wechatTemplate = new WechatTemplate();
wechatTemplate.setTemplate_id(template_id);
wechatTemplate.setTouser(fromUserName); //此处是用户的OpenId
wechatTemplate.setUrl(url);
private static Logger logger = LoggerFactory.getLogger(TuiSongTest.class);
//微信模板接口
private final String SEND_TEMPLAYE_MESSAGE_URL ="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
private final String APPID = "";
private final String SECRET = "";
//获取微信ACCESS_TOKEN接口
private final String aturl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APPID
+ "&secret=" + SECRET;
//openId
private static String fromUserName="";
//模板ID
private static String template_id="";
//模板消息详情跳转URL
private static String url="";
public static void main(String[] args) {
TuiSongTest tuiSongTest = new TuiSongTest();
Demo demo = tuiSongTest.getAccess_token();
String access_token=demo.getAccess_token();
logger.info("为模板消息接口获取的accessToken是"+access_token);
WechatTemplate wechatTemplate = new WechatTemplate();
wechatTemplate.setTemplate_id(template_id);
wechatTemplate.setTouser(fromUserName); //此处是用户的OpenId
wechatTemplate.setUrl(url);
<strong><span style="color:#ff0000"> //根据不同模板 拼写不同数据
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("#000000");
keyword1.setValue("136****1234");
m.put("keyword1", keyword1);
TemplateData keyword2 = new TemplateData();
keyword2.setColor("#000000");
keyword2.setValue("2018-06-10 10:23:00");
m.put("keyword2", keyword2);
TemplateData remark = new TemplateData();
remark.setColor("#000000");
remark.setValue("用户136****1234是您的直接推荐好友");
m.put("remark", remark);
wechatTemplate.setData(m);
try {
tuiSongTest.sendTemplateMessage(access_token, wechatTemplate);
} catch (Exception e) {
logger.info("异常"+e.getMessage());
}
}
public void sendTemplateMessage(String accessToken, WechatTemplate wechatTemplate) { String jsonString = new Gson().toJson(wechatTemplate).toString(); String requestUrl = SEND_TEMPLAYE_MESSAGE_URL.replace("ACCESS_TOKEN", accessToken); logger.info("请求参数",jsonString); //发送 post请求 发送json数据 String json = HttpClientUtil.sendHttpPostJson(requestUrl, jsonString); WeiXinResponse weiXinResponse = new Gson().fromJson(json, WeiXinResponse.class); logger.info("jsonObject="+weiXinResponse); if (null != weiXinResponse) { int errorCode = weiXinResponse.getErrcode(); if (0 == errorCode) { logger.info("模板消息发送成功"); } else { String errorMsg = weiXinResponse.getErrmsg(); logger.info("模板消息发送失败,错误是 "+errorCode+",错误信息是"+ errorMsg); } } } public Demo getAccess_token() { try { String access_token = ""; DefaultHttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(aturl); HttpResponse response = client.execute(request); String httpGet = HttpClientUtil.sendHttpGet(aturl); Gson gson=new Gson(); Demo jsonResult=new Demo(); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { String strResult = EntityUtils.toString(response.getEntity()); System.out.println("get请求结果:" + strResult); System.out.println("结果回调" +response.getStatusLine().getStatusCode() ); jsonResult = gson.fromJson(strResult, Demo.class); access_token = jsonResult.getAccess_token(); String expires_in =jsonResult.getExpires_in(); logger.info("access_token{}: expires_in{}:",access_token,expires_in); } return jsonResult; } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } }
}
相关实体如下:
public class Demo {
private String access_token;
private String expires_in;
public String getAccess_token() {
return access_token;
}
public void setAccess_token(String access_token) {
this.access_token = access_token;
}
public String getExpires_in() {
return expires_in;
}
public void setExpires_in(String expires_in) {
this.expires_in = expires_in;
}
}
import java.util.Map;
public class WechatTemplate {
private String touser;
private String template_id;
private String url;
private Map<String, TemplateData> 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, TemplateData> getData() {
return data;
}
public void setData(Map<String, TemplateData> data) {
this.data = data;
}
}
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;
}
}
public class WeiXinResponse {
private Integer errcode;
private String errmsg;
private String msgid;
public Integer getErrcode() {
return errcode;
}
public void setErrcode(Integer errcode) {
this.errcode = errcode;
}
public String getErrmsg() {
return errmsg;
}
public void setErrmsg(String errmsg) {
this.errmsg = errmsg;
}
public String getMsgid() {
return msgid;
}
public void setMsgid(String msgid) {
this.msgid = msgid;
}
}
/**
* 发送 post请求 发送json数据
*
* @param httpUrl
* 地址
* @param paramsJson
* 参数(格式 json)
*
*/
public static String sendHttpPostJson(String httpUrl, String paramsJson) {
HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
try {
// 设置参数
if (paramsJson != null && paramsJson.trim().length() > 0) {
StringEntity stringEntity = new StringEntity(paramsJson, "UTF-8");
stringEntity.setContentType(CONTENT_TYPE_JSON_URL);
httpPost.setEntity(stringEntity);
}
} catch (Exception e) {
e.printStackTrace();
}
return sendHttpPost(httpPost);
}
/**
* 发送Post请求
*
* @param httpPost
* @return
*/
private static String sendHttpPost(HttpPost httpPost) {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
// 响应内容
String responseContent = null;
try {
// 创建默认的httpClient实例.
httpClient = getHttpClient();
// 配置请求信息
httpPost.setConfig(requestConfig);
// 执行请求
response = httpClient.execute(httpPost);
// 得到响应实例
HttpEntity entity = response.getEntity();
// 判断响应状态
if (response.getStatusLine().getStatusCode() >= 300) {
throw new Exception(
"HTTP Request is not success, Response code is " + response.getStatusLine().getStatusCode());
}
if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
responseContent = EntityUtils.toString(entity, CHARSET_UTF_8);
EntityUtils.consume(entity);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 释放资源
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return responseContent;
}