微信公众号--发送模板消息

微信开发文档:https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Template_Message_Interface.html

1、新增模板接口:

 

 1 // 构造方法 get() set()都没写
 2 public class Template {
 3     private String touser;  // 接收模板消息的人的openid
 4     private String template_id;  // 模板ID
 5     private String url; // 点击模板消息跳转的地址  也可以为"" 
 6 }
 7 public class ApplyNoticeTemplate extends Template {
 8     private String from;
 9     private String to;
10     public ApplyNoticeTemplate(String touser, String template_id, String url, String from, String to) {
11         super(touser, template_id, url);
12         this.from = from;
13         this.to = to;
14     }
15 }

JSON字符串格式:

 1 ApplyNoticeTemplate template = new ApplyNoticeTemplate(caropenid,WXService.APPLY_NOTICE_TEMPLATE_ID,url,from,to);
 2 String jsonString = WXService.getApplyNoticeTemplateJson(template); // 将这个template里的内容转换成对应的json字符串
 3 System.out.println("jsonString-----------------" + jsonString); // 如果发送失败 看看这个json字符串与开发文档里面的json字符串有什么不同
 4 String template_url = WXService.TEMPLATE_URL; // 发送模板消息的URL 在开发文档里有
 5 template_url = template_url.replace("ACCESS_TOKEN", WXService.getAccessToken());
 6 String result = Util.post(template_url, jsonString);
 7 System.out.println("给用户发送给一个拼车申请通知模板消息: " + result);
 8 // 结果是 {"errcode":"0","errmsg":"ok","msgid":""}表示发送成功
 9 
10 // WXService类里面的方法:
11 public static String getApplyNoticeTemplateJson(ApplyNoticeTemplate template) {
12     Map<String, Object> params=new HashMap<String,Object>();
13     Map<String, Object> data=new HashMap<String,Object>();
14     Map<String, Object> from=new HashMap<String,Object>();
15     Map<String, Object> to=new HashMap<String,Object>();
16     params.put("touser", template.getTouser());
17     params.put("template_id", template.getTemplate_id());
18     params.put("url", template.getUrl());
19     from.put("value", template.getFrom());
20     from.put("color", "#173177");
21     to.put("value", template.getTo());
22     to.put("color", "#173177");
23     data.put("from", from);
24     data.put("to", to);
25     params.put("data", data);
26     String  paramString= JSON.toJSONString(params);
27     return paramString;
28}

在上面的点击模板消息跳转的url中,要写完整的项目地址加对应的页面地址,例如

 1 String url = "http://ddiamondd.w3.luyouxia.net/WeChat/apply/dealapplycar.jsp" 

否则不知道要具体跳转到哪里去。

原文地址:https://www.cnblogs.com/DDiamondd/p/13042340.html