上面的代码获取用户的唯一标识,用户的openid,为发送系统消息做准备。
getOpenid: function() {
wx.login({ success: function(response) { //请求自己后台获取用户openid
var code =response.code;
console.log("code"+code)
wx.request({ url: 'https://api.weixin.qq.com/sns/jscode2session?appid=wx3cea0551cd28c9d2&secret=97852fe91b861511c39228a3517f8356&grant_type=authorization_code&js_code='+code,
success: function(response) {
console.log(response)
var openid = response.data.openid; console.log('请求获取openid:' + openid); //可以把openid存到本地,方便以后调用
wx.setStorageSync('openid', openid);
//that.setData({ openid: "获取到的openid:" + openid
//})
}
})
},
fail: function(){
console.log("shibai");
}
})
},
用户订阅消息,订阅的消息只能消费一次。
onclick1: function(){
wx.requestSubscribeMessage({
tmplIds: ['A6HJRHBB1Xlx-P_k94UQ6Dx3FvfXAAv69wwIFL4LNoE'],
success (res) { }
})
},
给微信发送系统消息,我是利用了内网穿透工具(natapp)访问我后台的发送消息代码。
域名(http://x8u93d.natappfree.cc)
sendMsg2: function(){
console.log("111")
wx.request({
url: "http://x8u93d.natappfree.cc/msg/send?touser="+wx.getStorageSync('openid'),
method: "GET",
success: function(response) {
console.log(response)
}
})
},
后台代码
public String getAccessToken() {
String appId = "wx3cea0551cd28c9d2";
String appSecret = "97852fe91b861511c39228a3517f8356";
String result = cn.hutool.http.HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret);
JSONObject jsonObject = JSONUtil.parseObj(result);
return jsonObject.getStr("access_token");
}
@GetMapping("/send")
public String send(@RequestParam("touser") String touser) {
JSONObject body = new JSONObject();
body.set("touser", touser);
body.set("template_id", "A6HJRHBB1Xlx-P_k94UQ6Dx3FvfXAAv69wwIFL4LNoE");
JSONObject json = new JSONObject();
json.set("thing1", new JSONObject().set("value", "测试"));
json.set("amount2", new JSONObject().set("value", "20"));
body.set("data", json);
//发送
String accessToken = getAccessToken();
String post = cn.hutool.http.HttpUtil.post("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken, body.toString());
return "ok";
}