//app.js
wx.login({
success: res => {
// 发送 res.code 到后台换取 openId, sessionKey, unionId
wx.request({
url: `https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${res.code}&grant_type=authorization_code`,
success(res) {
var data = res;
// console.log(data)
var openid = data.data.openid;
// console.log(openid)
wx.setStorageSync('openid', openid)
}
})
}
})
//my/index.js
var util = require('../../utils/util.js');
subscribe() {
var appid = '';
var secret = '';
var openid = wx.getStorageSync('openid');
var page = '/pages/my/index'; //页面路径
var template_idList = []; //模板id列表
var times = util.formatTime(new Date()); //当前时间
var template_data1 = { //模板消息1
"thing1": {
"value": '大众超惠活动来袭'
},
"thing2": {
"value": `大众车展将于${times}开始,敬请关注`
},
"time3": {
"value": times
},
"phrase4": {
"value": '发布成功'
}
};
wx.requestSubscribeMessage({
tmplIds: [`${template_idList[0]}`],
success(res) {
console.log(res)
if (res.errMsg == 'requestSubscribeMessage:ok') { //用户允许推送消息
wx.request({
url: 'https://api.weixin.qq.com/cgi-bin/token',
data: {
grant_type: 'client_credential',
appid: appid,
secret: secret
},
method: 'GET',
success(res) {
// console.log(res)
var access_token = res.data.access_token;
if (access_token) {
wx.request({
url: 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' + access_token,
data: {
"touser": openid,
"template_id": template_idList[0],
"page": page,
"miniprogram_state": null,
"lang": null,
"data": template_data2
},
method: 'POST',
success(res) {
console.log(res)
if (res.data.errmsg = 'ok') {
wx.showToast({
title: '推送成功',
icon: 'none'
})
} else {
wx.showToast({
title: '模板消息有误',
icon: 'none'
})
};
}
});
}
}
})
} else {
wx.showToast({
title: '取消订阅消息',
icon: 'none'
})
}
}
})
}