当前位置:   article > 正文

java编写微信小程序消息提醒推送_微信小程序消息推送java

微信小程序消息推送java

微信小程序官方文档:发送订阅消息 | 微信开放文档

一.先制定模板,我以已删除的模板为例

二.java后台创建小程序 Vo类,用于封装传送的参数。

  1. import lombok.Data;
  2. @Data
  3. public class TemplateDataVo {
  4. /*微信文档中要求的格式 "data": { "name01": {"value": "某某"},"thing01": {"value": "广州至北京"
  5. } ,"date01": {"value": "2018-01-01"}
  6. }*/
  7. private String value;
  8. }
  1. import lombok.Data;
  2. import java.util.Map;
  3. /*
  4. * 小程序推送所需数据
  5. * */
  6. @Data
  7. public class WxMssVo {
  8. private String touser;//用户openid
  9. private String template_id;//模版id
  10. private String page = "pages/index/index";//默认跳到小程序首页
  11. // private String emphasis_keyword = "keyword1.DATA";//放大那个推送字段
  12. private Map<String, TemplateDataVo> data;//推送文字
  13. }

1.获取小程序全局后台接口调用凭据,有效期最长为7200

  1. /*
  2. * 获取access_token
  3. * appid和appsecret到小程序后台获取
  4. * */
  5. public String getAccess_token() {
  6. //获取access_token
  7. String appid = "*****"; //appid和appsecret到小程序后台获取
  8. String appsecret = "*****"; //appid和appsecret到小程序后台获取
  9. String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" +
  10. "&appid=" + appid + "&secret=" + appsecret;
  11. if(restTemplate==null){
  12. restTemplate = new RestTemplate();
  13. }
  14. String json = restTemplate.getForObject(url, String.class);
  15. JSONObject myJson = JSONObject.parseObject(json);
  16. return myJson.get("access_token").toString();
  17. }

2.发送消息给指定的用户

  1. public String pushOneUser(String access_token, String openid, String type, String templateId, String[] keywords) {
  2. //如果access_token为空则从新获取
  3. if(StringUtils.isEmpty(access_token)){
  4. access_token = getAccess_token();
  5. }
  6. String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send" +
  7. "?access_token=" + access_token;
  8. //拼接推送的模版
  9. WxMssVo wxMssVo = new WxMssVo();
  10. wxMssVo.setTouser(openid);//用户openid
  11. /*wxMssVo.setForm_id(formId);//formId*/
  12. wxMssVo.setTemplate_id(templateId);//模版id
  13. Map<String, TemplateDataVo> m = new HashMap<>();
  14. if (type.equals("3")) {
  15. m.put("thing3", new TemplateDataVo(keywords[0]));
  16. m.put("time1", new TemplateDataVo(keywords[1]));
  17. m.put("thing4", new TemplateDataVo(keywords[2]));
  18. wxMssVo.setData(m);
  19. }
  20. if(restTemplate==null){
  21. restTemplate = new RestTemplate();
  22. }
  23. ResponseEntity<String> responseEntity =
  24. restTemplate.postForEntity(url, wxMssVo, String.class);
  25. log.error("小程序推送结果={}", responseEntity.getBody());
  26. return responseEntity.getBody();
  27. }

3.整合

  1. package com.ac.project.task.utils;
  2. import com.ac.project.task.service.impl.applet.WXServiceImpl;
  3. import com.ac.project.task.vo.TemplateDataVo;
  4. import com.ac.project.task.vo.WxMssVo;
  5. import com.alibaba.druid.util.StringUtils;
  6. import com.alibaba.fastjson2.JSONObject;
  7. import lombok.extern.slf4j.Slf4j;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.http.ResponseEntity;
  10. import org.springframework.web.client.RestTemplate;
  11. import java.io.UnsupportedEncodingException;
  12. import java.net.URLEncoder;
  13. import java.util.HashMap;
  14. import java.util.Map;
  15. /**
  16. * @program: coworking
  17. * @description: 微信工具类
  18. * @author: zhaozehui
  19. * @create: 2023-05-08 10:09
  20. **/
  21. @Slf4j
  22. public class weChatUtil {
  23. private static RestTemplate restTemplate;
  24. final Boolean flag = false;
  25. /**
  26. * description 1.获取用户的临时code
  27. * param [appid, redirectUrl]
  28. * return java.lang.String
  29. * author
  30. **/
  31. public static String getUserUathUrl(String appid, String redirectUrl) throws UnsupportedEncodingException {
  32. StringBuffer getcodeUrl = new StringBuffer()
  33. .append("https://open.weixin.qq.com/connect/oauth2/authorize")
  34. .append("?appid=" + appid)
  35. .append("&redirect_uri=" + URLEncoder.encode(redirectUrl, "utf-8"))
  36. .append("&response_type=code")
  37. .append("&scope=snsapi_userinfo")
  38. .append("&state=" + System.currentTimeMillis())
  39. .append("#wechat_redirect");
  40. return getcodeUrl.toString();
  41. }
  42. /**
  43. * description 2.获取用户的openid和access_token
  44. * param [appid, appSecret, code]
  45. * return java.lang.String
  46. * author
  47. **/
  48. public static String getBaseAccessTokenUrl(String appid, String appSecret, String code) throws UnsupportedEncodingException {
  49. StringBuffer baseAccessTokenUrl = new StringBuffer()
  50. .append("https://api.weixin.qq.com/sns/oauth2/access_token")
  51. .append("?appid=" + appid)
  52. .append("&secret=" + appSecret)
  53. .append("&code=" + code)
  54. .append("&grant_type=authorization_code");
  55. return baseAccessTokenUrl.toString();
  56. }
  57. /**
  58. * description 3.根据openid 获取用户的信息
  59. * param [accessToken, openid]
  60. * return java.lang.String
  61. * author
  62. **/
  63. public static String getBaseUserInfoUrl(String accessToken, String openid) {
  64. StringBuffer baseUserInfoUrl = new StringBuffer()
  65. .append("https://api.weixin.qq.com/sns/userinfo")
  66. .append("?access_token=" + accessToken)
  67. .append("&openid=" + openid)
  68. .append("&lang=zh_CN");
  69. return baseUserInfoUrl.toString();
  70. }
  71. /**
  72. * description 4检验授权凭证(access_token)是否有效
  73. * param [openid, accessToken]
  74. * return java.lang.String
  75. **/
  76. public static String checkAccessToken(String openid, String accessToken) {
  77. StringBuffer stringBuffer = new StringBuffer().append(" https://api.weixin.qq.com/sns/auth")
  78. .append("?access_token=" + accessToken)
  79. .append("&openid=" + openid);
  80. return stringBuffer.toString();
  81. }
  82. /**
  83. * description 微信小程序登录,通过code获取session_key和openid
  84. * param [appid, secret, code]
  85. * return java.lang.String
  86. * author
  87. **/
  88. public static String getCode2Session(String appid, String secret, String code) {
  89. StringBuffer code2Session = new StringBuffer()
  90. .append("ttps://api.weixin.qq.com/sns/jscode2session")
  91. .append("?appid=" + appid)
  92. .append("&secret=" + secret)
  93. .append("&js_code=" + code)
  94. .append("&grant_type=authorization_code");
  95. return code2Session.toString();
  96. }
  97. /**
  98. * 推送消息给指定的用户
  99. * @param access_token app的token
  100. * @param openid 用户openid
  101. * @param type 类型 1派发模板 2.反馈提醒 3审核模板 4日期截至提醒模板
  102. * @param templateId 模板ID
  103. * @param keywords {与模板字段一一对应}
  104. * @return
  105. */
  106. public String pushOneUser(String access_token, String openid, String type, String templateId, String[] keywords) {
  107. //如果access_token为空则从新获取
  108. if(StringUtils.isEmpty(access_token)){
  109. access_token = getAccess_token();
  110. }
  111. String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send" +
  112. "?access_token=" + access_token;
  113. //拼接推送的模版
  114. WxMssVo wxMssVo = new WxMssVo();
  115. wxMssVo.setTouser(openid);//用户openid
  116. /*wxMssVo.setForm_id(formId);//formId*/
  117. wxMssVo.setTemplate_id(templateId);//模版id
  118. Map<String, TemplateDataVo> m = new HashMap<>();
  119. if (type.equals("3")) {
  120. m.put("thing3", new TemplateDataVo(keywords[0]));
  121. m.put("time1", new TemplateDataVo(keywords[1]));
  122. m.put("thing4", new TemplateDataVo(keywords[2]));
  123. wxMssVo.setData(m);
  124. } else if (type.equals("1")) {
  125. /* [发起人,发布时间,任务名称,任务描述,结束时间]*/
  126. m.put("thing12",new TemplateDataVo(keywords[0]));
  127. m.put("date3",new TemplateDataVo(keywords[1]));
  128. m.put("thing4",new TemplateDataVo(keywords[2]));
  129. m.put("thing6",new TemplateDataVo(keywords[3]));
  130. m.put("time9",new TemplateDataVo(keywords[4]));
  131. }else if (type.equals("2")){
  132. }
  133. if(restTemplate==null){
  134. restTemplate = new RestTemplate();
  135. }
  136. ResponseEntity<String> responseEntity =
  137. restTemplate.postForEntity(url, wxMssVo, String.class);
  138. log.error("小程序推送结果={}", responseEntity.getBody());
  139. return responseEntity.getBody();
  140. }
  141. /*
  142. * 获取access_token
  143. * appid和appsecret到小程序后台获取,当然也可以让小程序开发人员给你传过来
  144. * */
  145. public String getAccess_token() {
  146. //获取access_token
  147. String appid = "";
  148. String appsecret = "";
  149. String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" +
  150. "&appid=" + appid + "&secret=" + appsecret;
  151. if(restTemplate==null){
  152. restTemplate = new RestTemplate();
  153. }
  154. String json = restTemplate.getForObject(url, String.class);
  155. JSONObject myJson = JSONObject.parseObject(json);
  156. return myJson.get("access_token").toString();
  157. }
  158. public static void main(String[] args) {
  159. System.out.println(new WXServiceImpl().getAccess_token());
  160. WXServiceImpl wxService = new WXServiceImpl();
  161. String values[] = {"zzh7878","2023年5月8日 15:01","ceshi"};
  162. wxService.pushOneUser(wxService.getAccess_token()
  163. , "oM47R5KO0kFhsScuitgSJSjiN0s", "3", "QhJq4RvU7qGyf7FY_ZFc1sHJCTD8VkFvtHEx8uHwY4"
  164. , values);
  165. }
  166. }

4.测试

注意:在前端调用方法时,只有发生点击行为或者支付行为才会出现订阅栏

微信小程序文档:wx.requestSubscribeMessage(Object object) | 微信开放文档

会出现以下弹窗

 未允许的话,会出现以下日志

 点击允许后,再次测试收到通知

 

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

闽ICP备14008679号