最近搞了个微信小程序的订阅消息,因为微信小程序我也是刚刚接触,所以在做这块功能的时候看了很多文档,等做完后才发现其实也并不难,我后台使用java前台用的是前台用的HTTPS 调用来发送订阅消息(还可以用云调用)
一 获取模板 ID
登录 https://mp.weixin.qq.com 获取模板,如果没有合适的模板,可以申请添加新模板,审核通过后可使用
二 获取开发权限 wx.requestSubscribeMessage(Object object)
订阅消息与模板消息的区别就在于,订阅消息是由用户来授权是否接受消息。
所以要在wxml 写个点击事件来让用户授权是否接收消息
<view bindtap='tomeet'>取餐申请</view>
然后在js里面来写获取下发权限
tomeet:function(){
// 模板id 可以写多个 用“,”分隔即可
let tmpIds = [
""
];
wx.requestSubscribeMessage({
tmplIds: tmpIds,
success (res) {
console.log(res)
},
fail(err){
console.log(err)
}
});
},
注意:这个点击事件一定要用bindtap,不然其他点击事件是不会弹出下面的这个用户授权申请的
三 调用接口下发订阅消息
@RestController
@RequestMapping("/wxapp/sendMsg")
public class SendWxMessageController {
@GetMapping("/pushOneUser/{openid}/{name}")
public String push(@PathVariable String openid ,@PathVariable String name) {
RestTemplate restTemplate = new RestTemplate();
//https发送消息
String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + getAccessToken();
//拼接推送的模版
WxMssVo wxMssVo = new WxMssVo();
wxMssVo.setTouser(openid);
//模板id
wxMssVo.setTemplate_id("");
//点击消息进入到小程序页面
wxMssVo.setPage("pages/index/index");
Map<String, TemplateData> m = new HashMap<>(3);
Timestamp d=new Timestamp(System.currentTimeMillis());
Date daa= DateUtil.parseDateForFormat(d,"yyyy-MM-dd");
//小程序消息模板属性值
m.put("time1", new TemplateData(daa.toString()));
m.put("phrase2", new TemplateData("等待中"));
m.put("phrase3", new TemplateData(name));
wxMssVo.setData(m);
ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, wxMssVo, String.class);
return responseEntity.getBody();
}
public String getAccessToken() {
RestTemplate restTemplate = new RestTemplate();
Map<String, String> params = new HashMap<>();
params.put("APPID", ""); //开发者的appid
params.put("APPSECRET", ""); //应用密匙微信公众平台可找到
ResponseEntity<String> responseEntity = restTemplate.getForEntity(
"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={APPID}&secret={APPSECRET}", String.class, params);
String body = responseEntity.getBody();
JSONObject object = JSON.parseObject(body);
String Access_Token = object.getString("access_token");
String expires_in = object.getString("expires_in");
System.out.println("有效时长expires_in:" + expires_in);
return Access_Token;
}
}
//消息推送模板实体类
@Data
public class WxMssVo {
private String touser;//用户openid
private String template_id;//订阅消息模版id
private String page = "pages/index/index";//默认跳到小程序首页
private Map<String, TemplateData> data;//推送文字
}
至此就可以实现订阅消息功能了 看看效果