导语
  有很多场景下,需要要对接微信小程序的开发,在使用的过程中,会出现各种各样的问题,本人总结了关于如何调用微信小程序模板订阅消息的相关实现总结如下

微信订阅消息官网

  首先要求系统,在不同的场景下,发送不同的微信订阅消息。第一步需要实现的就是如何将订阅消息发送出去,通过官网上的描述,先编写了一个通用的请求方法。使用的最为传统的调用方法,当然也可以使用其他的方式进行优化对于Java 网络调用的优化。这里系统要求并不是太高,所以使用的最简单的方式来实现。

编写一个通用请求方法

 /*** http请求方法* @param requestUrl* @param requestMethod* @param outputStr* @return*/public static String httpsRequest(String requestUrl, String requestMethod, String outputStr) {try {URL url = new URL(requestUrl);HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();conn.setDoOutput(true);conn.setDoInput(true);conn.setUseCaches(false);conn.setRequestMethod(requestMethod);conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");if (outputStr != null) {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();return buffer.toString();} catch (ConnectException ce) {System.out.println("连接超时:{}");} catch (Exception e) {System.out.println("https请求异常:{}");}return null;}

获取Token

  根据官网文档,调用接口之前首先要获取到access_token的值,Token

public class Token
{private String accessToken;private int expiresIn;private long getTokenTime;public Token() {}public Token(String accessToken, int expiresIn, long getTokenTime) {this.accessToken = accessToken;this.expiresIn = expiresIn;this.getTokenTime = getTokenTime;}public long getGetTokenTime(){return this.getTokenTime;}public void setGetTokenTime(long getTokenTime){this.getTokenTime = getTokenTime;}public String getAccessToken(){return this.accessToken;}public void setAccessToken(String accessToken){this.accessToken = accessToken;}public int getExpiresIn(){return this.expiresIn;}public void setExpiresIn(int expiresIn){this.expiresIn = expiresIn;}}

  这里由于涉及到一个超时时间的问题,所以使用了一个简单的技巧将Token的操作进行了缓存,利用比较两个时间的方式来判断是否过期,需要重新请求Token,来减少Token调用的操作内容。

    /*** 获取有效的token* @return*/public static Token getToken() {if (token != null) {if (token.getGetTokenTime() + token.getExpiresIn() > new Date().getTime()) {return token;}}//记得补充上appid和appsecretString appid="appid";String secret="appsecret";String result = httpsRequest("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret, "GET", null);//new JSONObject();JSONObject jsonObject = JSONObject.parseObject(result);if (jsonObject != null) {try {token = new Token();token.setGetTokenTime(new Date().getTime());token.setAccessToken(jsonObject.getString("access_token"));token.setExpiresIn(jsonObject.getInteger("expires_in"));} catch (JSONException e) {token = null;log.error("获取token失败 errcode:{} errmsg:{}", Integer.valueOf(jsonObject.getInteger("errcode")), jsonObject.getString("errmsg"));}}return token;}

发送模板消息

  获取到Token就要开始发发送模板消息了

   定义消息体

public class TemplateParam
{private String key;private String value;public TemplateParam(String key, String value){this.key=key;this.value=value;}public String getValue() {return value;}public void setValue(String value) {this.value = value;}public String getKey() {return key;}public void setKey(String key) {this.key = key;}
}
public class Template
{private String touser;private String template_id;private String page;private List<TemplateParam> templateParamList;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 template_id) {this.template_id = template_id;}public String getPage() {return page;}public void setPage(String page) {this.page = page;}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.template_id)).append(",");buffer.append(String.format("\"page\":\"%s\"", this.page)).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\"},", param.getKey(), param.getValue()));}else{buffer.append(String.format("\"%s\": {\"value\":\"%s\"}", param.getKey(), param.getValue()));}}buffer.append("}");buffer.append("}");return buffer.toString();}public List<TemplateParam> getTemplateParamList() {return templateParamList;}public void setTemplateParamList(List<TemplateParam> templateParamList) {this.templateParamList = templateParamList;}
}
   /*** 发送模板消息** @param template* @return*/public static boolean sendTemplateMsg(Template template) {boolean flag = false;String requestUrl = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN";requestUrl = requestUrl.replace("ACCESS_TOKEN", getToken().getAccessToken());System.out.println(template.toJSON());String Result = httpsRequest(requestUrl, "POST", template.toJSON());System.out.println(Result);JSONObject jsonResult =  JSONObject.parseObject(Result);if (jsonResult != null) {int errorCode = jsonResult.getInteger("errcode");String errorMessage = jsonResult.getString("errmsg");if (errorCode == 0) {flag = true;} else {System.out.println("模板消息发送失败:" + errorCode + "," + errorMessage);}}return flag;}

封装内容

    public void signTemplate(SendTemplateMessageEvent sendTemplateMessageEvent) {SignSuccessMeg source = (SignSuccessMeg) sendTemplateMessageEvent.getSource();List<TemplateParam> paras=new ArrayList<>();paras.add(new TemplateParam("thing1",source.getTitle()));paras.add(new TemplateParam("thing3", source.getContent()));paras.add(new TemplateParam("thing4", source.getUnit()));paras.add(new TemplateParam("time5",DateUtils.dateTimeNow("yyyy-MM-dd HH:mm:ss")));paras.add(new TemplateParam("thing6",source.getRemark()));WxgzhUtil.sendMessageUtils("ouIH35CLsIBqwsZMqxx30Tzu35AI","88IGBsWFJ5CJhNePmVb8H2ljXYeO5YA6cM2znFALXdY",paras);}

测试

    //  测试public static void sendMessageUtils(String openid,String temp_id,List<TemplateParam> paras) {Template template=new Template();//这里填写模板IDtemplate.setTemplate_id(temp_id);//这里填写用户的openidtemplate.setTouser(openid);//这里填写点击订阅消息后跳转小程序的界面template.setPage("/pages/index/index");template.setTemplateParamList(paras);sendTemplateMsg(template);}

Spring Boot 实现微信小程序订阅模板消息相关推荐

  1. 微信小程序订阅模板消息

    1.登录管理员后台,订阅消息,选择模板或者申请模板 2. 开发管理,开发设置,开启消息推送,并验证服务器 3. 开发获取获取模板列表接口,和 测试消息发送接口 4. 前端根据接口配置授权弹窗页,获取用 ...

  2. 用Spring Boot完成微信小程序登录

    使用Spring Boot完成微信小程序登录 由于微信最近的版本更新,wx.getUserInfo()的这个接口即将失效,将用wx.getUserProfile()替换,所以近期我也对自己的登录进行更 ...

  3. spring boot接收微信小程序上传的文件

    spring boot接收微信小程序上传的文件,首先前台传给我们后端的不是一个路径,而是以一个文件类型传递给我,这时我们在controller层接收时就可以用MultipartFile进行接收,如果接 ...

  4. php+实现群发微信模板消息_使用php实现微信小程序发送模板消息(附代码)

    本篇文章给大家带来的内容是关于使用php实现微信小程序发送模板消息(附代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助. 本章将会简单说一下微信小程序的模板消息发送,相对来说比较简 ...

  5. 微信小程序发送模板消息踩的坑

    在微信的微信小程序中,微信提供了和微信服务号相同的模板消息功能. 但是,虽然都是发送模板消息,小程序和服务号的模板消息的使用还是有差别的. 对于微信服务号的模板消息只要通过查看文档就能够知道我们使用模 ...

  6. php怎么实现发送给指定用户,微信小程序 实现模板消息群发、发送给指定用户...

    1. 需求 最近在做一款拼课类小程序,大概需求就是分享课程页面给好友,好友参与达到一定数量后则拼课成功. 好友参与后会给分享者发送一条模板消息 参与人数满足后(拼课成功)会给分享者发送一条模板消息 管 ...

  7. 《微信小程序——发送模板消息》详细步骤

    第一步:获取access_token 第一步详情:因为access_token在微信公众号还是小程序,在一个月之内都有获取次数的限制,并且一个access_token只有2小时的有效期:所以每当我们获 ...

  8. (附源码)spring boot基于微信小程序的口腔诊所预约系统 毕业设计 201738

    小程序springboot口腔诊所预约系统 摘  要 随着我国经济迅速发展,人们对手机的需求越来越大,各种手机软件也都在被广泛应用,但是对于手机进行数据信息管理,对于手机的各种软件也是备受用户的喜爱, ...

  9. 小程序+spring boot记账微信小程序 毕业设计-附源码180815

    记账微信小程序 摘  要 随着我国经济迅速发展,人们对手机的需求越来越大,各种手机软件也都在被广泛应用,但是对于手机进行数据信息管理,对于手机的各种软件也是备受用户的喜爱,记账微信小程序被用户普遍使用 ...

最新文章

  1. Ansible的安装及部署
  2. 科学:揭示自由意志的生物学本质
  3. c语言原始,[蓝桥杯][历届试题]回文数字 最原始的方法(C语言代码)
  4. 亮剑吧,掏出你吃灰的单片机板子。
  5. Python 数据分析三剑客之 Pandas(十):数据读写
  6. LeetCode 1755. 最接近目标值的子序列和(状态枚举 + 双指针)
  7. 深入研究微服务架构——第二部分
  8. VsCode crtl + 鼠标右键 python代码无法跳转
  9. DSP与FPGA的SRIO通信实现
  10. Java开发规范之常量定义篇
  11. 上帝视角-我是一个线程『转』
  12. html 获取ie浏览器,用C#从,IE浏览器中获取HTML文档
  13. Android快速开发,十个最常用的框架
  14. vb6使用WinRAR压缩和解压文件
  15. 教你做表格(史上最全)
  16. linux判断季末日期,C#根据当前时间确定日期范围(本周、本月、本季度、本年度)...
  17. WPF 开源二维绘画小工具 GeometryToolDemo 项目
  18. 为了让5G更省电,这家设备商秀出黑科技
  19. 光线追踪渲染实战(四):微平面理论与迪士尼 BRDF,严格遵循物理!
  20. 香港5G自动驾驶车开测,明年大规模推出5G服务

热门文章

  1. hadoop php mysql_PHP+Hadoop+Hive+Thrift+Mysql实现数据统计分析
  2. leetcode mysql 排名_GitHub - nimphy/leetcode-Mysql
  3. 养老不用愁,这种机器人可以让老年人自主地进行日常生活
  4. vue+node全栈移动商城【10】注册页面传值到node中间件
  5. Android小知识-了解下Android系统的显示原理
  6. Python3自定义json逐层解析器
  7. java八大基本类型介绍
  8. pandas打开csv表格表头错位问题解决
  9. OSGi 的核心配置、动态化及问题
  10. NOIP2011选择客栈[递推]