一.微信服务号新建模板
二.建立模板消息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;
}
}
五.结果