uniapp WeChat applet subscription message sending service notification

Copyright statement: This article is an original blogger article, following the CC 4.0 BY-SA copyright agreement, please attach the original source link and this statement for reprinting

Link to this article: https://blog.csdn.net/qq_44718932/article/details/126130702

uniapp WeChat applet subscription message sending service notification

Due to the needs of the company, I just finished learning the small program and asked to develop a WeChat small program for live notifications. After learning Vue, I chose to use uniapp to develop it. I almost forgot after learning the native grammar of wx. In the process of using uniapp to write code, I encountered many problems. Through this blog, I will share the overall implementation ideas and some small pits. The whole blog uses a step-by-step approach to let you fully understand the entire process and how to write your own request method. Follow step by step to achieve the final effect.

Implementation idea:

First of all, to realize this requirement, the most direct way is to search for relevant documents and API introduction in the official documentation of wx, and search for subscription news in the official documentation of wx applet to see the introduction of subscription news of the applet

insert image description here

Subscription messages can be divided into the following types

1. 一次性订阅消息

The one-time subscription message is used to solve the notification problem of the follow-up service link after the user uses the Mini Program. After the user subscribes independently, the developer can send a corresponding service message for an unlimited time; each message can be subscribed or unsubscribed separately.

  1. Long-term subscription news

One-time subscription to messages can meet the needs of most service scenarios of Mini Programs, but there are scenarios in the field of offline public services that cannot be satisfied by one-time subscription, such as flight delays, and it is necessary to send message reminders multiple times according to the real-time status of the flight. To facilitate the service, we provide long-term subscription messages. After the user subscribes once, the developer can send multiple messages for a long time.

At present, long-term subscription news is only open to offline public services such as government affairs and people's livelihood, medical care, transportation, finance, and education, and will gradually support other offline public service businesses in the future.

  1. Device subscription message

Device subscription message is a special type of subscription message, which belongs to the long-term subscription message type and needs to complete "device access" before it can be used.

The device subscription message is used to send a message notification to the user when the device triggers certain events that require manual intervention (such as a device failure, insufficient equipment supplies, etc.). See Device Subscription Message Documentation for details.

Here you can choose according to your own needs. Generally, it is a one-time subscription message. According to the official website document, I will make a supplement for the details.


Implementation steps:


1. Get the template id

Manually configure and obtain the template ID on the WeChat public platform:
log in to https://mp.weixin.qq.com, function module, subscribe to news, click select in my template to select a template.
If there is no suitable template, you can apply to add a new template. It can be used after passing the review.
You can choose a basic template to use. After the application is completed, you can see the template you applied for in My Templates. Click on the details to enter the template details view insert image description here


Click to select to enter the public template library and search for templates: event start reminder, click to select to enter the template selection, select up to 5 notification content, here are all non-personalized settings, only according to the provided ones field to come. If you want a personalized design, you can click that: Click Apply. to apply. After selecting, click Submit.


insert image description here


In my template, click the details on the right side of the template you just applied to enter the configuration page. Pay attention to this part of my frame. This will be an important key to set parameters later.

insert image description here


2. Obtain the distribution permission

In the WeChat official document I mentioned above, the steps are the same as mine, where you can enter the details page to view the detailed steps. And the information corresponding to the interface callback parameters, the sample code is wx native code, here I use uniapp as an example. In the document, the request method for initiating a pop-up window is wx.requestSubscribeMessage(Object object), and this method is searched in uni: uni.requestSubscribeMessage(Object object), which is exactly the same, but the top-level object called is different.

methods:{
    
    
	Subscribe(){
    
    
		uni.requestSubscribeMessage({
    
    
			//此处填写刚才申请模板的模板ID
		  	tmplIds: ['ZcsAH2vJKgKocfQw8e2Phhz-8FzPQgfT_5ehxwic4ck'],
		  	success (res) {
    
    
		  		console.log(res)
		  	}
		})
	}
}

Define this method in methods, which can be used as a test by binding the click event.
The effect of debugging on the developer tool is different from that on the real device. The actual effect is only when debugging on the real device. You
can see it by printing res, accept means agree, and reject means reject


3. Call the interface to send subscription messages

The second step is to obtain the user's authorized subscription. to allow you to send subscription messages to users. The third step is to send a request to the WeChat server, send service notifications to specific users through WeChat , and refer to the official WeChat documentation for detailed request parameters. Here I use uniapp as an example

请求地址:POST https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN

By looking at the document, you can know that there must be 4 parameters, and the four parameters here need to be carefully looked at. The document only tells you that you need to fill in these four, and you need to get it step by step on how to get it.
insert image description here

3.1、access_token:

Here you need to send a request to an interface of wx, you need to pass in appidand secret, this step is used to get access_token, valid for 2 hours

get_wx_access_token() {
     
     
	   return uni.request({
     
     
	       method: 'get',
	       // appip和secret需要去小程序管理界面查看
	       url: `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${
       
       appid}&secret=${
       
       secret}`,
	       dataType: 'json',
	       timeout: 30000
	   }).then(res => {
     
     
	       let [err, success] = res
	       if (success.statusCode == 200) {
     
     
	           return success.data.access_token
	       }
	   })
}


If you forget the applet key, just click reset, and then remember to save

insert image description here

PS: The request for obtaining token here is recommended to be done in the backend, otherwise the secret is set in the frontend, and the online submission will be rejected by the marked risk


3.2 touser

The touser parameter is the user id that needs to receive subscription messages. To obtain the user id, you first need to log in to obtain the user's code, and then use the code to obtain the user id

// 先让用户登录,此user_login方法可以放到onLoad()生命周期中去执行
// 此处async和await异步操作不懂可以先百度,问题不大
async user_login() {
    
    
		let self = this
		await uni.login({
    
    
			success(res) {
    
    
				if (res.code) {
    
    
					self.code = res.code
				} else {
    
    
					console.log('获取失败!' + res.errMsg)
				}
			}
		})
},

After obtaining the user's login information, res.code is the user's code. Then send a request to the WeChat backend to obtain the openid. The request to obtain the openid here also needs to use the secret, so it is recommended to put this request in the backend . Paste the code obtained using uni

// wxappid wxsecret为小程序的appId和secretKey,登录小程序后台可查看,code就是user_login的那个code
uni.request({
    
    
	url: `https://api.weixin.qq.com/sns/jscode2session?appid=${
      
      wxappid}&secret=${
      
      wxsecret}&js_code=${
      
      code}&grant_type=authorization_code`,
	success(data) {
    
    
		self.useropenId = data.data.openid
	}
})

Documentation:
insert image description here
At this time, useropenId has been obtained, and this value needs to be passed to touser


3.3、template_id

This value is the template ID, just like passing a string directly, and then write the value passing code below


3.4、data

The value of data needs to use the part of my picture frame when I first applied for the template. If you are applying for other templates by yourself, you need to pay attention to the order of passing in the Keys. The data is passed in in Json format. A Json key is the key in the template.


Finally, send a subscription message

notice() {
    
    
		let self = this
		//下方的thing1,thing2和其他,对应的是你选取模板的模板详情中的字段名称(可在小程序后台模板查看对应的字段,要和上面的字段一样),需要更改成你自己的
		const pushmsg = {
    
    
			"touser": self.useropenId,
			"template_id": "ZcsAH2vJKgKocfQw8e2Phhz-8FzPQgfT_5ehxwic4ck",
			"data": {
    
    
				"thing1": {
    
    
					"value": "今天记得写代码"
				},
				"date2": {
    
    
					"value": "19:00"
				},
				"time3": {
    
    
					"value": "20:00"
				},
				"thing4": {
    
    
					"value": "今天写堆排序把"
				},
				"time7": {
    
    
					"value": "18:50"
				}
			}
		}
		uni.request({
    
    
			// 此处的mytoken
			url: 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' + this.get_wx_access_token(),
			data: JSON.stringify(pushmsg),
			method: 'POST',
			success: function(res) {
    
    
				// console.log('success');
			}
		})
},

The above is the entire process of sending service notifications from WeChat applets. At the end, it is attached: the method is dead, and the person is alive. In fact, the main steps are 3 steps, which are the three steps mentioned in the WeChat official document, but each step requires There are other knowledge points, but the document does not tell you, you need to discover it yourself. Maybe you have other experience, it is very easy to check the document to realize this requirement. This blog may be much more friendly to Xiaobai. Each individual step and request can be separated out to define the method by yourself, just like a building block, I have told you about each core component, and it is up to you how to put together in the end, but the premise is that you must first obtain the openid, and then the user Click on the pop-up window to authorize unification, then get a token, and finally combine the things before sending the request to realize the subscription of the template. Because the realization of this thing is completely a combination of many knowledge points, so you can test each one, clog the return value, you can understand the meaning of each operation, and finally put the key parts in the backend by yourself.


My implementation idea is:
front end:
execute user_login in the onLoad ( ) phase to obtain the user's code,
click the appointment button to pop up the uni.requestSubscribeMessage pop-up window
, and judge the return value after the pop-up is successful. The code
backend:
send a request to get openid,
send a request to get token
, and finally use openid, token, and hard-coded template_id and data to send service notifications


If you think it is useful, click a like and write almost 5,000 words. If you don’t understand or have questions, you can comment. I saw the reply

uniapp WeChat applet subscription message sending service notification

Due to the needs of the company, I just finished learning the small program and asked to develop a WeChat small program for live notifications. After learning Vue, I chose to use uniapp to develop it. I almost forgot after learning the native grammar of wx. In the process of using uniapp to write code, I encountered many problems. Through this blog, I will share the overall implementation ideas and some small pits. The whole blog uses a step-by-step approach to let you fully understand the entire process and how to write your own request method. Follow step by step to achieve the final effect.

Implementation idea:

First of all, to realize this requirement, the most direct way is to search for relevant documents and API introduction in the official documentation of wx, and search for subscription news in the official documentation of wx applet to see the introduction of subscription news of the applet

insert image description here

Subscription messages can be divided into the following types

1. 一次性订阅消息

Guess you like

Origin blog.csdn.net/qq_48850466/article/details/130944848