微信公众号消息推送开发(模板消息):准备工作[公众平台环境配置](一)
前言:
根据公众平台提供api,需要注意以下几点:
①,access_token需要缓存
②,需要按照所选模板封装对应的数据
③,推送消息必须条件:模板id,被推送者的openid
模板消息接口
开发实现:
下面以实现绑定推送消息为例:
①:获取access_token(由于每天access_token获取有次数限制,需要缓存)
/*** 获取access_token* @param AppId* @param AppSecret* @return* @throws Exception*/public static String getAccessToken(String AppId,String AppSecret)throws BusinessException{String access_tokenurl="https://api./cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";access_tokenurl=access_tokenurl.replace("APPID",AppId);access_tokenurl=access_tokenurl.replace("APPSECRET",AppSecret);String accesstoken="";JSONObject jsonObject = WeiXinUtil.httpsRequest(access_tokenurl,"GET",null);if (jsonObject !=null){accesstoken=jsonObject.getString("access_token");}return accesstoken;}
②,创建模板消息实体对象(由于应用模板较多,这里定义一个javabean.这个根据个人情况定义)
package com.steno.xf.weixin.vo;import org.apache.lucene.document.StringField;/*** 公众号推送消息封装*/public class GZHMsgVo {private String touser;private String templateId;private String title;private String remark;private String keyword1;private String keyword2;private String keyword3;private String keyword4;private String keyword5;//是否跳转相关private String smUrl;private String smAppid;private String smpagepath;//备注字体颜色private String remakColor;//标题字体颜色private String titleColor;//....省略geter/setter....//}
注:根据个人喜好,也可以把keyword封装成集合
③,调用模板消息接口(AccessToken为①获取的值)
GZHMsgVo msgVo = new GZHMsgVo();msgVo.setTemplateId(ReferenceTool.getItemvalue(XfReferenceConstrants.GZHMSG_BANGDING_ID));//模板idmsgVo.setTouser(gzhopenId);//用户openidmsgVo.setTitle("恭喜!您的新房账号已成功绑定微信");msgVo.setKeyword1(vo.getUsername());msgVo.setKeyword2("接收平台通知");msgVo.setKeyword3(DateFormatUtil.getNowDateTime());msgVo.setRemark("和谐共享,方便你我");msgVo.setRemakColor("EE3D11");WeiXinUtil.sendMessagePush(msgVo,AccessToken);
④,WeiXinUtil.sendMessagePush()
调用发送模板消息api:
https://api./cgi-bin/message/template/send?access_token=ACCESS_TOKEN
/*** 公众号推送封装* @param vo* @param ACCESS_TOKEN* @throws Exception*/public static String sendMessagePush(GZHMsgVo vo,String ACCESS_TOKEN){JSONObject json=new JSONObject();JSONObject text=new JSONObject();JSONObject first=new JSONObject();JSONObject remark=new JSONObject();if (vo.getTouser()==null){return "touser不能为空";}if (vo.getTemplateId()==null){return "TemplateId不能为空";}json.put("touser",vo.getTouser());json.put("template_id",vo.getTemplateId());first.put("value",vo.getTitle());remark.put("value",vo.getRemark());if (vo.getKeyword1()!=null){JSONObject keyword1=new JSONObject();keyword1.put("value",vo.getKeyword1());text.put("keyword1",keyword1);}if (vo.getKeyword2()!=null){JSONObject keyword2=new JSONObject();keyword2.put("value",vo.getKeyword2());text.put("keyword2",keyword2);}if (vo.getKeyword3()!=null){JSONObject keyword3=new JSONObject();keyword3.put("value",vo.getKeyword3());text.put("keyword3",keyword3);}if (vo.getKeyword4()!=null){JSONObject keyword4=new JSONObject();keyword4.put("value",vo.getKeyword4());text.put("keyword4",keyword4);}if (vo.getKeyword5()!=null){JSONObject keyword5=new JSONObject();keyword5.put("value",vo.getKeyword5());text.put("keyword5",keyword5);}if (vo.getTitleColor() !=null){first.put("color",vo.getTitleColor());}if (vo.getRemakColor() !=null){remark.put("color",vo.getRemakColor());}text.put("first", first);text.put("remark",remark);json.put("data", text);//发送模板消息String sendUrl="https://api./cgi-bin/message/template/send?access_token=ACCESS_TOKEN";sendUrl=sendUrl.replace("ACCESS_TOKEN",ACCESS_TOKEN);String jsonstringParm =json.toString();JSONObject object=WXAdvancedUtil.httpsRequest(sendUrl,"POST",jsonstringParm);return object.toString();}
⑤,WXAdvancedUtil.httpsRequest(sendUrl,"POST",jsonstringParm)
/*** 发送http请求* @param requestUrl* @param requestMethod* @param outputStr* @return*/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();conn.disconnect();jsonObject = JSONObject.fromObject(buffer.toString());} catch (ConnectException ce) {ce.printStackTrace();} catch (Exception e) {e.printStackTrace();}return jsonObject;}
效果:
微信公众号消息推送开发(模板消息):点击推送消息跳转到网页或者小程序(三)