微信小程序官方文档:发送订阅消息 | 微信开放文档
一.先制定模板,我以已删除的模板为例
二.java后台创建小程序 Vo类,用于封装传送的参数。
import lombok.Data;@Datapublic class TemplateDataVo { private String value;}
import lombok.Data;import java.util.Map;@Datapublic class WxMssVo { private String touser;//用户openid private String template_id;//模版id private String page = "pages/index/index";//默认跳到小程序首页// private String emphasis_keyword = "keyword1.DATA";//放大那个推送字段 private Map data;//推送文字}
获取小程序全局后台接口调用凭据,有效期最长为7200
public String getAccess_token() { //获取access_token String appid = "*****"; //appid和appsecret到小程序后台获取 String appsecret = "*****"; //appid和appsecret到小程序后台获取 String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" + "&appid=" + appid + "&secret=" + appsecret; if(restTemplate==null){ restTemplate = new RestTemplate(); } String json = restTemplate.getForObject(url, String.class); JSONObject myJson = JSONObject.parseObject(json); return myJson.get("access_token").toString(); }
发送消息给指定的用户
public String pushOneUser(String access_token, String openid, String type, String templateId, String[] keywords) { //如果access_token为空则从新获取 if(StringUtils.isEmpty(access_token)){ access_token = getAccess_token(); } String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send" + "?access_token=" + access_token; //拼接推送的模版 WxMssVo wxMssVo = new WxMssVo(); wxMssVo.setTouser(openid);//用户openid wxMssVo.setTemplate_id(templateId);//模版id Map m = new HashMap<>(); if (type.equals("3")) { m.put("thing3", new TemplateDataVo(keywords[0])); m.put("time1", new TemplateDataVo(keywords[1])); m.put("thing4", new TemplateDataVo(keywords[2])); wxMssVo.setData(m); } if(restTemplate==null){ restTemplate = new RestTemplate(); } ResponseEntity responseEntity = restTemplate.postForEntity(url, wxMssVo, String.class); log.error("小程序推送结果={}", responseEntity.getBody()); return responseEntity.getBody(); }
整合
package com.ac.project.task.utils;import com.ac.project.task.service.impl.applet.WXServiceImpl;import com.ac.project.task.vo.TemplateDataVo;import com.ac.project.task.vo.WxMssVo;import com.alibaba.druid.util.StringUtils;import com.alibaba.fastjson2.JSONObject;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.http.ResponseEntity;import org.springframework.web.client.RestTemplate;import java.io.UnsupportedEncodingException;import java.net.URLEncoder;import java.util.HashMap;import java.util.Map;@Slf4jpublic class weChatUtil { private static RestTemplate restTemplate; final Boolean flag = false; public static String getUserUathUrl(String appid, String redirectUrl) throws UnsupportedEncodingException { StringBuffer getcodeUrl = new StringBuffer() .append("https://open.weixin.qq.com/connect/oauth2/authorize") .append("?appid=" + appid) .append("&redirect_uri=" + URLEncoder.encode(redirectUrl, "utf-8")) .append("&response_type=code") .append("&scope=snsapi_userinfo") .append("&state=" + System.currentTimeMillis()) .append("#wechat_redirect"); return getcodeUrl.toString(); } public static String getBaseAccessTokenUrl(String appid, String appSecret, String code) throws UnsupportedEncodingException { StringBuffer baseAccessTokenUrl = new StringBuffer() .append("https://api.weixin.qq.com/sns/oauth2/access_token") .append("?appid=" + appid) .append("&secret=" + appSecret) .append("&code=" + code) .append("&grant_type=authorization_code"); return baseAccessTokenUrl.toString(); } public static String getBaseUserInfoUrl(String accessToken, String openid) { StringBuffer baseUserInfoUrl = new StringBuffer() .append("https://api.weixin.qq.com/sns/userinfo") .append("?access_token=" + accessToken) .append("&openid=" + openid) .append("&lang=zh_CN"); return baseUserInfoUrl.toString(); } public static String checkAccessToken(String openid, String accessToken) { StringBuffer stringBuffer = new StringBuffer().append(" https://api.weixin.qq.com/sns/auth") .append("?access_token=" + accessToken) .append("&openid=" + openid); return stringBuffer.toString(); } public static String getCode2Session(String appid, String secret, String code) { StringBuffer code2Session = new StringBuffer() .append("ttps://api.weixin.qq.com/sns/jscode2session") .append("?appid=" + appid) .append("&secret=" + secret) .append("&js_code=" + code) .append("&grant_type=authorization_code"); return code2Session.toString(); } public String pushOneUser(String access_token, String openid, String type, String templateId, String[] keywords) { //如果access_token为空则从新获取 if(StringUtils.isEmpty(access_token)){ access_token = getAccess_token(); } String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send" + "?access_token=" + access_token; //拼接推送的模版 WxMssVo wxMssVo = new WxMssVo(); wxMssVo.setTouser(openid);//用户openid wxMssVo.setTemplate_id(templateId);//模版id Map m = new HashMap<>(); if (type.equals("3")) { m.put("thing3", new TemplateDataVo(keywords[0])); m.put("time1", new TemplateDataVo(keywords[1])); m.put("thing4", new TemplateDataVo(keywords[2])); wxMssVo.setData(m); } else if (type.equals("1")) { m.put("thing12",new TemplateDataVo(keywords[0])); m.put("date3",new TemplateDataVo(keywords[1])); m.put("thing4",new TemplateDataVo(keywords[2])); m.put("thing6",new TemplateDataVo(keywords[3])); m.put("time9",new TemplateDataVo(keywords[4])); }else if (type.equals("2")){ } if(restTemplate==null){ restTemplate = new RestTemplate(); } ResponseEntity responseEntity = restTemplate.postForEntity(url, wxMssVo, String.class); log.error("小程序推送结果={}", responseEntity.getBody()); return responseEntity.getBody(); } public String getAccess_token() { //获取access_token String appid = ""; String appsecret = ""; String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" + "&appid=" + appid + "&secret=" + appsecret; if(restTemplate==null){ restTemplate = new RestTemplate(); } String json = restTemplate.getForObject(url, String.class); JSONObject myJson = JSONObject.parseObject(json); return myJson.get("access_token").toString(); } public static void main(String[] args) { System.out.println(new WXServiceImpl().getAccess_token()); WXServiceImpl wxService = new WXServiceImpl(); String values[] = {"zzh7878","2023年5月8日 15:01","ceshi"}; wxService.pushOneUser(wxService.getAccess_token() , "oM47R5KO0kFhsScuitgSJSjiN0s", "3", "QhJq4RvU7qGyf7FY_ZFc1sHJCTD8VkFvtHEx8uHwY4" , values); }}
测试
注意:在前端调用方法时,只有发生点击行为或者支付行为才会出现订阅栏
微信小程序文档:wx.requestSubscribeMessage(Object object) | 微信开放文档
会出现以下弹窗
未允许的话,会出现以下日志
点击允许后,再次测试收到通知
来源地址:https://blog.csdn.net/weixin_55823910/article/details/130558549