In order to improve the user experience of small program template message capability, wechat official adjusted the delivery conditions of template message. The old applets template message interface will go offline on January 10, 2020. The old applets template message interface will no longer be used to send template messages, and will be replaced by new one-time subscription and long-term subscription messages.

Subscribe message brought small developers a better ability to touch up to the user, in the concrete implementation process, the developers how to put the template messages for new subscriptions, whether to need to purchase a server to implement authentication server, how can after a period of time after the user subscription, for users to send or one-time subscribe message for a long time?

Applets ยท Cloud development has recently added support for sending subscription messages via cloud calls without access_token and added support for implementing cloud calls in timed triggers, making it easy for developers to play with applets subscription messages.

Today we will use small program ยท cloud development for a small program to realize subscription to remind the actual practice, to help you understand how to quickly access small program ยท cloud development small program subscription message.

Overall sequence diagram

Environment to prepare

  • Register an applet account
  • Open cloud development services

Gets the SUBSCRIPTION message template ID

In the background of wechat small program management, we added a template of subscription message, and here we added a template of course opening reminder.

Leading users to subscribe

WeChat small program provides wx. RequestSubscribeMessage interface to initiate application for subscription access interface.

Bind the tap event to the “subscribe” button, the event handler we’re using here is onSubscribe

index.wxml

<button class=" BTN "data-item="{{item}}" bindtap="onSubscribe" hover-class=" BTN -hover" > </button>Copy the code

Within the onSubscribe function, we will call WeChat API wx. Send subscription privileges requestSubscribeMessage application, when the user after the popup window agreed to subscribe, we will receive a success callback, The subscribed course information will be called the cloud function SUBSCRIBE into the cloud development database, the implementation of the cloud function SUBSCRIBE will be described below.

index.js

onSubscribe: function(e) {
    // Get course information
    const item = e.currentTarget.dataset.item;

    // Call wechat API to request sending subscription messages
    wx.requestSubscribeMessage({
      // Pass in the template ID of the subscription message. The template ID can be obtained in the applets management background
      tmplIds: [lessonTmplId],
      success(res) {
        // Subscribed successfully
        if (res.errMsg === 'requestSubscribeMessage:ok') {
          // Call the cloud function to store the subscribed course information into the cloud development data
          wx.cloud
            .callFunction({
              name: 'subscribe'.data: {
                data: item,
                templateId: lessonTmplId,
              },
            })
            .then((a)= > {
              wx.showToast({
                title: 'Subscription successful'.icon: 'success'.duration: 2000}); }) .catch((a)= > {
              wx.showToast({
                title: 'Subscription failed'.icon: 'success'.duration: 2000}); }); }}}); },Copy the code

Store subscription messages into the cloud development database

Next, we create a cloud function subscribe, which stores the user’s subscription information in the collection messages of the cloud development database, waiting to be called when the user needs to be notified in the future.

Create database collection Messages in the cloud development panel of wechat Developer tools

Create a SUBSCRIBE cloud function. In the cloud function, we will store the course subscription information sent from the small program side in the cloud development database set. After the development is completed, right-click in the wechat developer tool to upload and deploy the cloud function.

cloudfunctions/subscribe/index.js

const cloud = require('wx-server-sdk');
cloud.init();
const db = cloud.database();

exports.main = async (event, context) => {
  try {
    const {OPENID} = cloud.getWXContext();
    // Store subscribed courses in the cloud development database
    const result = await db.collection('messages').add({
      data: {
        touser: OPENID, // OpenID of the subscriber
        page: 'index'.// Which page of the applet will open when the message card is clicked
        data: event.data, // Subscribe to message data
        templateId: event.templateId, // Subscribe message template ID
        done: false.// Message sending status is set to false}});return result;
  } catch (err) {
    console.log(err);
    returnerr; }};Copy the code

Use timed triggers to send subscription messages on a regular basis

Next we need to implement a cloud function send that executes periodically to check if there are subscription messages in the database that need to be sent to the user. If there is need to send a subscribe message, via the cloud. The cloud call openapi. SubscribeMessage. Send will subscribe message sent to the user.

To create a cloud function called send, first configure the cloud function and add the subscribeMessage.send cloud call permission in the permissions of config.json, and then add a timer trigger of sendMessagerTimer. The syntax of the timing trigger is similar to that of the Linux crontab; for example, we configured “0 * * * * * *” to execute the cloud function every minute.

cloudfunctions/send/config.json

{
  "permissions": {
    "openapi": ["subscribeMessage.send"]},"triggers": [{"name": "sendMessagerTimer"."type": "timer"."config": "0 * * * * * *"}}]Copy the code

This cloud function will query the list of messages waiting to be sent from the messages collection of the cloud development database, and check whether there are subscription messages to be sent to users in the database. The sending conditions can be realized according to their own business. For example, the course start reminder can check whether the subscription message needs to be sent according to the course start date. In our following code example, the filter condition only checks the status as unsent.

After querying the list of messages to be sent, we loop through the list of messages, sending each subscription message in turn, and changing the status of the message in the database to sent when it is successfully sent.

cloudfunctions/send/index.js

const cloud = require('wx-server-sdk');

exports.main = async (event, context) => {
  cloud.init();
  const db = cloud.database();

  try {
    // Query the list of messages waiting to be sent from the cloud development database
    const messages = await db
      .collection('messages')
      // The query criteria are simplified to find only unsent messages
      // In a real production environment, you can filter which messages should be sent based on conditions such as class start dates
      .where({
        done: false,
      })
      .get();

    // Loop message list
    const sendPromises = messages.data.map(async message => {
      try {
        // Send a subscription message
        await cloud.openapi.subscribeMessage.send({
          touser: message.touser,
          page: message.page,
          data: message.data,
          templateId: message.templateId,
        });
        // Change the status of the message to sent after it is successfully sent
        return db
          .collection('messages')
          .doc(message._id)
          .update({
            data: {
              done: true,}}); }catch (e) {
        returne; }});return Promise.all(sendPromises);
  } catch (err) {
    console.log(err);
    returnerr; }};Copy the code

The final result

The source code

Github.com/binggg/tcb-…


About me

Binggg (Booker Zhao) @ Tencent - Worked in Xunlei and Tencent successively, personal open source projects include MRN.js, etc. - Founded Xunlei internal component warehouse XNPM, participated in the development of several Xunlei front-end open source projects - keen on optimization and efficiency improvement, He is a lazy engineer who pursues "laziness makes progress"Copy the code

Social information

  • ๐Ÿ™ lot: github.com/binggg
  • ๐Ÿ“• Jane books: www.jianshu.com/u/60f22559b…
  • ๐Ÿ“’ Nuggets: juejin.cn/user/160934…
  • ๐Ÿ‘๏ธ๐Ÿ—จ๏ธ
  • ๐Ÿ“— thought no: segmentfault.com/u/binggg
  • ๐Ÿ“š Blog Park: www.cnblogs.com/binggg/
  • ๐Ÿ“– Open Source China: my.oschina.net/u/4217267
  • ๐Ÿ’ป Polar Community: aijishu.com/u/binggg
  • ๐Ÿ“ฐ today’s headline: www.toutiao.com/c/user/1023…
  • ๐Ÿ“ CSDN: blog.csdn.net/weixin_4254…

Welcome to wechat official account binggg_net