拿注册来举例,注册成功后,在注册成功方法中调用模板消息接口发送消息:
①注册成功之后的调用的方法:
/**
* 注册成功之后发送模板信息
* @param openid
*/
private void sendRegisterTemplate(){
try {
Model first = new Model("恭喜您,注册成功!", "#000000");
Model keyword1 = new Model("张三", "#000000");
Model keyword2 = new Model("131XXXXXXX", "#000000");
Model remark = new Model("开始尽情的购物吧!", "#000000");
RegisterData data = new RegisterData(first, keyword1, keyword2, remark);
TemplateReserve template = new TemplateReserve(data);
template.setTouser("接收信息人的openid");//openId
template.setTemplate_id("在模板库中添加的模板信息的id");//模版消息Id
template.setUrl("用户点击模板信息后跳转的地址");//模版点击后链接的地方
template.setTopcolor("模板头部的颜色");//模版头颜色
AdvancedUtil.sendTemplate("调用接口所需的token", template);
} catch (Exception e) {
e.printStackTrace();
}
}
②调用接口方法
/**
* 发送模版消息
* @param accessToken 接口访问凭证
* @param template 消息模版
*
* */
public static void sendTemplate(String accessToken,BaseTemplate template){
String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
requestUrl = requestUrl.replace("ACCESS_TOKEN",accessToken);
String postData = JSONObject.fromObject(template).toString();
JSONObject jsonObject = WSPostUtil.httpsRequest(requestUrl, "POST", postData);
System.out.println(jsonObject.toString());
try {
int errorCode = jsonObject.getInt("errcode");
String errorMsg = jsonObject.getString("errmsg");
if(errorCode==0){
log.info("模版发送成功 errcode:{} errmsg:{}", errorCode, errorMsg);
}else{
log.error("模版发送失败 errcode:{} errmsg:{}", errorCode, errorMsg);
}
} catch (Exception e) {
log.error("模版消息发送异常,"+e.getMessage());
}
}
③httpRequest方法
/**
* 发送https请求
*
* @param requestUrl 请求地址
* @param requestMethod 请求方式(GET、POST)
* @param outputStr 提交的数据
* @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
*/
public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
JSONObject jsonObject = null;
try {
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(ssf);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
// 设置请求方式(GET/POST)
conn.setRequestMethod(requestMethod);
// 当outputStr不为null时向输出流写数据
if (null != outputStr) {
OutputStream outputStream = conn.getOutputStream();
// 注意编码格式
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 从输入流读取返回内容
InputStream inputStream = conn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
StringBuffer buffer = new StringBuffer();
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
// 释放资源
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
inputStream = null;
conn.disconnect();
jsonObject = JSONObject.fromObject(buffer.toString());
} catch (ConnectException ce) {
log.error("连接超时:{}", ce);
} catch (Exception e) {
log.error("https请求异常:{}", e);
}
return jsonObject;
}
public class Model{
private String value; //内容
private String color; //字体颜色
public Model(String color) {
this.color = color;
}
public Model() {
super();
}
public Model(String value, String color) {
super();
this.value = value;
this.color = color;
}
public String getValue() {
return value;
}
public Model setValue(String value) {
this.value = value;
return this;
}
public String getColor() {
return color;
}
public Model setColor(String color) {
this.color = color;
return this;
}
}
public class RegisterData extends Data{
private Model first;//模板开始前描述
private Model keyword1;//关键词1
private Model keyword2;//关键词2
private Model remark;//模板结束描述
public RegisterData(Model first, Model keyword1, Model keyword2, Model remark) {
this.first = first;
this.keyword1 = keyword1;
this.keyword2 = keyword2;
this.remark = remark;
}
public Model getFirst() {
return first;
}
public void setFirst(Model first) {
this.first = first;
}
public Model getKeyword1() {
return keyword1;
}
public void setKeyword1(Model keyword1) {
this.keyword1 = keyword1;
}
public Model getKeyword2() {
return keyword2;
}
public void setKeyword2(Model keyword2) {
this.keyword2 = keyword2;
}
public Model getRemark() {
return remark;
}
public void setRemark(Model remark) {
this.remark = remark;
}
}
⑥TemplateReverse类
public class TemplateReserve extends BaseTemplate {
private Data data;
public TemplateReserve(Data data){
this.data = data;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
}
public abstract class Data {
}
⑧BaseTemplate类
/**
* 模版消息基类
* @author wangrr
* */
public class BaseTemplate {
private String touser; //openId
private String template_id; //模版消息Id
private String url; //模版点击后链接的地方
private String topcolor; //模版头颜色
public BaseTemplate() {
}
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;
}