由于微信訂閱号開發改變,之前寫的那片訂閱号推送有些内容不可以使用了,是以我重新整理了一下開發邏輯,希望可以對有需要的朋友帶來幫助。
一、 選擇訂閱号消息的模闆
通過微信公衆平台登入微信小程式的背景,按照下面的步驟選取模闆,擷取模闆的id,消息推送要用。
模闆id
二、其他參數的準備
(1)參數的介紹
openid:每個微信唯一的id,服務通知用它的作用是你想要通知誰,誰的openid就給你發送過去,它類似你的電話号碼,給你發短信,必須知道你的電話号。
access_token:因為如何實作微信服務通知,底層我們不知道,微信給了接口,想用這個接口必須有access_token參數。因為微信保密做的還相對嚴格,是以擷取就需要各種參數。
template_id:模闆id,這個就是微信公衆平台裡邊,你選用什麼格式通知模闆,就把對應的template_id粘貼過來。(上邊已經擷取)
appid、secret:在微信公衆平台裡邊,這個大家應該都熟悉,我就不多說了。
(2)參數的擷取
openid
//擷取openid
wx.login({
success: function (res) {
var code1 = res.code
var appid1 = "自己的"
var secret1 = "自己的"
var ul = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + appid1 + '&secret=' + secret1 + '&js_code=' + code1 + '&grant_type=authorization_code'
//擷取openid
wx.request({
url: ul,
method: 'GET',
success: function (e) {
var openid = e.data.openid
console.log('擷取登入身份的唯一openid', openid)
that.openid=e.data.openid
wx.setStorageSync('openid', openid)
}
})
}
})
access_token
//擷取access_token
const appid = "" // 這裡填寫你的appid
const secret = "" // 這裡填寫你的secret
wx.request({
url: `https://api.weixin.qq.com/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_token
console.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=this
wx.requestSubscribeMessage({
//模闆id 微信公衆背景擷取
tmplIds: ['feqi54dbgg2vSfzQ54nMJbor8Bf7tCgf58HotgrGof8'],
success(res) {
if(res.errMsg === 'requestSubscribeMessage:ok'){
that.sendMessage();
}
}
})
},
sendMessage: function (e) {
var that=this
var today = new Date();
var year = today.getFullYear();
var m1 = today.getMonth();
var month = m1 + 1
var day = today.getDate();
var h = today.getHours();
var m = today.getMinutes();
var etime = year + "-" + month + "-" + day
var time=h+":"+m
const 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.weixin.qq.com/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)
}
})
},