This is the third day of my participation in Gwen Challenge
1. Introduction
Applets message subscription is actually a fairly common feature. Because the project has packaged a good third-party dependency package, so I have not been to study how to realize the message subscription of the small program, recently stepped on a pit: message subscription panel occasionally appeared and occasionally did not appear, puzzled, pain determined to have a good reason, so there is this article.
2. Applet messages
The message capabilities of applets fall into the following four categories:
- Subscribing to notifications: Users need to actively subscribe to notifications before developers can push to users for an unlimited period of time.
- Unified Service message
- The news of the service
- Position the message
This small program around the subscribe message do explain, if interested in other news, please to see: developers.weixin.qq.com/miniprogram…
Subscribe to messaging: The ability to subscribe to messaging is provided to developers for a closed loop of services and a better experience.
Take a look at the basics provided by the official website:Need to pay attention to the wechat developer tools vs real machine message panel differences.
Let’s take a look at wechat developer tools (center):Take a look at the real machine effect (from the bottom of the panel):
Pit: Wechat developer tools cannot display a full list of subscription messages and cannot check to select, nor can it display the option ‘always keep the above selection, never ask again’.
Now that we have the basics, let’s look at how to implement a small program subscription message!
3. Instructions
3.1 Obtaining the TEMPLATE ID
A. Open the wechat public platform address, scan the code to log in to the background, and find the subscription message TAB.
Wechat public platform link please stamp here:mp.weixin.qq.com/
If you do not have a message subscription template, you will be prompted to enable this feature first.The following is the screenshot after opening:
B. Manually configure the template ID. If no suitable template is found in the public template library, apply for adding a new template and use it after the template is approved.
First, select the XXX template and click Select (in the public template library for demonstration purposes).You then jump to the Subscription Message Settings page: Here you can configure the subscription message template and preview it in real time (left)
Once configured, submit and you’ll see the subscription message in my template.At this point, we can copy the template into our code.
3.2 Obtaining the Delivery Permission
News about small program end subscription interface, please stamp this link: developers.weixin.qq.com/miniprogram… It is up to the user to decide whether to receive the subscription message (the subscription panel) before sending the subscription message for the applet.
Wx. RequestSubscribeMessage (Object Object) API available issued by the authority
Call up the client applet subscription message interface, return the user subscription message operation result. When the user checks’ always keep the above selection, never ask again ‘in the subscription panel, the template message is added to the user’s applet Settings page and the subscription status of the relevant template is obtained through the wx.getSetting interface.
Starting from version 2.8.2, users can only call up the subscription message interface after clicking or initiating a payment callback.
The successful callback function is described as follows:
The failed callback function is as follows:
I’m going to show you how to use it.
// WXML <text class="user-motto" bind:tap="subscribe"> // js const app = getApp() Page({subscribe () { wx.requestSubscribeMessage({ tmplIds: [' XXXXXXXXXX '], success (res) {console.log(' failed callback function ', res)}, fail (err) {console.log(' failed callback function ', err)}, Complete () {console.log(' interface call-end callback (executed on success or failure)')}})}})Copy the code
Click the button, the subscription message panel will appear, click permit/cancel, and the relevant callback will be given. The specific scenario is shown as follows.
3.2.1 Successful Subscription (Single Item)
TmplIds is configured with only one item, and the option ‘always keep the above selection, no longer ask’ is not checked. Click ‘Allow interface to be called successfully, and the following information will be called:
Users can still wake up the subscription panel by clicking again.
3.2.2 Unsubscribing (Single Item)
TmplIds is configured with only one item, and the option ‘always keep the above selection, no longer ask’ is not checked. Click cancel interface call successfully, and the following information will be called back:
Here you will find, as long as the interface call succeeds, triggering the success callback, just a template ID corresponding values may be the accept/reject/ban/filter.
Template ID value | Meaning that |
---|---|
accept | The user agrees to subscribe to the template message corresponding to this ID |
reject | The user refused to subscribe to the template message corresponding to this ID |
ban | It’s been banned backstage |
filter | The template is filtered by background because the template title has the same name |
3.2.3 Partial Subscription (Multiple Subscriptions)
Suppose you now have two subscribe messages, one checked and one unchecked, and then click AllowA successful callback will display an agreement and a rejection, as shown below:The second click will re-pop the authorization window. Here are a few things to note:
In an authorization call, each tmpId corresponding to the template title must not have the same, if the same, keep one. Up to 3 messages can be subscribed to at one call (keep an eye on the client version)
The iOS client 7.0.6 or Android client 7.0.7 or later supports multiple template messages. IOS client 7.0.5 and Android client 7.0.6 support only one template message at a time.
If more than 3, small WeChat program will throw an exception: directly requestSubscribeMessage: fail Templates count out of Max bounds
/ / get application example const app = getApp () Page ({the subscribe () {wx. RequestSubscribeMessage ({tmplIds: ['xxxx1','xxxx2','xxxx3','xxx4'], // 4 template ids are different success (res) {console.log(' interface call successful callback function ', res)}, Fail (err) {console.log(' interface call failed callback ', err)}, complete () {console.log(' interface call failed callback ')}})}})Copy the code
Detailed error screenshots are as follows:
3.2.4 All Subscriptions (Multiple Subscriptions)
Suppose you now have two subscribe messages, check them all, and click AllowThe successful callback will display both items agreed, as shown in the following figure:The second click will re-pop the authorization window.
3.2.5 Manually Close the Subscription Button (Settings page)
Go to the applet native Settings page – Notifications Management – to close receiving notificationsThe subscription panel does not wake up on the second click, as shown below.
The main switch is switched off.
3.3.6 Check ‘Always keep the above selection and never ask again’
Suppose you now have two subscribe messages, check them all, check ‘always keep the above selection, never ask again ‘, and then click Allow.A successful callback is shown below:Repopover authorization does not appear on the second click, but the code continues.
Pit: if checked ‘always keep the above choice, stop asking’ option, the code level will still call wx. RequestSubscribeMessage () this function, just won’t appear popup window, if need to modify the Settings, to go to the small program native Settings page.
3.3.7 Obtaining the Notification Subscription Permission
Wx. getSetting obtains user subscription notification permission.
Wx.getsetting () withSubscriptions wx.getSetting({withSubscriptions: true, success (res) { console.log(res.subscriptionsSetting) // res.subscriptionsSetting = { // "4xijn4T0leWUq6-aQnwPm2TCmmyttczwEktotiAuVhY": "reject", // "F3GZ_x07Hc-tM7r2zOX7yRNgROoNIKx70C48mrHaTrs": "accept", // "itemSettings": { // "4xijn4T0leWUq6-aQnwPm2TCmmyttczwEktotiAuVhY": "reject", // "F3GZ_x07Hc-tM7r2zOX7yRNgROoNIKx70C48mrHaTrs": "accept" // }, // "mainSwitch": false // } } })Copy the code
The user turns on or off subscription message authorization (wx.openSetting) in the Settings page. Currently, the applet does not provide the corresponding callback method, requiring the developer to call wx.getSetting() to check the authorization information.
3.3 Invoking the Interface to Deliver subscription Messages
If the user agrees to receive subscription messages in 3.2, the user can receive subscription messages after implementation of 3.3. If the user refuses to accept in 3.2, the user will not receive the subscription message after performing 3.3. Throw in website details first: developers.weixin.qq.com/miniprogram… Call method:
- HTTPS call
- Cloud call
This interface should be invoked on the server side, but as a front-end developer, only cloud invocation is demonstrated here.
1. Add the name of the interface to be called in the permissions. Openapi field in config.json in the cloud function directory.
{
"permissions": {
"openapi": [
"subscribeMessage.send"
]
}
}
Copy the code
2. When using cloud functions to call cloud functions, the wX-server-SDK version must be at least 0.4.0. It is recommended to keep the wX-server-SDK field in package.json in the cloud function directory up-to-date. Run NPM install –save wx-server-sdk@latest if the WX-server-SDK has not been installed, install it first.
// const cloud = require('wx-server-sdk') cloud.init({env: cloud.DYNAMIC_CURRENT_ENV, }) exports.main = async (event, context) => { try { const result = await cloud.openapi.subscribeMessage.send({ "touser": Cloud.getwxcontext ().openid, // obtain OPENID "page": '/pages/logs/logs? Title = cloud development biography ", "lang" : "zh_CN", "data" : {" date01 ": {" value" : 'jan 05, 2015'}}, "templateId" : '0bzzt22P68jQtzFfWJHUEVKqVSOHDj48be3WAvuVJvw', "miniprogramState": 'developer' }) return result } catch (err) { return err } }Copy the code
This step requires you to get the cloud environment right before you can actually do it.
3.4 Applet page receives parameters passed in the subscription message
Clicking on the service notification card takes you directly to the page path configured by the applet card, and the developer can accept the pass parameters in the onLoad lifecycle function.
OnLoad (options) {console.log(options,' skip parameters ')}Copy the code
4. Tread pit records
4.1 Subscription panel cannot appear
The error code is as follows:
subscribe () { this.setData({ status: 1 },()=>{ wx.requestSubscribeMessage({ tmplIds: [' 0 bzzt22p68jqtzffwjhuevkqvsohdj48be3wavuvjvw], success (res) {the console. The log (' success callback function called interface, res)}, Fail (err) {console.log(' interface call failed callback ', err)}, complete () {console.log(' interface call failed callback ')}})})}Copy the code
The error message is as follows:Error reason: wx. RequestSubscribeMessage () must be synchronized, is not allowed inside the callback function to achieve (in addition to pay back)
4.2 Implementation of UI final persistence
Designers will always have some fancy requirements, such as: before the user has subscribed, the button text says: Remind me to subscribe; After the user subscribes, the button copy displays: subscription has been set. But if the user logs out and enters the page from another entry, it still shows me a reminder to subscribe to the copywriting (even if I subscribed before exiting the page)
There is no way for the developer to know if the user subscribed (in the initial state)
// wxml <view>{{ isSubscribed ? 'Subscription set ': 'remind me to subscribe to'}} < / view > < text class = "user - motto" bind: tap = "subscribe" > point I arouse subscriptions panel < / text > / / js const app = getApp () Page ({data: { isSubscribed: false }, The subscribe () {const tmpId = 'F3GZ_x07Hc - tM7r2zOX7yRNgROoNIKx70C48mrHaTrs / / stamp button before get news subscriptions wx getSetting ({ withSubscriptions: true, success: (res) => {console.log(' Subscribe message Settings ', Res) const {subscriptionsSetting} = res / / to determine whether the subscribe message subscribed to the if (subscriptionsSetting && subscriptionsSetting. ItemSettings && subscriptionsSetting.itemSettings[tmpId] && subscriptionsSetting.itemSettings[tmpId] === 'accept') { Console. log(' subscribed ') return} this.doSubscribe(tmpId)}, fail: () => {this.dosubscribe (tmpId)}})} doSubscribe (tmpId) { const _this = this if(tmpId){ wx.requestSubscribeMessage({ tmplIds: [tmpId], success (res) {console.log(' interface call successful callback ', res) const {errMsg} = res Has been set to subscribe to the if (errMsg = = = 'requestSubscribeMessage: ok' && res [tmpId] = = = 'accept') {_this. SetData ({isSubscribed: }, fail (err) {console.log(' interface failed to call callback function ', err)}, Complete () {console.log(' interface call-end callback (executed on success or failure)')}})}}})Copy the code
5. To summarize
- Wx. RequestSubscribeMessage () must be synchronized, if on request after the asynchronous operations, will prompt an error as follows: ‘can only be invoked by the user tap gesture’ (only by users click gesture to call)
- If the user checks the ‘always keep the above selection, never ask again’ option, the subscription panel will not appear on the second request;
- The user has clicked permit or deny on the subscription message and does not know how to clear the user subscription message authorization record.
6. Write at the end
If there is a mistake, please leave a message, will be corrected in time! If feel helpful to you, please click a like or collect it!