The WeChat Mini Program is an application launched by Tencent on January 9, 2017 that can be used on the WeChat platform without downloading and installing. Users can scan or search to open the application. It also embodies the "use and go" concept, users don't have to worry about whether to install too many applications. Applications will be everywhere and available at any time, but there is no need to install or uninstall. For developers, the threshold for small program development is relatively low, less difficult than APP, and can meet simple basic applications. For users, it can save time and cost and mobile phone memory space. For developers, it can also save development and Promotion cost.
This article mainly introduces how to use the MQTT WeChat applet project to realize the connection, subscription, message sending and unsubscription of the applet client and the MQTT cloud service
MQTT is a lightweight IoT messaging protocol based on the publish/subscribe model. It can provide real-time and reliable messaging services for networked devices with very little code and bandwidth. It is widely used in the Internet of Things, mobile Internet, smart hardware, The Internet of Vehicles, electric power and other industries.
Project initialization
Preliminary preparation
Register a WeChat applet account and download WeChat Developer Tools . Due to the relatively high security requirements of the WeChat applet, the communication with the back-end server must use the https or wss protocol, so the domain name server must be set up in the back-end of the WeChat applet.
WeChat applet only supports instant communication via WebSocket, and MQTT Over WebSocket of EMQ X can be fully compatible with the WeChat applet. However, due to the specification restrictions of WeChat Mini Programs, EMQ X needs to pay attention to the following points when using WeChat Mini Programs to access:
- domain name that has been domain name
- The domain name needs to be WeChat public platform After logging in, add the configuration server domain name address under the server domain name on the main page
- Only supports the WebSocket/TLS protocol, and the domain name needs to be assigned a certificate issued by a trusted CA
- Due to a bug in the WeChat applet, the real Android device must use the TLS/443 port, otherwise the connection will fail (that is, the connection address cannot have a port)
Add the server domain name, here we add broker.emqx.io
as an example to the server domain name, we enter the page and select the start configuration button, enter wss://broker.emqx.io
under the socket legal domain name column, note : must start with the wss protocol, as shown below:
After the addition is completed, we will be allowed to communicate and interact with the server under the domain name address when the WeChat applet is developed.
New Project
After preparing to complete the preliminary network communication related work, we open the WeChat developer tool that has been downloaded, and click to create a new small program project on the page after opening it, as shown in the following figure:
After clicking Confirm, the WeChat Developer Tool will automatically initialize the project, and we can start development.
Install the MQTT client library
Because the applet is developed through JavaScript, you can use MQTT.js as the MQTT client library .
Program Basic Library version 1613b259f10a0e 2.2.1 or above, and Developer Tools 1.02.1808300 or above, the Mini Program supports the use of npm to install third-party packages. If you are interested, you can check official document supported by the npm for operation and use. This article is to simplify the operation process and will not use npm to install. We will create a new mqtt.js file under the utils folder, and we will directly obtain the packaged and built source code copy mqtt.js file on the MQTT.js CDN.
MQTT.js CDN address: https://unpkg.com/mqtt@4.0.1/dist/mqtt.min.js can be opened and viewed through a browser.
Note : Up to now the latest mqtt.js v4.2.8 version, when used in the applet, an undefined error of net.createConnection will be reported, and you need to roll back and use version 4.0.1.
After completion, we can directly import in the index.js main page:
import mqtt from '../../utils/mqtt'
MQTT use
This article will use the free public MQTT server provided by EMQ X Cloud as the MQTT server address for this test. The server access information is as follows:
- Broker: broker.emqx.io
- TCP Port: 1883
- SSL/TLS Port: 8883
For more details, please visit EMQ X Cloud official website , or check EMQ X Cloud document .
Connection code
The WeChat applet uses WebSocket to connect to the MQTT server wxs
protocol name in the URL address of the connection, the key code for connection and initialization data:
Page({
data: {
client: null,
host: 'broker.emqx.io:8084',
topic: 'testtopic/miniprogram',
msg: 'Hello! I am from WeChat miniprogram',
mqttOptions: {
protocolVersion: 4, //MQTT连接协议版本
clientId: 'emqx_cloud_miniprogram',
clean: true,
password: '',
username: '',
reconnectPeriod: 1000, // 1000毫秒,两次重新连接之间的间隔
connectTimeout: 30 * 1000, // 1000毫秒,两次重新连接之间的间隔
resubscribe: true // 如果连接断开并重新连接,则会再次自动订阅已订阅的主题(默认true)
},
},
connect() {
this.data.client = mqtt.connect(`wxs://${this.data.host}/mqtt`, this.data.mqttOptions)
this.data.client.on('connect', () => {
wx.showToast({
title: '连接成功'
})
})
},
})
Subscribe to topics
subscribe() {
this.data.client.subscribe(this.data.topic)
wx.showToast({
title: '主题订阅成功'
})
},
unsubscribe
unsubscribe() {
this.data.client.unsubscribe(this.data.topic)
wx.showToast({
title: '取消订阅成功'
})
},
News release
publish() {
this.data.client.publish(this.data.topic, this.data.msg)
},
Disconnect
disconnect() {
this.data.client.end()
wx.showToast({
title: '断开连接成功'
})
},
test
We simply wrote the following application interface in the applet. The application has the functions of creating connections, subscribing to topics, sending and receiving messages, canceling subscriptions, and disconnecting.
Complete project example code: https://github.com/emqx/MQTT-Client-Examples/tree/master/mqtt-client-wechat-miniprogram
Use MQTT 5.0 client tool-MQTT X as another client for message sending and receiving test.
You can see that MQTT X can normally receive messages sent from the applet. Similarly, when using MQTT X to send a message to the topic, you can also see that the applet can receive the message normally.
Summarize
To sum up, we have realized the creation of MQTT connection in the Mini Program project, simulating the scenario where the Mini Program client and the MQTT server subscribe, send and receive messages, unsubscribe, and disconnect.
Copyright statement: This article is EMQ original, please indicate the source for reprinting.
Original link: https://www.emqx.com/zh/blog/how-to-use-mqtt-in-wechat-miniprogram
Technical support: If you have any questions about this article or EMQ related products, you can visit the EMQ Q&A community https://askemq.com ask questions, and we will reply to support in time.
For more technical dry goods, please pay attention to our public account [EMQ Chinese Community].
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。