由于微信订阅号开发改变,之前写的那片订阅号推送有些内容不可以使用了,所以我重新整理了一下开发逻辑,希望可以对有需要的朋友带来帮助。
一、 选择订阅号消息的模板
通过微信公众平台登录微信小程序的后台,按照下面的步骤选取模板,获取模板的id,消息推送要用。
模板id
二、其他参数的准备
(1)参数的介绍
openid:每个微信唯一的id,服务通知用它的作用是你想要通知谁,谁的openid就给你发送过去,它类似你的电话号码,给你发短信,必须知道你的电话号。
access_token:因为如何实现微信服务通知,底层我们不知道,微信给了接口,想用这个接口必须有access_token参数。因为微信保密做的还相对严格,所以获取就需要各种参数。
template_id:模板id,这个就是微信公众平台里边,你选用什么格式通知模板,就把对应的template_id粘贴过来。(上边已经获取)
appid、secret:在微信公众平台里边,这个大家应该都熟悉,我就不多说了。
(2)参数的获取
openid
//获取openidwx.login({success: function (res) {var code1 = res.codevar appid1 = "自己的"var secret1 = "自己的"var ul = 'https://api./sns/jscode2session?appid=' + appid1 + '&secret=' + secret1 + '&js_code=' + code1 + '&grant_type=authorization_code'//获取openidwx.request({url: ul,method: 'GET',success: function (e) {var openid = e.data.openidconsole.log('获取登录身份的唯一openid', openid)that.openid=e.data.openidwx.setStorageSync('openid', openid)}})}})
access_token
//获取access_tokenconst appid = "" // 这里填写你的appidconst secret = "" // 这里填写你的secretwx.request({url: `https://api./cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${secret}`, header: {'content-type': 'application/json' },success(res) {console.log("at微信小程序"+res.data.access_token)that.access_token=res.data.access_tokenconsole.log("onload:"+that.access_token)wx.setStorageSync('at',res.data.access_token)},fail(error){console.log(error)}})
3、消息推送
这个需要绑定函数才能触发,在加载函数没办法实现的
wxml
<view class="tab-item" bindtap="Initialize"><text>获取位置</text></view>
js
//初始化函数Initialize(e){//发送是否订阅订阅消息var that=thiswx.requestSubscribeMessage({//模板id 微信公众后台获取tmplIds: ['feqi54dbgg2vSfzQ54nMJbor8Bf7tCgf58HotgrGof8'],success(res) {if(res.errMsg === 'requestSubscribeMessage:ok'){that.sendMessage();}}})},
sendMessage: function (e) {var that=thisvar today = new Date();var year = today.getFullYear();var m1 = today.getMonth();var month = m1 + 1var day = today.getDate();var h = today.getHours();var m = today.getMinutes();var etime = year + "-" + month + "-" + day var time=h+":"+mconst access_token1 = wx.getStorageSync('at');const openid1 = wx.getStorageSync('openid')const value1 = wx.getStorageSync('value1')const value3 = wx.getStorageSync('value3')const page = wx.getStorageSync('page1')console.log("测试at"+access_token1+"测试openid"+openid1)wx.request({url: `https://api./cgi-bin/message/subscribe/send?access_token=${access_token1}`, //仅为示例,并非真实的接口地址data: {"touser": openid1,"template_id": "feqi54dbgg2vSfzQ54nMJbor8Bf7tCgf58HotgrGof8","page":page,"data":{"thing1": {"value": value1},"time2": {"value": time},"thing3": {"value": value3},"thing4": {"value": "点击查看详细介绍"}}},method: 'post',header: { 'Content-Type': 'application/json' },success(res) {console.log("res",res)},fail(error){console.log("error",error)}})},