微信小程序实现订阅消息通知
创始人
2024-11-06 09:39:19
0

小程序订阅消息(用户通过弹窗订阅)开发指南 | 微信开放文档 (qq.com)

一. 在小程序后台申请模板获得模板ID

在这里插入图片描述

二.相关代码

2.1 编写相关实体类

2.1.1 详细内容类

在这里插入图片描述

@Data @AllArgsConstructor @NoArgsConstructor public class DataClaimVO {     private Map thing4;     private Map name2;     private Map phone_number3;     private Map time5; } 

2.1.2 通知订阅类

此处根据自己的实际业务书写,有多个模板就需要使用泛型

一个模板直接用final即可

@Data public class WxInfoVO {     /**      * 用户openid      */     private String touser;     /**      * 模版id      */     private String template_id;     /**      * 默认      */     private static final String page = "pages/index/index";      /**      * "data": {      * "thing1": "身份证",      * "name2": "风清默",      * "phone_number4": "113132",      * "date3": "2024-4-25"      * },      */     private T data;      /**      * 转小程序类型:developer为开发版;trial为体验版;formal为正式版;默认为正式版      */     private static final String miniprogram_state = "developer";      private static final String lang = "zh_CN";      //category 0 :物品找回通知 通知失主  1:失物认领通知  通知发布(捡到的人)     public WxInfoVO(String touser, Boolean category, T dataVO) {         this.touser = touser;         this.template_id = (!category ? 模板1id : 模板2id);         this.data = dataVO;     }  } 

2.1.3 小程序配置类

@Component @ConfigurationProperties(prefix = "xunhang.wechat.wxinfo") @Data public class WeChatProperties {      private String appid; //小程序的appid     private String secret; //小程序的秘钥     private String mchid; //商户号     private String mchSerialNo; //商户API证书的证书序列号     private String privateKeyFilePath; //商户私钥文件     private String apiV3Key; //证书解密的密钥     private String weChatPayCertFilePath; //平台证书     private String notifyUrl; //支付成功的回调地址     private String refundNotifyUrl; //退款成功的回调地址  }  

2.2 相关工具类

2.2.1 http请求类

public class HttpClientUtil {      static final  int TIMEOUT_MSEC = 5 * 1000;      /**      * 发送GET方式请求      * @param url      * @param paramMap      * @return      */     public static String doGet(String url,Map paramMap){         // 创建Httpclient对象         CloseableHttpClient httpClient = HttpClients.createDefault();          String result = "";         CloseableHttpResponse response = null;          try{             URIBuilder builder = new URIBuilder(url);             if(paramMap != null){                 for (String key : paramMap.keySet()) {                     builder.addParameter(key,paramMap.get(key));                 }             }             URI uri = builder.build();              //创建GET请求             HttpGet httpGet = new HttpGet(uri);              //发送请求             response = httpClient.execute(httpGet);              //判断响应状态             if(response.getStatusLine().getStatusCode() == 200){                 result = EntityUtils.toString(response.getEntity(),"UTF-8");             }         }catch (Exception e){             e.printStackTrace();         }finally {             try {                 response.close();                 httpClient.close();             } catch (IOException e) {                 e.printStackTrace();             }         }          return result;     }      /**      * 发送POST方式请求      * @param url      * @param paramMap      * @return      * @throws IOException      */     public static String doPost(String url, Map paramMap) throws IOException {         // 创建Httpclient对象         CloseableHttpClient httpClient = HttpClients.createDefault();         CloseableHttpResponse response = null;         String resultString = "";          try {             // 创建Http Post请求             HttpPost httpPost = new HttpPost(url);              // 创建参数列表             if (paramMap != null) {                 List paramList = new ArrayList();                 for (Map.Entry param : paramMap.entrySet()) {                     paramList.add(new BasicNameValuePair(param.getKey(), param.getValue()));                 }                 // 模拟表单                 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);                 httpPost.setEntity(entity);             }              httpPost.setConfig(builderRequestConfig());              // 执行http请求             response = httpClient.execute(httpPost);              resultString = EntityUtils.toString(response.getEntity(), "UTF-8");         } catch (Exception e) {             throw e;         } finally {             try {                 response.close();             } catch (IOException e) {                 e.printStackTrace();             }         }          return resultString;     }      /**      * 发送POST方式请求      * @param url      * @param paramMap      * @return      * @throws IOException      */     public static String doPostByJson(String url, T object) throws IOException {         // 创建Httpclient对象         CloseableHttpClient httpClient = HttpClients.createDefault();         CloseableHttpResponse response = null;         String resultString = "";          try {             // 创建Http Post请求             HttpPost httpPost = new HttpPost(url);              if (object != null) {                 //构造json格式数据                 // 将对象转换为JSON字符串                 ObjectMapper objectMapper = new ObjectMapper();                 String jsonStr= JSONUtil.toJsonStr(object);                  StringEntity entity = new StringEntity(jsonStr,"utf-8");                 //设置请求编码                 entity.setContentEncoding("utf-8");                 //设置数据类型                 entity.setContentType("application/json");                 httpPost.setEntity(entity);             }              httpPost.setConfig(builderRequestConfig());              // 执行http请求             response = httpClient.execute(httpPost);              resultString = EntityUtils.toString(response.getEntity(), "UTF-8");         } catch (Exception e) {             throw e;         } finally {             try {                 response.close();             } catch (IOException e) {                 e.printStackTrace();             }         }          return resultString;     }     private static RequestConfig builderRequestConfig() {         return RequestConfig.custom()                 .setConnectTimeout(TIMEOUT_MSEC)                 .setConnectionRequestTimeout(TIMEOUT_MSEC)                 .setSocketTimeout(TIMEOUT_MSEC).build();     }  }  

2.2.2 微信功能类(核心)

这里我使用了 Redis 存储 accessToken

@Component public class WxUtil {      @Autowired     private WeChatProperties weChatProperties;       @Autowired     private StringRedisTemplate stringRedisTemplate;       public void getAccessToken() {         String appid = weChatProperties.getAppid();         String secret = weChatProperties.getSecret();         String grant_type = "client_credential";         Map map = new HashMap();         map.put("appid", appid);         map.put("secret", secret);         map.put("grant_type", grant_type);         String json = HttpClientUtil.doGet(WX_ACCESS_TOKEN_URL, map);         JSONObject jsonObject = JSONObject.parseObject(json);         Integer errcode = jsonObject.getInteger("errcode");         if (errcode == null || errcode == 0) {             String accessToken = jsonObject.getString("access_token");             Integer expiresIn = jsonObject.getInteger("expires_in");             stringRedisTemplate.opsForValue().set(ACCESS_TOKEN_KEY, accessToken, expiresIn, TimeUnit.SECONDS);         } else {             throw new WxServiceException("调用accessToken失败");         }     }       public String sendSubscribeInfo(WxInfoVO wxInfoVO) throws InterruptedException, IOException {         String token = stringRedisTemplate.opsForValue().get(ACCESS_TOKEN_KEY);         if (token == null) {             getAccessToken();         }         Integer t = 0;                  while (token == null && t < 10) {             token = stringRedisTemplate.opsForValue().get(ACCESS_TOKEN_KEY);             t++;             Thread.sleep(100);         }         if (token == null) {             throw new WxServiceException("获取不到accessToken");         }          String json = HttpClientUtil.doPostByJson(WX_SEND_SUBSCRIBE_URL + "?access_token=" + token,wxInfoVO);         return json;      }   } 

2.3 相关依赖

                          org.springframework.boot             spring-boot-starter-data-redis                                         org.apache.commons             commons-pool2                                         org.projectlombok             lombok             true                                cn.hutool         hutool-all         4.5.15                                             com.alibaba             fastjson             2.0.40          

三.执行

@SpringBootTest public class WxinfoApplicationTests {      @Autowired     WxUtil wxUtil;     @Test     public void test() throws IOException, InterruptedException {            Map thing1 = new HashMap<>();         thing1.put("value","身份证");         Map name2 = new HashMap<>();         name2.put("value","风清默");          Map phone_number4 = new HashMap<>();         phone_number4.put("value","1199293");         Map date3 = new HashMap<>();         date3.put("value",LocalDateTime.now());          DatafoundVO dataVO = new DatafoundVO(thing1, name2, phone_number4,date3);         WxInfoVO wxInfoVO = new WxInfoVO(用户openid,false,dataVO);        // System.out.println(JSONUtil.toJsonStr(wxInfoVO));          System.out.println(wxUtil.sendSubscribeInfo(wxInfoVO));     } } 

成功

在这里插入图片描述

相关内容

热门资讯

八分钟了解!newpoker怎... 八分钟了解!newpoker怎么安装脚本,哈糖大菠萝能开挂吗,指南书教程(有挂分析)1、哈糖大菠萝能...
方案辅助!微信小程序微乐破解器... 方案辅助!微信小程序微乐破解器2024!解谜真的是有辅助教程(有挂细节)1、进入到微信小程序微乐破解...
第9分钟了解!德普之星有辅助软... 第9分钟了解!德普之星有辅助软件吗,德州局透视脚本,步骤教程(有挂神器)运德普之星有辅助软件吗辅助工...
窍要辅助!洞庭茶苑app辅助!... 窍要辅助!洞庭茶苑app辅助!关于存在有辅助神器(有挂辅助)1.洞庭茶苑app辅助 选牌创建新账号,...
七分钟了解!wepoker怎么... 七分钟了解!wepoker怎么开辅助,wepoker透视脚本免费app,绝活儿教程(有挂细节)1、w...
窍要辅助!嘟咪互动有挂吗!开挂... 窍要辅助!嘟咪互动有挂吗!开挂是有辅助软件(有挂总结)窍要辅助!嘟咪互动有挂吗!开挂是有辅助软件(有...
1分钟了解!wepoker辅助... 1分钟了解!wepoker辅助器最新版本更新内容,德普之星私人局辅助免费,办法教程(有挂辅助)wep...
大纲辅助!心悦海南苹果版辅助器... 大纲辅助!心悦海南苹果版辅助器!关于是有辅助工具(有挂攻略)1、玩家可以在心悦海南苹果版辅助器线上大...
指南辅助!小程序广东雀神智能插... 指南辅助!小程序广东雀神智能插件安装下载!解谜真的是有辅助技巧(新版有挂)运小程序广东雀神智能插件安...
第九分钟了解!wepoker作... 第九分钟了解!wepoker作弊辅助,wpk辅助购买,步骤教程(新版有挂)1、完成wepoker作弊...