java开发微信模板消息推送
概述
详细
概述
微信公众平台开始支持前端网页,大家可能看到很多网页上都有分享到朋友圈,关注微信等按钮,点击它们都会弹出一个窗口让你分享和关注,这个是怎么实现的呢?今天就给大家讲解下如何在微信公众平台前端网页上添加分享到朋友圈,关注微信号等按钮。
一、前言
(1)适合人群
1,JAVA服务端开发人员
2,初级人员开发人员
3,了解spring springboot + maven.
4,了解微信开发
(2)你需要准备什么?
1,积极主动学习
2,微信公众号开发基本流程
3,java后端几大框架掌握如(spring springboot maven )
二、前期准备工作
软件环境:eclipse
官方下载:https://www.eclipse.org/downloads/
1 ,基本需求
微信模板消息推送订单购买成功推送
三、项目结构
四、使用规则
-
所有服务号都可以在功能->添加功能插件处看到申请模板消息功能的入口
-
需要选择公众账号服务所处的2个行业,每月可更改1次所选行业
-
在所选择行业的模板库中选用已有的模板进行调用
-
每个账号可以同时使用25个模板
-
当前每个账号的模板消息的日调用上限为10万次,单个模板没有特殊限制,以公众号MP后台开发者中心页面中标明的数字为准
五、接口文档规范
-
模板消息调用时主要需要模板ID和模板中各参数的赋值内容
-
模板中参数内容必须以".DATA"结尾,否则视为保留字
-
模板保留符号"{{ }}"
-
测试公众号可以随意定义,正式的必须用模板库中的
以下是我使用的模板消息示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | package cn.demo.Template; /** * 模板详细信息 */ public class Data_first { private String value; private String color; 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; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | /** * 获取acctoken * @return */ private String getAccessToken() { if (access_token != null && (access_token_updateTime + 5400000 ) > new Date().getTime()) return access_token; AccessTokenResult accessTokenResult = restTemplate.getForObject(String.format( "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s" , APPID, SECRET), AccessTokenResult. class ); if (accessTokenResult.getErrcode() == null || accessTokenResult.getErrcode().equals( "0" )) { access_token_updateTime = new Date().getTime(); access_token = accessTokenResult.getAccess_token(); } else System.out.println( "error:" + accessTokenResult); return accessTokenResult.getAccess_token(); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | /** * 微信请求 - 信任管理器 */ public 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 ; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | /** * 发送https请求 * @param requestUrl 请求地址 * @param requestMethod 请求方式(GET、POST) * @param outputStr 提交的数据 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值) */ public class WeixinUtil { public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) { JSONObject jsonObject = null ; StringBuffer buffer = new StringBuffer(); try { TrustManager[] tm = { new MyX509TrustManager() }; SSLContext sslContext = SSLContext.getInstance( "SSL" , "SunJSSE" ); sslContext.init( null , tm, new SecureRandom()); SSLSocketFactory ssf = sslContext.getSocketFactory(); URL url = new URL(requestUrl); HttpsURLConnection httpUrlConn = (HttpsURLConnection)url.openConnection(); httpUrlConn.setSSLSocketFactory(ssf); httpUrlConn.setDoOutput( true ); httpUrlConn.setDoInput( true ); httpUrlConn.setUseCaches( false ); httpUrlConn.setRequestMethod(requestMethod); if ( "GET" .equalsIgnoreCase(requestMethod)) { httpUrlConn.connect(); } if (outputStr != null ) { OutputStream outputStream = httpUrlConn.getOutputStream(); outputStream.write(outputStr.getBytes( "UTF-8" )); outputStream.close(); } InputStream inputStream = httpUrlConn.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8" ); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String str = null ; while ((str = bufferedReader.readLine()) != null ) { buffer.append(str); } bufferedReader.close(); inputStreamReader.close(); inputStream.close(); inputStream = null ; httpUrlConn.disconnect(); jsonObject = JSONObject.fromObject(buffer.toString()); } catch (ConnectException ce) { // logger.error("Weixin server connection timed out."); } catch (Exception e) { // logger.error("https request error:{}", e); } return jsonObject; } } |
下面请求微信发送模板消息
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | /** * * 发送模板消息 * appId 公众账号的唯一标识 * appSecret 公众账号的密钥 * openId 用户标识 */ public void send_template_message(String appId, String openId) { String access_token = getAccessToken(); String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token; NewOrdersTemplate temp = new NewOrdersTemplate(); Data data = new Data(); Data_first first = new Data_first(); Data_Day Day = new Data_Day(); Data_orderId orderId = new Data_orderId(); Data_orderType orderType = new Data_orderType(); Data_customerName customerName = new Data_customerName(); Data_customerPhone customerPhone = new Data_customerPhone(); Data_remark remark = new Data_remark(); first.setValue( "收到一个新的订单" ); first.setColor( "#173177" ); Day.setValue( "14时56分" ); Day.setColor( "#173177" ); orderId.setValue( "1002" ); orderId.setColor( "#173177" ); orderType.setValue( "订位" ); orderType.setColor( "#173177" ); customerName.setValue( "陈丑丑" ); customerName.setColor( "#173177" ); customerPhone.setValue( "13222222222" ); customerPhone.setColor( "#173177" ); remark.setValue( "请及时处理您的订单" ); remark.setColor( "#173177" ); data.setFirst(first); data.setDay(Day); data.setOrderId(orderId); data.setOrderType(orderType); data.setCustomerName(customerName); data.setCustomerPhone(customerPhone); data.setRemark(remark); temp.setTouser(openId); temp.setTemplate_id( "C0BHxo_YLQ9TV2XytzqucHI7dNJytq0aAxYkBkqZTiw" ); temp.setUrl( "http://weixin.qq.com/download" ); temp.setTopcolor( "#173177" ); temp.setData(data); String jsonString = JSONObject.fromObject(temp).toString().replace( "day" , "Day" ); JSONObject jsonObject = WeixinUtil.httpRequest(url, "POST" , jsonString); System.out.println(jsonObject); int result = 0 ; // logger.info("模板消息发送结果:"+result}; } |
下一步请求conterller因为我参数写死在conterller里面
1 2 3 4 5 6 7 8 9 | @RequestMapping ( "/test" ) @ResponseBody public String testDemo() { String openId = "oJilVv4k-DXciUhIsC2wSXJs2J" ; String appId = "wx1ff244a71563c" ; send_template_message(appId, openId); return appId; } |
六、运行效果
访问这地址 http://localhost:8080/app/tetst 测试结果如图
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· Windows编程----内核对象竟然如此简单?