微信公眾號--發送模板消息


微信開發文檔: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" 

否則不知道要具體跳轉到哪里去。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM