前言:
正如许多推送一样,微信也友好的给广大开发者提供了“模板消息”,比推送更好的是,它能借助海量用户的微信平台直接通过服务号以短消息形式传达给用户,大大提高了运营的可能性。比如我们现在可以完全抛开银行卡的短信服务,通过相关银行提供服务号绑定银行卡,当发生交易的时候同样的能收到交易详情短消息,确实是方便了不少!
开发准备:设置模板
官方文档:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1433751277
实际项目中肯定会存在多种类型的模板,那么肯定需要做一些共用代码封装,我这里以“告警通知”这个模板为例
项目结构:
实例代码:
xiaoqiang.java:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import javax.net.ssl.HttpsURLConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.client.RestTemplate;
import net.sf.json.JSONObject;
public class xiaoqiang {
public static final String appid = "xxxxxxxxxxxxxxxxxx";
public static final String appsecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
private static Logger loger = LoggerFactory.getLogger(xiaoqiang.class);
public static void main(String args[]) throws UnsupportedEncodingException {
boolean isOk = sendWXmessage("omC2vt7Abjv5ZTlD_WXRaN4c2vOs","有美女爱上了你,请尽快处理","https://blog.csdn.net/m0_37739193");
if (isOk) {
loger.info("微信预警发送成功");
} else {
loger.info("微信预警发送失败");
}
}
// 发送微信预警信息
public static boolean sendWXmessage(String openid, String text, String Url) throws UnsupportedEncodingException {
boolean flag = false;
Map<String, String> paramMap = new HashMap<String, String>();
paramMap.put("first", "xxx系统预警信息");
paramMap.put("content", text);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
String date = df.format(new Date());
paramMap.put("occurtime", date);
try {
String template_id = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";// 模板ID
TemplateMessage templateInfo = new TemplateMessage();
templateInfo.setTouser(openid);
templateInfo.setTemplate_id(template_id);
templateInfo.setUrl(Url); //点击模板跳转链接
Map<String, TemplateValue> data = new HashMap<String, TemplateValue>();
Map<String, String> map = paramMap;
for (Entry<String, String> entity : map.entrySet()) {
TemplateValue value = new TemplateValue();
value.setColor("#173177");
value.setValue(entity.getValue());
data.put(entity.getKey(), value);
}
templateInfo.setData(data);
// String acessToken = getWXAccessToken(); // 可参考上一篇文章中获取access_token的代码
String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + acessToken;
RestTemplate template = new RestTemplate();
TemplateResult result = template.postForObject(url, templateInfo, TemplateResult.class);
System.out.println(result.getErrcode());
if (result.getErrcode() != 0) {
System.out.println(
String.valueOf("发送模版信息失败:openId:[" + templateInfo.getTouser() + "]," + result.getErrcode())
+ ":" + result.getErrmsg());
} else {
flag = true;
}
return flag;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
TemplateMessage.java:
import java.util.Map;
/**
* 功能描述:
* <p>
* 微信模版消息
* </p>
*/
public class TemplateMessage {
private String touser;
private String template_id;
private String url;
private Map<String, TemplateValue> 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 Map<String, TemplateValue> getData() {
return data;
}
public void setData(Map<String, TemplateValue> data) {
this.data = data;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
TemplateResult.java:
/**
* 功能描述:
* <p>发送模版信息结果对象 </p>
*/
public class TemplateResult {
private int errcode;
private String errmsg;
private long msgid;
public int getErrcode() {
return errcode;
}
public void setErrcode(int errcode) {
this.errcode = errcode;
}
public String getErrmsg() {
return errmsg;
}
public void setErrmsg(String errmsg) {
this.errmsg = errmsg;
}
public long getMsgid() {
return msgid;
}
public void setMsgid(long msgid) {
this.msgid = msgid;
}
}
TemplateValue.java:
/**
* 功能描述:
* <p>微信模版业务数据参数对象 </p>
*/
public class TemplateValue {
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;
}
}
运行代码结果:
注意这里有个坑:
所有value的总长度不能超过200字,否则会出现三个点省略号的尴尬局面。
POST请求实例:
https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=access_token
{
"touser":openid,
"template_id":模板ID,
"url":"https://blog.csdn.net/m0_37739193",
"data":{
"first": {
"value":"恭喜你购买成功!",
"color":"#2354ad"
},
"content":{
"value":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaee",
"color":"#173177"
},
"occurtime": {
"value":"2018-12-10 18:45:12",
"color":"#173177"
}
}
}