在微信公衆號開發過程當中,咱們有時候作不一樣權限的時候,好比在註冊的時候,須要審覈,而後咱們要想辦法讓對方知道審覈的結果。這時候咱們能夠經過模板消息來通知。java
首先,登陸微信公衆平臺,看有沒有模板消息這一塊,沒有的話點擊添加功能插件,去添加,這裏就省略不說了,這個主要就是選擇你公衆號的行業對應的模板消息,而後經過審覈以後就可使用了,說是幾個工做日android
可是通常很快就審覈經過的。ios
有模板消息以後點進來,對應本身所須要的模板消息進行添加,好比,我添加了一個審覈的模板,在模板使用介紹上面其實也是沒說的很清楚,我看了感受徹底就是不會用,就是給你個數據類型,數據樣式查看spring
好了,這些大概百度下了解是什麼意思,咱們如今主要仍是上代碼部分吧。json
(一)首先咱們先上一個工具類api
1 import java.io.BufferedReader; 2 import java.io.InputStream; 3 import java.io.InputStreamReader; 4 import java.io.OutputStream; 5 import java.net.ConnectException; 6 import java.net.URL; 7 8 import javax.net.ssl.HttpsURLConnection; 9 import javax.net.ssl.SSLContext; 10 import javax.net.ssl.SSLSocketFactory; 11 import javax.net.ssl.TrustManager; 12 13 import net.sf.json.JSONException; 14 import net.sf.json.JSONObject; 15 16 import org.slf4j.Logger; 17 import org.slf4j.LoggerFactory; 18 19 import com.mj.agriculturalByProduct.templatemessage.pojo.Token; 20 import com.mj.templatemessage.util.MyX509TrustManager; 21 22 public class CommonUtil { 23 24 private static Logger log = LoggerFactory.getLogger(CommonUtil.class); 25 26 // 憑證獲取(GET) 27 public final static String token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET"; 28 29 /** 30 * 發送 https 請求 31 * 32 * @param requestUrl 請求地址 33 * @param requestMethod 請求方式(GET、POST) 34 * @param outputStr 提交的數據 35 * @return JSONObject(經過 JSONObject.get(key) 的方式獲取 JSON 對象的屬性值) 36 */ 37 public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) { 38 39 JSONObject jsonObject = null; 40 41 try { 42 // 建立 SSLContext 對象,並使用咱們指定的信任管理器初始化 43 TrustManager[] tm = { new MyX509TrustManager() }; 44 SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); 45 sslContext.init(null, tm, new java.security.SecureRandom()); 46 // 從上述 SSLContext 對象中獲得 SSLSocketFactory 對象 47 SSLSocketFactory ssf = sslContext.getSocketFactory(); 48 49 URL url = new URL(requestUrl); 50 HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); 51 conn.setSSLSocketFactory(ssf); 52 53 conn.setDoOutput(true); 54 conn.setDoInput(true); 55 conn.setUseCaches(false); 56 57 // 設置請求方式(GET/POST) 58 conn.setRequestMethod(requestMethod); 59 60 // 當 outputStr 不爲 null 時,向輸出流寫數據 61 if (null != outputStr) { 62 OutputStream outputStream = conn.getOutputStream(); 63 64 // 注意編碼格式 65 outputStream.write(outputStr.getBytes("UTF-8")); 66 outputStream.close(); 67 } 68 69 // 從輸入流讀取返回內容 70 InputStream inputStream = conn.getInputStream(); 71 InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8"); 72 BufferedReader bufferedReader = new BufferedReader(inputStreamReader); 73 String str = null; 74 StringBuffer buffer = new StringBuffer(); 75 76 while ((str = bufferedReader.readLine()) != null) { 77 buffer.append(str); 78 } 79 80 // 釋放資源 81 bufferedReader.close(); 82 inputStreamReader.close(); 83 inputStream.close(); 84 inputStream = null; 85 conn.disconnect(); 86 jsonObject = JSONObject.fromObject(buffer.toString()); 87 } catch (ConnectException ce) { 88 log.error(" 鏈接超時:{}", ce); 89 } catch (Exception e) { 90 log.error("https 請求異常:{}", e); 91 } 92 93 return jsonObject; 94 } 95 96 /** 97 * 獲取接口訪問憑證 98 * 99 * @param appid 憑證 100 * @param appsecret 密鑰 101 * @return 102 */ 103 public static Token getToken(String appid, String appsecret) { 104 Token token = null; 105 String requestUrl = token_url.replace("APPID", appid).replace("APPSECRET", appsecret); 106 // 發起GET請求獲取憑證 107 JSONObject jsonObject = httpsRequest(requestUrl, "GET", null); 108 109 if (null != jsonObject) { 110 try { 111 token = new Token(); 112 token.setAccessToken(jsonObject.getString("access_token")); 113 token.setExpiresIn(jsonObject.getInt("expires_in")); 114 System.out.println(jsonObject.getString("access_token")+"========="); 115 } catch (JSONException e) { 116 token = null; 117 // 獲取token失敗 118 log.error("獲取token失敗 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg")); 119 } 120 } 121 return token; 122 } 123 124 }
public class Token {
//接口訪問憑證
private String accessToken;
//接口有效期,單位:秒
private int expiresIn;
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public int getExpiresIn() {
return expiresIn;
}
public void setExpiresIn(int expiresIn) {
this.expiresIn = expiresIn;
}瀏覽器
}微信
(二)一個模板消息類app
1 import java.text.SimpleDateFormat; 2 import java.util.Date; 3 4 import net.sf.json.JSONObject; 5 6 import org.slf4j.Logger; 7 import org.slf4j.LoggerFactory; 8 import org.springframework.stereotype.Service; 9 10 import com.mj.agriculturalByProduct.templatemessage.pojo.Data; 11 import com.mj.agriculturalByProduct.templatemessage.pojo.Data_style; 12 import com.mj.agriculturalByProduct.templatemessage.pojo.NewOrdersTemplate; 13 import com.mj.agriculturalByProduct.templatemessage.pojo.Token; 14 import com.mj.basic.util.TTResult; 15 @Service 16 public class Template { 17 18 private static Logger log = LoggerFactory.getLogger(Template.class); 19 20 /** 21 * 發送模板消息 22 * appId 公衆帳號的惟一標識 23 * appSecret 公衆帳號的密鑰 24 * openId 用戶標識 25 * @return 26 */ 27 public TTResult send_template_message(String appId, String appSecret, String openId) { 28 //由於我申請的模板是須要填寫當前時間戳的,因此在這裏我獲取了當前的時間 29 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-HH-MM"); 30 String format = simpleDateFormat.format(new Date()); 31 Token token = CommonUtil.getToken(appId, appSecret);//這裏要注意,若是你是申請的正式公衆號的話,獲取token的時候,必定要在後臺加上你的ip,否則獲取token的時候會報錯 32 String access_token = token.getAccessToken(); 33 String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+access_token; 34 String templateId = "填寫你所使用的模板id"; 35 String goUrl = "填寫接收模板消息以後,你想要跳轉的url頁面。"; 36 37 Data_style first = new Data_style(); 38 Data_style keyword1 = new Data_style(); 39 Data_style keyword2 = new Data_style(); 40 Data_style remark = new Data_style(); 41 42 NewOrdersTemplate temp = new NewOrdersTemplate(); 43 Data data = new Data(); 44 45 first.setValue(format); 46 first.setColor("#173177"); 47 48 keyword1.setValue("您申請的審覈已經過,請到PC端瀏覽器輸入如下連接進行管理後臺的設置:(這些都是自定義內容)" 49 + "自定義內容"); 50 keyword1.setColor("#173177"); 51 52 keyword2.setValue(format); 53 keyword2.setColor("#173177"); 54 55 remark.setValue(""); 56 remark.setColor("#173177"); 57 58 data.setFirst(first); 59 data.setKeyword1(keyword1); 60 data.setKeyword2(keyword2); 61 data.setRemark(remark); 62 63 temp.setTouser(openId); 64 temp.setTemplate_id(templateId); 65 temp.setUrl(goUrl); 66 temp.setTopcolor("#173177"); 67 temp.setData(data); 68 69 String jsonString = JSONObject.fromObject(temp).toString().replace("day", "Day"); 70 JSONObject jsonObject = CommonUtil.httpsRequest(url, "POST", jsonString); 71 System.out.println(jsonObject); 72 int result = 0; 73 if (null != jsonObject) { 74 if (0 != jsonObject.getInt("errcode")) { 75 result = jsonObject.getInt("errcode"); 76 log.error("錯誤 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg")); 77 } 78 } 79 log.info("模板消息發送結果:"+result); 80 return TTResult.ok(); 81 }
}
https://mp.weixin.qq.com/advanced/tmplmsg?action=faq&token=1244423508&lang=zh_CN 這個是模板消息接口文檔地址。
上面的
Data_style first = new Data_style();
Data_style keyword1 = new Data_style(); Data_style keyword2 = new Data_style(); Data_style remark = new Data_style();
根據你實際的模板消息的參數個數添加修改。我這裏是兩個參數的模板。
(三)controller層接口微信公衆平臺
1 @Controller 2 public class TemplateController { 3 4 @Autowired 5 private Template template; 6 7 /** 8 * @param openid 9 * @param request 10 * @return 11 */ 12 @RequestMapping("/template/adopt") 13 public @ResponseBody TTResult test(String openid,HttpServletRequest request){ 14 try { 15 return template.send_template_message("你的APPID", "APPID對應的祕鑰", openid); 16 //openid 你想發送給你公衆號上的人 這個openid獲取方法下次寫,到這一步的話openid應該早就獲取過了吧。 17 } catch (Exception e) { 18 // TODO: handle exception 19 } 20 return TTResult.fail(); 21 } 22 這個TTresult的話就是一個返回值的一個參數說明 這個你們的定義都不同,這個無所謂的 就是 200成功 500失敗 之類的 自定義code
(4)問我仍是把個人TTresult貼出來吧
1 import java.util.List; 2 import com.fasterxml.jackson.databind.JsonNode; 3 import com.fasterxml.jackson.databind.ObjectMapper; 4 5 public class TTResult { 6 // 定義jackson對象 7 private static final ObjectMapper MAPPER = new ObjectMapper(); 8 9 // 響應業務狀態 10 private Integer status; // 200 表明成功, 500 表明失敗 11 12 // 響應消息 13 private String msg; 14 15 // 響應中的數據 16 private Object data; 17 18 public static TTResult build(Integer status, String msg, Object data) { 19 return new TTResult(status, msg, data); 20 } 21 22 public static TTResult ok(Object data) { 23 return new TTResult(data); 24 } 25 26 27 public static TTResult ok() { 28 return new TTResult(null); 29 } 30 31 public static TTResult fail(){ 32 return new TTResult(500,"fail",null); 33 } 34 35 public static TTResult fail(Object data){ 36 return new TTResult(500,"fail",data); 37 } 38 39 public TTResult() { 40 41 } 42 43 public static TTResult build(Integer status, String msg) { 44 return new TTResult(status, msg, null); 45 } 46 47 public TTResult(Integer status, String msg, Object data) { 48 this.status = status; 49 this.msg = msg; 50 this.data = data; 51 } 52 53 public TTResult(Object data) { 54 this.status = 200; 55 this.msg = "OK"; 56 this.data = data; 57 } 58 59 60 // public Boolean isOK() { 61 // return this.status == 200; 62 // } 63 64 public Integer getStatus() { 65 return status; 66 } 67 68 public void setStatus(Integer status) { 69 this.status = status; 70 } 71 72 public String getMsg() { 73 return msg; 74 } 75 76 public void setMsg(String msg) { 77 this.msg = msg; 78 } 79 80 public Object getData() { 81 return data; 82 } 83 84 public void setData(Object data) { 85 this.data = data; 86 } 87 88 /** 89 * 將json結果集轉化爲TTResult對象 90 * 91 * @param jsonData 92 * json數據 93 * @param clazz 94 * TTResult中的object類型 95 * @return 96 */ 97 public static TTResult formatToPojo(String jsonData, Class<?> clazz) { 98 try { 99 if (clazz == null) { 100 return MAPPER.readValue(jsonData, TTResult.class); 101 } 102 JsonNode jsonNode = MAPPER.readTree(jsonData); 103 JsonNode data = jsonNode.get("data"); 104 Object obj = null; 105 if (clazz != null) { 106 if (data.isObject()) { 107 obj = MAPPER.readValue(data.traverse(), clazz); 108 } else if (data.isTextual() || data.isNumber()) { 109 obj = MAPPER.readValue(data.asText(), clazz); 110 } 111 } 112 return build(jsonNode.get("status").intValue(), jsonNode.get("msg") 113 .asText(), obj); 114 } catch (Exception e) { 115 return null; 116 } 117 } 118 119 /** 120 * 沒有object對象的轉化 121 * 122 * @param json 123 * @return 124 */ 125 public static TTResult format(String json) { 126 try { 127 return MAPPER.readValue(json, TTResult.class); 128 } catch (Exception e) { 129 e.printStackTrace(); 130 } 131 return null; 132 } 133 134 /** 135 * Object是集合轉化 136 * 137 * @param jsonData 138 * json數據 139 * @param clazz 140 * 集合中的類型 141 * @return 142 */ 143 public static TTResult formatToList(String jsonData, Class<?> clazz) { 144 try { 145 JsonNode jsonNode = MAPPER.readTree(jsonData); 146 JsonNode data = jsonNode.get("data"); 147 Object obj = null; 148 if (data.isArray() && data.size() > 0) { 149 obj = MAPPER.readValue(data.traverse(), MAPPER.getTypeFactory() 150 .constructCollectionType(List.class, clazz)); 151 } 152 return build(jsonNode.get("status").intValue(), jsonNode.get("msg") 153 .asText(), obj); 154 } catch (Exception e) { 155 return null; 156 } 157 } 158 }
MyX509TrustManager 工具類
import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.X509TrustManager; /** * 信任管理器 * */ public class MyX509TrustManager implements X509TrustManager { @Override public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } }
還有上面所用到的一些類,接口
public class Data_style { 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; } }
public class Data { private Data_style first; private Data_style keyword1; private Data_style keyword2; private Data_style remark; public Data_style getFirst() { return first; } public void setFirst(Data_style first) { this.first = first; } public Data_style getKeyword1() { return keyword1; } public void setKeyword1(Data_style keyword1) { this.keyword1 = keyword1; } public Data_style getKeyword2() { return keyword2; } public void setKeyword2(Data_style keyword2) { this.keyword2 = keyword2; } public Data_style getRemark() { return remark; } public void setRemark(Data_style remark) { this.remark = remark; } }
public class NewOrdersTemplate { private String touser; //用戶OpenID private String template_id; //模板消息ID private String url; //URL置空,則在發送後,點擊模板消息會進入一個空白頁面(ios),或沒法點擊(android)。 private String topcolor; //標題顏色 private Data 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 templateId) { template_id = 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 Data getData() { return data; } public void setData(Data data) { this.data = data; } }
public class Token { //接口訪問憑證 private String accessToken; //接口有效期,單位:秒 private int expiresIn; public String getAccessToken() { return accessToken; } public void setAccessToken(String accessToken) { this.accessToken = accessToken; } public int getExpiresIn() { return expiresIn; } public void setExpiresIn(int expiresIn) { this.expiresIn = expiresIn; } }
不詳細說明了,直接貼代碼吧
import java.util.List; public class Template { // 消息接收方 private String toUser; // 模板id private String templateId; // 模板消息詳情連接 private String url; // 消息頂部的顏色 private String topColor; // 參數列表 private List<TemplateParam> templateParamList; //省略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<TemplateParam> getTemplateParamList() { return templateParamList; } public void setTemplateParamList(List<TemplateParam> templateParamList) { this.templateParamList = templateParamList; } }
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.ConnectException; import java.net.HttpURLConnection; import java.net.URL; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import net.sf.json.JSONObject; public class CommonUtil { public static JSONObject httpsRequest(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.fromObject(buffer.toString()); } catch (ConnectException ce) { ce.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return jsonObject; } public static String httpRequest(String requestUrl, String requestMethod, String outputStr) { StringBuffer buffer = new StringBuffer(); try { URL url = new URL(requestUrl); HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection(); 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.fromObject(buffer.toString()); } catch (ConnectException ce) { ce.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return buffer.toString(); } public static String urlEncodeUTF8(String source){ String result = source; try { result = java.net.URLEncoder.encode(source,"utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return result; } public static String httpsRequestForStr(String requestUrl, String requestMethod, String outputStr) { String result=""; 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(); result=buffer.toString(); } catch (ConnectException ce) { ce.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return result; } }
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; } }
public interface TemplateMessageService { /** * * @param inform * @param defeated * @param instructions * @param createds * @param request */ boolean sendMessage(String openid,String title,String defeated, String instructions,HttpServletRequest request); }
import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Service; import com.mj.agriculturalByProduct.templatemessage.pojo.Template; import com.mj.agriculturalByProduct.templatemessage.pojo.TemplateParam; import com.mj.templatemessage.util.CommonUtil; import net.sf.json.JSONObject; @Service public class TemplateMessageServiceImpl implements TemplateMessageService{ /** * 處理要通知的數據(完善模板消息) */ @Override public boolean sendMessage(String openid,String title, String defeated, String instructions, HttpServletRequest request) { Template tem=new Template(); tem.setTemplateId("模板消息id"); tem.setTopColor("#00DD00");//顏色 tem.setToUser(openid);//接收方ID System.out.println(openid+"====================="); //設置超連接(點擊模板可跳轉相應連接中) tem.setUrl("你要跳轉的連接"); List<TemplateParam> paras=new ArrayList<TemplateParam>();//消息主體 paras.add(new TemplateParam("first",title,"#333")); //標題 paras.add(new TemplateParam("keyword1",defeated,"#333"));//審覈類型 paras.add(new TemplateParam("keyword2",instructions,"#333"));//時間 // paras.add(new TemplateParam("keyword3",createds,"#333")); paras.add(new TemplateParam("remark","點擊此消息查看詳情","#333")); tem.setTemplateParamList(paras); boolean result=sendTemplateMsg(tem); System.out.println(result); return result; } /** * 發送模板消息 * @param template * @return */ public static boolean sendTemplateMsg(Template template){ String token = getToken(template); // String token = ""; boolean flag=false; String requestUrl="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN"; requestUrl=requestUrl.replace("ACCESS_TOKEN", token); String jsonString = template.toJSON();//把String拼接轉爲json類型 JSONObject jsonResult=CommonUtil.httpsRequest(requestUrl, "POST", jsonString); if(jsonResult!=null){ int errorCode=jsonResult.getInt("errcode"); String errorMessage=jsonResult.getString("errmsg"); if(errorCode==0){ flag=true; }else{ System.out.println("模板消息發送失敗:"+errorCode+","+errorMessage); System.out.println(token+"================"); flag=false; } } return flag; } /** *獲取token * @param template * @return */ public static String getToken(Template template){ String requestUrl="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=你的appid&secret=你的appid對應的祕鑰"; JSONObject jsonResult=CommonUtil.httpsRequest(requestUrl, "POST", template.toJSON()); if(jsonResult!=null){ String access_token=jsonResult.getString("access_token"); return access_token; }else{ return ""; } } }
大概就是這樣的,controller層根據上面方法一中相似的。這個本身根據service層的一些來寫就好。
有啥不對的地方請指教,謝謝。