0%

Taro学习--小程序原生消息推送

小程序最近刚支持给用户发送一次性的通知消息,尝鲜在taro中试了下。

因为Taro官方还没有文档出来,分析了其它的类似API,觉得可以自己先手动写下试试。果然ok

模版设置部分请参照微信官方的设置

定义个按钮让用户触发权限申请

1
<Button openType='subscribe' onClick={this.handleSubscribe} className='btn-max-w' plain type='primary'>同意</Button>

直接用微信原生代码绑定

1
2
3
4
5
6
7
8
9
10
handleSubscribe = () =>{
wx.requestSubscribeMessage({
tmplIds: ['xxxxxxxxxxx'],
success: (res)=> {
if (res.errMsg === 'requestSubscribeMessage:ok'){
// 处理页面逻辑
}
},
})
}

后端根据用户ID给他发消息

核心方法如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
def getAccessToken():
params = {
"appid": app.config['AppID'],
"secret": app.config['AppSecret'],
"grant_type": 'client_credential',
}
r = requests.get(url="https://api.weixin.qq.com/cgi-bin/token", params=params, verify=False)
content = r.json()
return content['access_token']

def sendSubscribe(token,user,templateId,data):
data = {
'touser': user,
"page": "pages/index/index",
'template_id': templateId,
'data': data
}
url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token="+token
r = requests.post(url, data=json.dumps(data), verify=False)
content = r.json()
return content

def checkApprov(checkStatus,userId,userName,name,checkTime):
accessToken = getAccessToken()
openId = userId
templateId = 'xxxxxxxxxxx'
checkText = ''
if checkStatus == 1:
checkText = '审核通过'
if checkStatus == 3:
checkText = '审核未通过'
data = {
"phrase1": {"value": checkText},
"thing2": {"value": '加入班级%s'%name},
"date4": {"value": checkTime},
"name5": {"value": userName},
"thing6": {"value": '加入班级'},
}
sendSubscribe(accessToken,openId,templateId,data)