微信消息模板可以解决什么问题?
1.类似微信支付成功的消息返回,可以自定义返回的内容
2.可以通过用户openID,主动推送消息到具体的微信用户
微信消息模板设置,此处不细说直接截图,此处注意,模板内容识别回车。
配置成功之后,微信的准备工作就做完了。下面是代码
首先,模板的内容要json格式的,我们需要一个模板内容的组装方法,json我用的是alibaba
public static JSONObject packJsonmsg(String first, String code, String description,String time, String remark){
JSONObject json = new JSONObject();
try {
JSONObject jsonFirst = new JSONObject();
jsonFirst.put("value", first);
jsonFirst.put("color", "#173177");
json.put("first", jsonFirst);
JSONObject jsonOrderCode = new JSONObject();
jsonOrderCode.put("value", code);
jsonOrderCode.put("color", "#173177");
json.put("woId", jsonOrderCode);
JSONObject jsonOrderDescription = new JSONObject();
jsonOrderDescription.put("value", description);
jsonOrderDescription.put("color", "#173177");
json.put("description", jsonOrderDescription);
JSONObject jsonOrderTime = new JSONObject();
jsonOrderTime.put("value", time);
jsonOrderTime.put("color", "#173177");
json.put("time", jsonOrderTime);
JSONObject jsonRemark = new JSONObject();
jsonRemark.put("value", remark);
jsonRemark.put("color", "#173177");
json.put("remark", jsonRemark);
} catch (JSONException e) {
e.printStackTrace();
}
return json;
}
其次,是发送消息模板的方法,返回结果自己根据心情随便写
/**
* @method sendWechatmsgToUser
* @描述: TODO(发送模板信息给用户)
* @参数@param touser 用户的openid
* @参数@param templat_id 信息模板id
* @参数@param url 用户点击详情时跳转的url
* @参数@param topcolor 模板字体的颜色
* @参数@param data 模板详情变量 Json格式
* @参数@param token 微信请求accesstoken
* @参数@return
*/
public static String sendWechatmsgToUser(String touser, String templat_id, String clickurl, String topcolor, JSONObject data, String token){
String send_model_url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
String url = send_model_url.replace("ACCESS_TOKEN", token);
JSONObject json = new JSONObject();
try {
json.put("touser", touser);
json.put("template_id", templat_id);
json.put("url", clickurl);
json.put("topcolor", topcolor);
json.put("data", data);
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject resultJson = WeixinUtil.httpRequest(url, "POST", json.toString());
String errmsg = (String) resultJson.get("errmsg");
if(!"ok".equals(errmsg)){
return "error";
}
return "success";
}
工具方法,发送请求的,微信模板是需要POST请求
/**
* 发起https请求并获取结果
*
* @param requestUrl 请求地址
* @param requestMethod 请求方式(GET、POST)
* @param outputStr 提交的数据
* @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
*/
public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
JSONObject jsonObject = null;
StringBuffer buffer = new StringBuffer();
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 httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// 设置请求方式(GET/POST)
httpUrlConn.setRequestMethod(requestMethod);
if ("GET".equalsIgnoreCase(requestMethod))
httpUrlConn.connect();
// 当有数据需要提交时
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
// 注意编码格式,防止中文乱码
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 将返回的输入流转换成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
jsonObject = JSONObject.parseObject(buffer.toString());
} catch (ConnectException ce) {
logger.info("Weixin server connection timed out.");
} catch (Exception e) {
logger.info("https request error:{}"+e.getMessage());
}
return jsonObject;
}
最后是使用方法:这个可以放在想要发送消息的地方,比如在微信网页中提交后,返回处理结果提醒,等场景。
String openId = "gh123213213";
String messageTemplatId = "微信添加模板生成的";
JSONObject callbackjson = MessageModel.packJsonmsg("有处理提醒,请查看", "A20171110001","","2017-11-10 13:20", "祝您生活愉快");
String result = MessageModel.sendWechatmsgToUser(openId, messageTemplatId, "http://www.baidu.com/", "#ef0505", callbackjson, token);