当前位置:   article > 正文

Java后端发送微信小程序模板订阅消息_微信小程序发送订阅消息使用java

微信小程序发送订阅消息使用java

申请注册账号

第一步:首先你需要在微信公众平台 (qq.com)注册一个小程序个人测试账号,然后在首页发布一个小程序成功后如图:

然后就会产生一个小程序的appId和密钥,这两个东西是产生AccessToken和openId的关键点击开发中的开发管理,然后如图查看自己小程序的appId和密钥,密钥的话重置一下就看到了:

 第二步:点击你的订阅消息然后里面有添加模板然然后根据自己的业务需求添加模板或者使用现成的模板就可以产生一模板ID这这个ID发送消息的时候需要,如图:

Java后端发送

第三步:后端代码附上:

myHttpRequesUtil是微信发送工具

  1. package com.longdatech.decryptcode.utils;
  2. import java.io.*;
  3. import java.net.URL;
  4. import java.net.URLConnection;
  5. import java.net.URLEncoder;
  6. import java.util.List;
  7. import java.util.Map;
  8. /**
  9. * @author: qiaolu
  10. * @date 2023/4/7 12:51
  11. */
  12. public class MyHttpRequestUtil {
  13. /**
  14. * 向指定URL发送GET方法的请求
  15. *
  16. * @param url 发送请求的URL
  17. * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
  18. * @return URL 所代表远程资源的响应结果
  19. */
  20. public static String sendGet(String url, String param) {
  21. String result = "";
  22. BufferedReader in = null;
  23. try {
  24. String urlNameString = url + "?" + param;
  25. URL realUrl = new URL(urlNameString);
  26. System.out.println(realUrl);
  27. // 打开和URL之间的连接
  28. URLConnection connection = realUrl.openConnection();
  29. // 设置通用的请求属性
  30. connection.setRequestProperty("accept", "*/*");
  31. connection.setRequestProperty("connection", "Keep-Alive");
  32. connection.setRequestProperty("user-agent",
  33. "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  34. // 建立实际的连接
  35. connection.connect();
  36. // 获取所有响应头字段
  37. Map<String, List<String>> map = connection.getHeaderFields();
  38. // 遍历所有的响应头字段
  39. /* for (String key : map.keySet()) {
  40. System.out.println(key + "--->" + map.get(key));
  41. }*/
  42. // 定义 BufferedReader输入流来读取URL的响应
  43. in = new BufferedReader(new InputStreamReader(
  44. connection.getInputStream()));
  45. String line;
  46. while ((line = in.readLine()) != null) {
  47. result += line;
  48. }
  49. } catch (Exception e) {
  50. System.out.println("发送GET请求出现异常!" + e);
  51. e.printStackTrace();
  52. }
  53. // 使用finally块来关闭输入流
  54. finally {
  55. try {
  56. if (in != null) {
  57. in.close();
  58. }
  59. } catch (Exception e2) {
  60. e2.printStackTrace();
  61. }
  62. }
  63. return result;
  64. }
  65. /**
  66. * @description
  67. * @author: qiaolu
  68. * @date 2023/4/7 12:51
  69. * @param url
  70. * @return
  71. */
  72. public static String sendGet(String url) {
  73. String result = "";
  74. BufferedReader in = null;
  75. try {
  76. String urlNameString = url;
  77. URL realUrl = new URL(urlNameString);
  78. System.out.println(realUrl);
  79. // 打开和URL之间的连接
  80. URLConnection connection = realUrl.openConnection();
  81. // 设置通用的请求属性
  82. connection.setRequestProperty("accept", "*/*");
  83. connection.setRequestProperty("connection", "Keep-Alive");
  84. connection.setRequestProperty("user-agent",
  85. "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  86. // 建立实际的连接
  87. connection.connect();
  88. // 获取所有响应头字段
  89. Map<String, List<String>> map = connection.getHeaderFields();
  90. // 遍历所有的响应头字段
  91. /* for (String key : map.keySet()) {
  92. System.out.println(key + "--->" + map.get(key));
  93. }*/
  94. // 定义 BufferedReader输入流来读取URL的响应
  95. in = new BufferedReader(new InputStreamReader(
  96. connection.getInputStream()));
  97. String line;
  98. while ((line = in.readLine()) != null) {
  99. result += line;
  100. }
  101. } catch (Exception e) {
  102. System.out.println("发送GET请求出现异常!" + e);
  103. e.printStackTrace();
  104. }
  105. // 使用finally块来关闭输入流
  106. finally {
  107. try {
  108. if (in != null) {
  109. in.close();
  110. }
  111. } catch (Exception e2) {
  112. e2.printStackTrace();
  113. }
  114. }
  115. return result;
  116. }
  117. /**
  118. * 向指定 URL 发送POST方法的请求
  119. *
  120. * @param url 发送请求的 URL
  121. * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
  122. * @return 所代表远程资源的响应结果
  123. */
  124. public static String sendPost(String url, String param) {
  125. PrintWriter out = null;
  126. BufferedReader in = null;
  127. String result = "";
  128. try {
  129. URL realUrl = new URL(url);
  130. // 打开和URL之间的连接
  131. URLConnection conn = realUrl.openConnection();
  132. // 设置通用的请求属性
  133. conn.setRequestProperty("accept", "*/*");
  134. conn.setRequestProperty("connection", "Keep-Alive");
  135. conn.setRequestProperty("user-agent",
  136. "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  137. // 发送POST请求必须设置如下两行
  138. conn.setDoOutput(true);
  139. conn.setDoInput(true);
  140. // 获取URLConnection对象对应的输出流
  141. out = new PrintWriter(conn.getOutputStream());
  142. // 发送请求参数
  143. out.print(param);
  144. // flush输出流的缓冲
  145. out.flush();
  146. // 定义BufferedReader输入流来读取URL的响应
  147. in = new BufferedReader(
  148. new InputStreamReader(conn.getInputStream()));
  149. String line;
  150. while ((line = in.readLine()) != null) {
  151. result += line;
  152. }
  153. } catch (Exception e) {
  154. System.out.println("发送 POST 请求出现异常!" + e);
  155. e.printStackTrace();
  156. }
  157. //使用finally块来关闭输出流、输入流
  158. finally {
  159. try {
  160. if (out != null) {
  161. out.close();
  162. }
  163. if (in != null) {
  164. in.close();
  165. }
  166. } catch (IOException ex) {
  167. ex.printStackTrace();
  168. }
  169. }
  170. return result;
  171. }
  172. public static String getUserUathUrl(String appid, String redirectUrl) throws UnsupportedEncodingException {
  173. StringBuffer getcodeUrl = new StringBuffer()
  174. .append("https://open.weixin.qq.com/connect/oauth2/authorize")
  175. .append("?appid=" + appid)
  176. .append("&redirect_uri=" + URLEncoder.encode(redirectUrl, "utf-8"))
  177. .append("&response_type=code")
  178. .append("&scope=snsapi_userinfo")
  179. .append("&state=" + System.currentTimeMillis())
  180. .append("#wechat_redirect");
  181. return getcodeUrl.toString();
  182. }
  183. }

 WxVo类是根据微信api模板消息发送需要参数的实体类

  1. package com.longdatech.decryptcode.utils;
  2. import com.alibaba.fastjson.JSONObject;
  3. import lombok.Data;
  4. /**
  5. * @author qiaolu
  6. * @date 2023/4/7 12:51
  7. */
  8. @Data
  9. public class WxVo {
  10. private String touser;
  11. private String template_id;
  12. private String page;
  13. private String access_token;
  14. private String request_url;
  15. private String miniprogram_stat;
  16. private String lang;
  17. private JSONObject data;
  18. }
  1. package com.longdatech.decryptcode.utils;
  2. import com.alibaba.fastjson.JSONObject;
  3. import lombok.extern.slf4j.Slf4j;
  4. import org.springframework.stereotype.Component;
  5. import org.springframework.web.client.RestTemplate;
  6. import java.io.BufferedReader;
  7. import java.io.IOException;
  8. import java.io.InputStreamReader;
  9. import java.io.PrintWriter;
  10. import java.net.URL;
  11. import java.net.URLConnection;
  12. /**
  13. * @author qiaolu
  14. * @date 2023/4/7 12:51
  15. */
  16. @Slf4j(topic = "WxchatSendUtil")
  17. @Component
  18. public class WxchatSendUtil {
  19. // @Value("${bussiness.appId}")
  20. private static String appId = "你自己的appId";
  21. // @Value("${bussiness.secret}")
  22. private static String secret = "你自己的密钥";
  23. // @Value("${bussiness.orderPlacementNoticeTemplateId}")
  24. private static String orderPlacementNoticeTemplateId = "你自己的模板Id";
  25. /**
  26. * 获取小程序token
  27. *
  28. * @return
  29. */
  30. public static String getAccessToken() {
  31. String url = "https://api.weixin.qq.com/cgi-bin/token?" +
  32. "appid=" + appId + "&secret=" + secret + "&grant_type=client_credential";
  33. PrintWriter out = null;
  34. BufferedReader in = null;
  35. String line;
  36. StringBuffer stringBuffer = new StringBuffer();
  37. try {
  38. URL realUrl = new URL(url);
  39. // 打开和URL之间的连接
  40. URLConnection conn = realUrl.openConnection();
  41. // 设置通用的请求属性 设置请求格式
  42. //设置返回类型
  43. conn.setRequestProperty("contentType", "text/plain");
  44. //设置请求类型
  45. conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
  46. //设置超时时间
  47. conn.setConnectTimeout(1000);
  48. conn.setReadTimeout(1000);
  49. conn.setDoOutput(true);
  50. conn.connect();
  51. // 获取URLConnection对象对应的输出流
  52. out = new PrintWriter(conn.getOutputStream());
  53. // flush输出流的缓冲
  54. out.flush();
  55. // 定义BufferedReader输入流来读取URL的响应 设置接收格式
  56. in = new BufferedReader(
  57. new InputStreamReader(conn.getInputStream(), "UTF-8"));
  58. while ((line = in.readLine()) != null) {
  59. stringBuffer.append(line);
  60. }
  61. JSONObject jsonObject = JSONObject.parseObject(stringBuffer.toString());
  62. return jsonObject.getString("access_token");
  63. } catch (Exception e) {
  64. e.printStackTrace();
  65. }
  66. //使用finally块来关闭输出流、输入流
  67. finally {
  68. try {
  69. if (out != null) {
  70. out.close();
  71. }
  72. if (in != null) {
  73. in.close();
  74. }
  75. } catch (IOException ex) {
  76. ex.printStackTrace();
  77. }
  78. }
  79. return null;
  80. }
  81. public static final String SEND_INFO_URL = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=";
  82. public static void main(String[] args) throws IOException {
  83. // 1、获取 接口调用凭证
  84. RestTemplate restTemplate = new RestTemplate();
  85. String url = SEND_INFO_URL + WxchatSendUtil.getAccessToken();
  86. System.out.println("s:" + WxchatSendUtil.getAccessToken());
  87. //拼接推送的模版
  88. WxVo wxMssVo = new WxVo();
  89. //用户的openId
  90. wxMssVo.setTouser("osCmN4mokDtVkfcipnhaRC1J3_qY");
  91. //订阅消息模板id
  92. wxMssVo.setTemplate_id(orderPlacementNoticeTemplateId);
  93. wxMssVo.setPage("index");
  94. wxMssVo.setMiniprogram_stat("developer");
  95. wxMssVo.setLang("zh_CN");
  96. JSONObject m = new JSONObject();
  97. JSONObject object1 = new JSONObject();
  98. JSONObject object2 = new JSONObject();
  99. JSONObject object3 = new JSONObject();
  100. JSONObject object4 = new JSONObject();
  101. //下面的key是固定的就是"value"自己看接口api然后下面的val值就是发送的内容
  102. object1.put("value", "154956559599");
  103. object2.put("value", "eri0g9i9");
  104. object3.put("value", "30");
  105. object4.put("value", "30");
  106. //自己看自己小程序中生成的模板参数然后然后替换我写的key值
  107. m.put("number2", object1);
  108. m.put("thing1", object2);
  109. m.put("amount3", object3);
  110. m.put("amount4", object4);
  111. wxMssVo.setData(m);
  112. MyHttpRequestUtil.sendPost(url, JSONObject.toJSONString(wxMssVo));
  113. System.out.println(MyHttpRequestUtil.sendPost(url, JSONObject.toJSONString(wxMssVo)));
  114. }
  115. }

到此返回的对象中code为0就是发送成功。

自己手机测试

如果想在自己手机上测试那就必须要下载微信开发工具:微信开放文档如图:

使用微信开发工具登录自己在注册的小程序账号然后生成appjs中复制下面一段代码,不过要在代码中更改自己的模板Id,代码附上

  1. // app.js
  2. App({
  3.   onLaunch() {
  4.   
  5.     // 展示本地存储能力
  6.     const logs = wx.getStorageSync('logs') || []
  7.     logs.unshift(Date.now())
  8.     wx.setStorageSync('logs', logs)
  9.      wx.showModal({
  10.             title'提示',
  11.             content:'请授权开通服务通知',
  12.             showCanceltrue,
  13.             successfunction (ress) {
  14.               if (ress.confirm) { 
  15.                 // console.log('用户点击确定')
  16.                 wx.requestSubscribeMessage({   // 调起消息订阅界面
  17.                   tmplIds: ['自己的模板Id'],
  18.                   success (res) { 
  19.                     console.log('订阅消息 成功 ');
  20.                     console.log(res);
  21.                   },
  22.                   fail (er){
  23.                     console.log("订阅消息 失败 ");
  24.                     console.log(er);
  25.                   }
  26.                 })     
  27.                      
  28.               } else if (ress.cancel) {
  29.                 // console.log('用户点击取消')
  30.               }
  31.             }
  32.           })
  33.     // 登录
  34.     wx.login({
  35.       successres => {
  36.         // 发送 res.code 到后台换取 openId, sessionKey, unionId
  37.        
  38.         console.log(res.code)
  39.       }
  40.     })
  41.   },
  42.   globalData: {
  43.     userInfonull
  44.   }
  45. })

 然后你就消息订阅成功,然后代码会返回一个code值如图:

最后拿着你的code值去生成当前小程序的openId就可以返回上面发送代码进行发送,生成openId代码附上:

  1. public String decryptCode(@RequestParam String code){
  2. log.info("1.0:解密code===>code:" + code);
  3. String result = MyHttpRequestUtil.sendGet(WxConstant.getDesryptCodeUri(code));
  4. JSONObject ojb = JSONObject.parseObject(result);
  5. System.out.println("返回结果:" + ojb);
  6. Set<String> keys = ojb.keySet();
  7. keys.forEach(item->{
  8. System.out.println(item + ":" + ojb.get(item));
  9. });
  10. System.out.println(ojb.getString("openid"));
  11. return ojb.getString("openid");
  12. }

 就可以如图收到消息:

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/在线问答5/article/detail/849400
推荐阅读
相关标签
  

闽ICP备14008679号