第一步:申请模板消息功能并添加模板
在微信公众平台找到你需要的模板,并添加上即可;
第二步:添加功能模块后开始开发
功能中使用的类及代码:
发送数据主实体类:
Template.java
package com.wfcm.wxUitls; import org.apache.commons.lang.StringUtils; import java.util.ArrayList; import java.util.List; public class Template { // 消息接收方 private String toUser; // 模板id private String templateId; // 模板消息详情链接 private String url; // 消息顶部的颜色 private String topColor; // 参数列表 private ListtemplateParamList; //省略getter、setter方法 //按微信接口要求格式化模板 public String toJSON() { StringBuffer buffer = new StringBuffer(); buffer.append("{"); buffer.append(String.format("\"touser\":\"%s\"", this.toUser)).append(","); buffer.append(String.format("\"template_id\":\"%s\"", this.templateId)).append(","); buffer.append(String.format("\"url\":\"%s\"", this.url)).append(","); buffer.append(String.format("\"topcolor\":\"%s\"", this.topColor)).append(","); buffer.append("\"data\":{"); TemplateParam param = null; for (int i = 0; i < this.templateParamList.size(); i++) { param = templateParamList.get(i); // 判断是否追加逗号 if (i < this.templateParamList.size() - 1){ buffer.append(String.format("\"%s\": {\"value\":\"%s\",\"color\":\"%s\"},", param.getName(), param.getValue(), param.getColor())); }else{ buffer.append(String.format("\"%s\": {\"value\":\"%s\",\"color\":\"%s\"}", param.getName(), param.getValue(), param.getColor())); } } buffer.append("}"); buffer.append("}"); return buffer.toString(); } public String getToUser() { return toUser; } public void setToUser(String toUser) { this.toUser = toUser; } public String getTemplateId() { return templateId; } public void setTemplateId(String templateId) { this.templateId = templateId; } 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 List getTemplateParamList() { return templateParamList; } public void setTemplateParamList(List templateParamList) { this.templateParamList = templateParamList; } }
TemplateParam.java
package com.wfcm.wxUitls; import java.util.ArrayList; import java.util.List; public class TemplateParam { private String name; private String value; private String color; public TemplateParam(String name, String value, String color) { this.name = name; this.value = value; this.color = color; } public String getName() { return name; } public void setName(String name) { this.name = name; } 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; } }
HttpUtil.java
package com.wfcm.utils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.net.ConnectException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.List; import java.util.Map; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.apache.commons.io.IOUtils; public class HttpUtil { /** * 向指定 URL 发送POST方法的请求 * * @param url 发送请求的 URL * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 * @return 所代表远程资源的响应结果 */ public static String sendPost(String url, String param) { PrintWriter out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(url); // 打开和URL之间的连接 HttpURLConnection conn = (HttpURLConnection) realUrl .openConnection(); // 设置通用的请求属性 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 发送POST请求必须设置如下两行 conn.setDoOutput(true); conn.setDoInput(true); // 获取URLConnection对象对应的输出流 out = new PrintWriter(conn.getOutputStream()); // 发送请求参数 out.print(param); // flush输出流的缓冲 out.flush(); // 定义BufferedReader输入流来读取URL的响应 in = new BufferedReader(new InputStreamReader( conn.getInputStream(), "utf-8")); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("发送 POST 请求出现异常!" + e); e.printStackTrace(); } // 使用finally块来关闭输出流、输入流 finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return result; } }
Demo : 其中accessToken 如何获取就不详细讲了。
@Test public void test(String tplId,String openId) { // String tplId = "Z7CfpaavOr7JT5MMH98IvXzpn4A0bJbguKSQYMEh5Iw"; // String openId = "oBkmD01XLbYdT"; Template tem=new Template(); tem.setTemplateId(tplId); tem.setTopColor("#ffab17"); Listparas=new ArrayList (); paras.add(new TemplateParam("first","您好,恭喜您成功购买商品","#ffab17")); paras.add(new TemplateParam("keyword1","支付金额200","#ffab17")); paras.add(new TemplateParam("keyword2", "小学语文","#ffab17")); paras.add(new TemplateParam("keyword2", "1234567890","#ffab17")); paras.add(new TemplateParam("remark","先到先得!!!点击立即学习","#ffab17")); tem.setTemplateParamList(paras); tem.setToUser(openId);//用户openid //设置超链接 tem.setUrl("https://newwf.wfkids.net/#/?1553247181"); JSONObject jsonObject = sendTemplateMsg(tem); log.info("结果:"+jsonObject); System.out.println("结果:"+jsonObject); } public JSONObject sendTemplateMsg(Template template){ //获取token String token = "20_ZQvOMFYGY_uGeis_edeAD-U-yd2opdxxxxxx"; log.info("wxAccessToken:"+token); String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN"; requestUrl=requestUrl.replace("ACCESS_TOKEN", token); if (log.isDebugEnabled()) { log.debug(template.toJSON()); } //发送模板消息,返回json格式结果 log.info("json:"+ template.toJSON()); String r = HttpUtil.sendPost(requestUrl, template.toJSON()); JSONObject jsonObject= FastJSONUtils.getJSONObject(r); return jsonObject; }