功能介绍
- 订阅消息推送位置:服务通知
- 订阅消息下发条件:用户自主订阅(用户不主动订阅无法进行通知)
1.创建小程序订阅消息模板
进入微信小程序【功能】——>【订阅消息】添加模板获取模板id
模板详情
2.获取下发权限
用户需要主动订阅
wxml
<button bindtap="requestSubscribeMessage">订阅授权</button>
js
//订阅授权
requestSubscribeMessage(){
const _this = this;
// 获取用户的当前设置,判断是否点击了“总是保持以上,不在询问”
wx.getSetting({
withSubscriptions: true, // 是否获取用户订阅消息的订阅状态,默认false不返回
success(res) {
console.log('res.authSetting', res.authSetting)
if (res.authSetting['scope.subscribeMessage']) {
console.log('用户点击了“总是保持以上,不再询问”')
} else {
console.log('用户没有点击“总是保持以上,不再询问”则每次都会调起订阅消息')
//因为没有选择总是保持,所以需要调起授权弹窗再次授权
_this.authorizationBtn();
}
}
})
},
// 授权
authorizationBtn() {
wx.requestSubscribeMessage({
tmplIds: ['J6O1CV-3Hz-K5No8fVA9-rV16cMupJE3AdKjIDyVUts'],
success(res) {
console.log('授权成功')
}
})
},
3.调用接口下发订阅消息
获取token
import com.alibaba.fastjson.JSONObject;
import com.ddm.baseService.tools.HtmlTools;
import com.ddm.baseService.tools.JsonTools;
import org.apache.log4j.Logger;
import java.net.MalformedURLException;
/**
* @CLASS_NAME: appletSubscribe
* @author:Lian
* @DATE: 2023/9/1 9:09
**/
public class appletSubscribe {
private static Logger logger = Logger.getLogger(MsgSend.class);
public static final String getAccessToken1(String appid, String appSecret) {
StringBuffer buffer = new StringBuffer();
buffer.append("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential");
buffer.append("&appid=" + appid);
buffer.append("&secret=" + appSecret);
Object content = HtmlTools.getUrlContent(buffer.toString());
JSONObject jsonObject = JsonTools.strToJson(content);
if (jsonObject.get("errcode") != null) {
logger.info("weixin getAccessToken 错误:" + jsonObject.toString());
}
return jsonObject.getString("access_token");
}
}
消息推送
public String send(){
Record body = new Record();
body.set("touser","xxxxxxxx");//推送用户的openid
body.set("template_id","xxxxxxxx");//推送模板id
Record json = new Record();//用户咨询推送通知
json.set("thing2",new Record().set("value","咨询。。。。"));//咨询内容
json.set("thing1",new Record().set("value","张三"));//商家名称
body.set("data",json);
//发送
String accessToken= getAccessToken();
String post = HtmlTools.postJSON("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken, body.toJson());
return post;
}
4.java完整代码
import com.alibaba.fastjson.JSONObject;
import com.ddm.baseService.tools.HtmlTools;
import com.ddm.baseService.tools.JsonTools;
import com.jfinal.plugin.activerecord.Record;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.net.MalformedURLException;
import java.time.LocalDateTime;
/**
* @CLASS_NAME: appletSubscribe
* @author: Lian
* @DATE: 2023/9/1 9:21 周二
**/
@Slf4j
@RestController
@RequestMapping(value = "/appletSubscribe")
@Api(value = "appletSubscribe.消息订阅")
@Scope("prototype")//多例模式
public class appletSubscribe {
private static Logger logger = Logger.getLogger(MsgSend.class);
@Value("${wx.user_appid}")
private String appid;//appId
@Value("${wx.user_secret}")
private String secret;//appId
@Value("${wx.template_id}")
private String templateId;推送模板id
//微信小程序获取access_token
public String getAccessToken() {
StringBuffer buffer = new StringBuffer();
buffer.append("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential");
buffer.append("&appid=" +appid);
buffer.append("&secret=" + secret);
log.info("templateId==="+templateId);
Object content = HtmlTools.getUrlContent(buffer.toString());
JSONObject jsonObject = JsonTools.strToJson(content);
if (jsonObject.get("errcode") != null) {
logger.info("weixin getAccessToken 错误:" + jsonObject.toString());
}
return jsonObject.getString("access_token");
}
public String send(String openid){
Record body = new Record();
body.set("touser",openid);//推送用户的openid
body.set("template_id",templateId);//推送模板id
Record json = new Record();//用户私信通知
json.set("thing2",new Record().set("value","咨询内容"));//咨询内容
json.set("thing1",new Record().set("value","张三"));//商家名称
body.set("data",json);
//发送
String accessToken= getAccessToken();
String post = HtmlTools.postJSON("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken, body.toJson());
log.info("小程序消息订阅推送===="+post);
return post;
}
}