WeChat applet is an application launched by Tencent that can be used on the WeChat platform without downloading and installing. Users can scan or search to start using the application, which can save a lot of mobile phone memory and time costs.

With the continuous development of WeChat ecology, compared with APP development, mini programs have the advantages of low development difficulty, convenient use, and a large number of users with their own WeChat, so they are more and more favored by developers.

As an IM tool, WeChat is the most commonly used function to send and receive messages. In the IoT business scenario, if you can connect with the device through the WeChat applet, receive and send messages, or receive alarms of abnormal device status in time, it will greatly improve the feasibility of remote intelligent manipulation.

This article will take the MQTT connection test scenario as an example, use MQTT.js to connect to the MQTT service - EMQX Cloud deployment, and implement a simple and convenient MQTT connection test tool in the WeChat applet.

EMQX Cloud is a fully managed cloud-native MQTT messaging service that provides users with reliable and real-time capabilities such as connection of massive IoT devices, event message processing, and IoT data bridging in an automated and fully managed form, eliminating the burden of infrastructure management and maintenance and accelerating IoT application development.

Project initialization

Related preparations on the WeChat applet side

Certificate and Domain Name

  1. Certificate

    Due to the high security requirements of the WeChat applet, the communication with the background server must use the https/wss protocol. So we need to buy a certificate and configure TLS/SSL certificate. Log in to the EMQX Cloud console and go to the overview page of the corresponding deployment to configure TLS/SSL. One-way or two-way authentication is acceptable. Note that the certificate chain is required . Otherwise, subsequent real machine debugging will fail. This article chooses one-way authentication.

  2. Bind domain name

    The default connection address of EMQX Cloud Professional Edition deployment is IP. Since the applet can only communicate with the specified domain name, EMQX Cloud users need to bind their ICP -registered domain name to the deployment IP, and go to the WeChat public platform -> [Development]->[Development Management]->[Development Settings]->[Server Domain Name] add the socket legal domain name .

Create project

Register a WeChat applet account and download the WeChat developer tools . Open the WeChat developer tool and click Create a new applet project.

MQTT library installation

It is recommended to use MQTT.js v4.2.1 (for the native WeChat applet). If the debugger can be connected but there are still problems with real machine debugging, it is recommended to try switching the MQTT.js version .

The available versions of the native WeChat applet MQTT.js are v4.2.1, v4.2.0, v4.1.0 and v2.18.8

Use uniapp framework to build WeChat applet MQTT.js Available versions are v4.1.0 and v2.18.8

Create a new utils folder in the project root directory, put the downloaded mqtt.min.js file of the corresponding version into this folder, and import mqtt in index.js in the following way

 import mqtt from "../../utils/mqtt.min.js";

MQTT connection test tool key code

establish connection

Only the wss protocol can be used, but it needs to be written as wxs in the WeChat applet

The port is 8084 (EMQX Cloud Professional Edition deployment), but the actual port number is subject to the information on the overview page of the corresponding deployment in the EMQX Cloud console

Don't forget to bring the path /mqtt at the end of the connection address

For EMQX Cloud deployment, you need to add the username and password in [Authentication] -> [Authentication] on the deployment details page, and then write it into mqttOptions

 Page({
  data: {
    client: null,
    conenctBtnText: "连接",
    host: "wx.emqxcloud.cn",
    subTopic: "testtopic/miniprogram",
    pubTopic: "testtopic/miniprogram",
    pubMsg: "Hello! I am from WeChat miniprogram",
    receivedMsg: "",
    mqttOptions: {
      username: "test",
      password: "test",
      reconnectPeriod: 1000, // 1000毫秒,设置为 0 禁用自动重连,两次重新连接之间的间隔时间
      connectTimeout: 30 * 1000, // 30秒,连接超时时间
      // 更多参数请参阅 MQTT.js 官网文档:https://github.com/mqttjs/MQTT.js#mqttclientstreambuilder-options
      // 更多 EMQ 相关 MQTT 使用教程可在 EMQ 官方博客中进行搜索:https://www.emqx.com/zh/blog
    },
  },

  setValue(key, value) {
    this.setData({
      [key]: value,
    });
  },

  connect() {
    // MQTT-WebSocket 统一使用 /path 作为连接路径,连接时需指明,但在 EMQX Cloud 部署上使用的路径为 /mqtt
    // 因此不要忘了带上这个 /mqtt !!!
    // 微信小程序中需要将 wss 协议写为 wxs,且由于微信小程序出于安全限制,不支持 ws 协议
    try {
      this.setValue("conenctBtnText", "连接中...");
      const clientId = new Date().getTime();
      this.data.client = mqtt.connect(`wxs://${this.data.host}:8084/mqtt`, {
        ...this.data.mqttOptions,
        clientId,
      });

      this.data.client.on("connect", () => {
        wx.showToast({
          title: "连接成功",
        });
        this.setValue("conenctBtnText", "连接成功");

        this.data.client.on("message", (topic, payload) => {
          wx.showModal({
            content: `收到消息 - Topic: ${topic},Payload: ${payload}`,
            showCancel: false,
          });
          const currMsg = this.data.receivedMsg ? `<br/>${payload}` : payload;
          this.setValue("receivedMsg", this.data.receivedMsg.concat(currMsg));
        });

        this.data.client.on("error", (error) => {
          this.setValue("conenctBtnText", "连接");
          console.log("onError", error);
        });

        this.data.client.on("reconnect", () => {
          this.setValue("conenctBtnText", "连接");
          console.log("reconnecting...");
        });

        this.data.client.on("offline", () => {
          this.setValue("conenctBtnText", "连接");
          console.log("onOffline");
        });
        // 更多 MQTT.js 相关 API 请参阅 https://github.com/mqttjs/MQTT.js#api
      });
    } catch (error) {
      this.setValue("conenctBtnText", "连接");
      console.log("mqtt.connect error", error);
    }
  },
});

Subscribe to topics

 subscribe() {
  if (this.data.client) {
    this.data.client.subscribe(this.data.subTopic)
    wx.showModal({
      content: `成功订阅主题:${this.data.subTopic}`,
      showCancel: false,
    })
    return
  }
  wx.showToast({
    title: '请先点击连接',
    icon: 'error',
  })
},

unsubscribe

 unsubscribe() {
  if (this.data.client) {
    this.data.client.unsubscribe(this.data.subTopic)
    wx.showModal({
      content: `成功取消订阅主题:${this.data.subTopic}`,
      showCancel: false,
    })
    return
  }
  wx.showToast({
    title: '请先点击连接',
    icon: 'error',
  })
},

make an announcement

 publish() {
  if (this.data.client) {
    this.data.client.publish(this.data.pubTopic, this.data.pubMsg)
    return
  }
  wx.showToast({
    title: '请先点击连接',
    icon: 'error',
  })
},

Disconnect

 disconnect() {
  this.data.client.end()
  this.data.client = null
  this.setValue('conenctBtnText', '连接')
  wx.showToast({
    title: '成功断开连接'
  })
},

For the complete code of the project, please refer to: https://github.com/emqx/MQTT-Client-Examples/tree/master/mqtt-client-wechat-miniprogram

Real machine test verification

This article uses the MQTT 5.0 client tool - MQTT X as the test client and the applet to send and receive messages to each other.

The applet establishes a connection, subscribes to the topic testtopic/miniprogram , and sends a message to the topic. At the same time, use MQTT X to connect to the same address and subscribe to the topic testtopic/# .

It can be seen that MQTT X can normally receive messages sent from the applet. Similarly, when using MQTT X to send a message to the topic testtopic/miniprogram , you can also see that the applet can receive the message normally.

Epilogue

Through this article, we introduced how to use MQTT.js in the WeChat applet to realize the functions of connection, subscription, unsubscription, sending and receiving messages, and disconnection of the MQTT protocol, and successfully built a simple MQTT connection test tool. In addition to exposing the connection address to facilitate modification, other related connection parameter options can also be configured in the form of a form, which will be more flexible and efficient. In the actual production environment, it can be optimized on the basis of this example to support multiple connections online at the same time, and expand the configurable option parameters.

Copyright statement: This article is original by EMQ, please indicate the source when reprinting.

Original link: https://www.emqx.com/zh/blog/how-to-use-mqtt-in-wechat-miniprogram


EMQX
336 声望436 粉丝

EMQ(杭州映云科技有限公司)是一家开源物联网数据基础设施软件供应商,交付全球领先的开源 MQTT 消息服务器和流处理数据库,提供基于云原生+边缘计算技术的一站式解决方案,实现企业云边端实时数据连接、移动、...