1. 程式人生 > >微信服務號模板訊息推送

微信服務號模板訊息推送

一.微信服務號新建模板

 

二.建立模板訊息pojo

import java.util.HashMap;
import net.sf.json.JSONObject;

public class TemplateData {
	private String touser;//推送給誰 openID
	private String template_id;//模板ID
	private String url;//跳轉連結地址
	private String topcolor;//顏色設定
	private TemplateItem data;//資料封裝
	public static TemplateData New() {
		return new TemplateData();
	}
	private TemplateData() {
		this.data = new TemplateItem();
	}
	public String getTouser() {
		return touser;
	}
	public TemplateData setTouser(String touser) {
		this.touser = touser;
		return this;
	}
	public String getTemplate_id() {
		return template_id;
	}
	public TemplateData setTemplate_id(String template_id) {
		this.template_id = template_id;
		return this;
	}
	public String getUrl() {
		return url;
	}
	public TemplateData setUrl(String url) {
		this.url = url;
		return this;
	}
	public String getTopcolor() {
		return topcolor;
	}

	public TemplateData setTopcolor(String topcolor) {
		this.topcolor = topcolor;
		return this;
	}
	public TemplateItem getData() {
		return data;
	}
	public TemplateData add(String key, String value, String color){
		data.put(key, new Item(value, color));
		return this;
	}

	/**
	 * 直接轉化成jsonString
	 * @return {String}
	 */
	 public String build() {
		 return JSONObject.fromBean(this).toString();
	 }
	 public class TemplateItem extends HashMap<String, Item> {

		 private static final long serialVersionUID = -3728490424738325020L;

		 public TemplateItem() {}

		 public TemplateItem(String key, Item item) {
			 this.put(key, item);
		 }
	 }
	 public class Item {
		 private Object value;
		 private String color;

		 public Object getValue() {
			 return value;
		 }
		 public void setValue(Object value) {
			 this.value = value;
		 }
		 public String getColor() {
			 return color;
		 }
		 public void setColor(String color) {
			 this.color = color;
		 }

		 public Item(Object value, String color) {
			 this.value = value;
			 this.color = color;
		 }
	 }
}

二.建立傳送方法

    /**
	 * 獲取需要推送的引數推送模板訊息
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/sendTemplateData")
	@ResponseBody
	public Map<String,Object> sendTemplateData(HttpServletRequest request, HttpServletResponse response) throws Exception{
		System.out.println("/sendTemplateData");
		Map<String,Object> map = new HashMap<String, Object>();
		//獲取引數
		String msgType = this.getString(request, "msgType");
		String json="";
		String time = this.getString(request, "time");
		String remark = this.getString(request, "remark");
		String content = this.getString(request, "content");
		String templateId = "6ZioBRrRGXZVqgN0IWweTA6kq30Hh9QQr61DReKy9Tg";//模板id
		String openId = "osnEq1DJWPHgsMzS6RXRCUGv9OIo";//通知給誰
		/* 新訂單提醒
		 * 
			{{first.DATA}} 
			內容:{{keyword1.DATA}} 
			時間:{{keyword2.DATA}} 
			{{remark.DATA}}
		 */
		if(msgType.equals("1")){//採購單
			
			json=TemplateData.New()
				.setTouser(openId)//hm.gao
				.setTemplate_id(templateId)
                  //.setTopcolor("#743A3A")
                  //.setUrl(url)
				.add("first","有新的採購資訊","#000000")
				.add("keyword1",content, "#00b0f0")
				.add("keyword2",time, "#000000")
				.add("remark", remark, "#00b0f0")
				.build();
		}else if(msgType.equals("0")){//訂單通知報價
			json=TemplateData.New()
					.setTouser(openId)
					.setTemplate_id(templateId)
                      //.setTopcolor("#743A3A")
                      //.setUrl(url)
					.add("first","有新的訂單資訊","#000000")
					.add("keyword1",content, "#ff0000")
					.add("keyword2",time, "#000000")
					.add("remark", remark, "#ff0000")
					.build();
		}
		JSONObject result = baseMPService.sendTemplateInfo(super.getToken(), json);
		String success = result.getString("errmsg");
		if(success.equals("ok")){
			//是否推送成功處理
			map.put("rtn", "ok");
		}else{
			map.put("rtn", "error");
			map.put("message", success);
		}
		return map;
	}
}

四.底層請求方法

	@Override
	public JSONObject sendTemplateInfo(String token, String json) {
		String s = post(Constant.send_message_url.replace("ACCESS_TOKEN", token), json);
		JSONObject result = JSONObject.fromString(s);
		return result;
	}
	public String post(String url, String data) {
		
		try {
			
			Proxy px = getProxy();
			
			if (px != null && StringUtils.isNotEmpty(px.getHost())) {
				
				String proxy = px.getHost();
				int port = px.getPort();
				
				System.setProperty("proxyType", "4");
				System.setProperty("proxyPort", Integer.toString(port));
				System.setProperty("proxyHost", proxy);
				System.setProperty("proxySet", "true");
			}
			
			  SSLContext sc = SSLContext.getInstance("SSL");
			   
			  //指定信任https
			  sc.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom());
			  
			  URL console = new URL(url);
			  
			  HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
			  
			  conn.setSSLSocketFactory(sc.getSocketFactory());
			  
			  conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
			  
			  conn.setRequestMethod("POST");
			  
			  conn.setDoOutput(true);
			  
			  if (data != null) {
				  
				  OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
				  
				  out.write(data);
				  
				  out.flush();
				  
				  out.close();
			  }
			  
			  conn.connect();
			  
			  System.out.println("返回結果:"+conn.getResponseMessage());
			   
			  InputStream is = conn.getInputStream();
			  
			  BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
			  
			  StringBuffer sb = new StringBuffer();
			  
			  String curLine = null;
			  
			  while ((curLine = reader.readLine()) != null) {
				  
				  sb.append(curLine);
				  
			  }
			  is.close();
			  if (px != null && StringUtils.isNotEmpty(px.getHost())) {
					System.clearProperty("proxyType");
					System.clearProperty("proxyPort");
					System.clearProperty("proxyHost");
					System.clearProperty("proxySet");
			  }
				  
			  
			  return sb.toString();
			
		} catch (Exception e) {
			
			System.out.println("------------呼叫微信介面失敗--------------:" + e.getMessage());
			
			e.printStackTrace();
			
			throw new RuntimeException(e.getMessage());
		}
	}
	class TrustAnyTrustManager implements X509TrustManager {
		 
		  public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
			  
		  }
		  
		  public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
			  
		  }
		   
		  public X509Certificate[] getAcceptedIssuers() {
			  
			  return new X509Certificate[]{};
		  }
		}
		   
	  class TrustAnyHostnameVerifier implements HostnameVerifier {
		  
		  public boolean verify(String hostname, SSLSession session) {
			  
			  return true;
			  
		  }
	  }

五.結果