微信開發---微信模板訊息傳送
阿新 • • 發佈:2019-02-18
剛開始做這個模板訊息開發的時候參考了很多大神的部落格,講解的也是比較的詳細,但是在工具類這一塊都沒有詳細的說,因為開發的經驗少,對這些常用的工具類不是很瞭解,所以走了很多的彎路,所以今天把整個的詳細流程貼上來,給和我一樣的初學者一個參考。
1 模板訊息由於模板選取不同需要傳入引數的名稱、值、引數個數也不同首先要封裝2個實體
這一塊中最重要的是對資料的json處理,我也是完全拷貝的package com.Model; import java.util.List; public class Template { // 訊息接收方 private String toUser; // 模板id private String templateId; // 模板訊息詳情連結 private String url; // 訊息頂部的顏色 private String topColor; // 引數列表 private List<TemplateParam> templateParamList; 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 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 List<TemplateParam> getTemplateParamList() { return templateParamList; } public void setTemplateParamList(List<TemplateParam> templateParamList) { this.templateParamList = templateParamList; } }
2、這是訊息傳送的程式碼package com.Model; 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; } }
4、這一部分是我耗時最多的部分工具類public @ResponseBody Map<String, Object> classremind(HttpServletRequest request,Model model){ Map<String, Object> map=new HashMap<>(); Template tem=new Template(); tem.setTemplateId("");//訊息模板的id tem.setTopColor("#00DD00"); tem.setToUser(user.getOpenid());//接收人的openid tem.setUrl(""); List<TemplateParam> paras=new ArrayList<TemplateParam>(); paras.add(new TemplateParam("first","訊息內容","#FF3333")); paras.add(new TemplateParam("keyword1","對應的模板中的訊息","#0044BB")); paras.add(new TemplateParam("keyword2","對應的模板的訊息","#0044BB")); paras.add(new TemplateParam("Remark","請準時收聽直播課程!","#AAAAAA")); tem.setTemplateParamList(paras); String token=GlobalConstant.access_token;\\根據你們自己的方法獲取token String requestUrl="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN"; requestUrl=requestUrl.replace("ACCESS_TOKEN", token); JSONObject jsonResult=Util.httpsRequest(requestUrl, "POST", tem.toJSON()); if(jsonResult!=null){ int errorCode=jsonResult.getInteger("errcode"); String errorMessage=jsonResult.getString("errmsg"); if(errorCode==0){ map.put("status",0); }else{ log.info("模板訊息傳送失敗:"+errorCode+","+errorMessage); map.put("status", 1); map.put("info", "提醒失敗,請稍候再試!"); } } return map; }
package com.util;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONObject;
import com.yiwangjiankang.Controller.ZhiboController;
public class Util {
private static Logger log = LoggerFactory.getLogger(ZhiBoUtil.class);
public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
JSONObject jsonObject = null;
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 conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(ssf);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
// 設定請求方式(GET/POST)
conn.setRequestMethod(requestMethod);
// 當 outputStr 不為 null 時,向輸出流寫資料
if (null != outputStr) {
OutputStream outputStream = conn.getOutputStream();
// 注意編碼格式
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 從輸入流讀取返回內容
InputStream inputStream = conn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
StringBuffer buffer = new StringBuffer();
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
// 釋放資源
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
inputStream = null;
conn.disconnect();
jsonObject = JSONObject.parseObject(buffer.toString());
} catch (ConnectException ce) {
log.error(" 連線超時:{}", ce);
} catch (Exception e) {
log.error("https 請求異常:{}", e);
}
return jsonObject;
}
}
\\這個MyX509TrustManager()是一個介面,自己必須新增一個實現類才可以直接使用,如下
class MyX509TrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException
{
}
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException
{
}
public X509Certificate[] getAcceptedIssuers()
{
return null;
}
}
完整的就是這樣了,裡面可能摻雜了一些我自己工程裡面的程式碼,希望能對大家有所幫助!有問題也希望和大家多多交流