uniapp小程序如何订阅消息,给用户推送消息?

小程序的模板推送分为“一次性订阅”和“长期订阅”
一次性订阅:用户订阅小程序后,程序只能对指定OpenId进行一次推送模板消息,无法多次推送
长期订阅:用户长期订阅,能够多次推送模板消息(长期订阅模板需要向微信官方发起申请)

此文章,为了理解更全面,全部写在前端页面进行调试,在开发中,前端获取用户授权后,由后端进行处理

<template>
	<view>
		<view class="">
			<button @click="openid">获取openid</button>
		</view>
		<view class="">
			<button @click="getToken">获取token</button>
		</view>
		<view class="">
			<button @click='notification'>推送消息</button>
		</view>
	</view>
</template>

在微信公众平台 中查找 小程序 APPID, 和 小程序密钥,
其中thing1、time2、number3,thing4,thing6是根据小程序中的模板定义的,注意模板使用规则
后台也需要对应模板内容添加字段
在这里插入图片描述

return:{
		useropenid:'',
		mytoken:'',
		tmplIdsone:'', // 要发送订阅的模板id
		wxappid:'',  // 小程序appID
		wxsecret:'',  // 小程序密钥
		pushmsg: {
			"touser": 'xxx',		// 获取到的用户openid
			"template_id": "xxxx", // 对应的模板id(微信公众平台中的订阅消息,选择对应模板)
			"data": {
				"thing1": {
					"value": "李四"
				},
				"time2": {
					"value": "2021年4月14日 14:05"
				},
				"number3": {
					"value": "10"
				},
				"thing4": {
					"value": "20"
				},
				"thing6": {
					"value": "张三"
				}
			},
			"page":""  //进入哪个页面
		},
}

调用API获取登录用户的openid
其中appid,secret 在公众平台查找

async openid() {
	wx.login({
		success(res) {
			if (res.code) {
				wx.request({
					url: `https://api.weixin.qq.com/sns/jscode2session?appid=${this.wxappid}&secret=${this.wxsecret}&js_code=${res.code}&grant_type=authorization_code`,
					success(data) {
						this.useropenid = data.data.openid
						this.pushmsg.touser = this.useropenid
					}
				})
			} else {
				console.log('获取失败!' + res.errMsg)
			}
		}
	})
},

wx.requestSubscribeMessage() ,获取用户授权
获取推送消息模板的token
根据AppId、Secret调用开发文档Api获取token

getToken() {
	wx.requestSubscribeMessage({
		tmplIds: [this.tmplIdsone],   // 要发送订阅的模板id
		success(res) {
			for (let key in res) {
				if (res[key] == "accept") {
					uni.showToast({
						title:'已允许消息推送'
					})
					wx.request({
						url: `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${this.wxappid}&secret=${this.wxsecret}`,
						data: {},
						success: function(res) {
							this.mytoken = res.data.access_token
						}
					})
				} else{
				}
			}
		},
		fail: function(res) {
		}
	})
},

调用消息推送

notification() {
		wx.request({
			url: 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' + this.mytoken,
			data: JSON.stringify(this.pushmsg),
			method: 'POST',
			success: function(res) {
				console.log(res)
			},
		})
	}

推送订阅消息结果
在这里插入图片描述

小程序订阅消息参数值内容限制规则

在这里插入图片描述


如果对你有用,就收藏关注点个赞吧

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐