Websocket implements mqtt protocol on Alipay applet to connect to server and control hardware


The Alipay applet is open to the public and has many interesting places. So this article will implement the mqtt protocol on the Alipay applet via websocket to connect to the server and control the intelligent hardware! !


I. Introduction;

  1. 那么本系列连载的博文,都是围绕着 支付宝小程序如何实现控制 esp8266 为主线的!

2. Recall the process of transplanting Alipay applet;

  • April 26, 2019
            直到晚上9点半,我看到 GitHub 有一个 MQTT.js 库支持 支付宝小程序 mqtt的协议实现,我像是打了胰岛素一样非常兴奋,意味着我们 支付宝小程序可以控制智能设备 了,而且容易实现!
            这晚上我折腾到了凌晨12点半,早上九点还要上班呢。所幸的是,我在虚拟机(支付宝开发工具 提供)上运行并连接服务器成功了!之后我调试到真机也行了!但预览连接失败?但是我内心还是兴奋的,毕竟虚拟机是成功哇!!
    早上带熊猫眼上班,总结凌晨的开发预览到 真机就失败?我在想是不是 ios 和 android 的机子问题?于是乎我换个 ios 手机,一样地还是预览失败!按照以往的开发经验,是否 未检查域名? 还是不对!于是乎我 ios 报错的截图拿给了 支付宝小程序开发官方钉钉群里面。报错是 某个类未定义,如下截图:

    3. Register an account to understand the structure of Alipay developer tools;

    Having said so much before, let’s start with the main content of this blog post!

    Official website registration: Alipay Open Platform Scan your own Alipay APP to log in and apply!

    Official website structure development documents: Mini Program Documents - Alipay Document Center

    The debugging functions of the development tools include debugging and previewing, which can be compiled to a virtual machine simulator, or debugged and previewed to a real machine, but the Alipay app must be opened! The upload function is to put the developed version on the server, and the server can provide a QR code for testers to use!

    View the log print, click the "Debug" button at the bottom, and you can see the debug log, including your own console.log log!

    Specific development API documents use demo, which is also provided by Alipay. When creating a project, there is a template selection. You can try to select it to familiarize yourself with the development structure!

    Again, don't debug websockets on the emulator! !

    4. Points to pay special attention to during the transplantation process;

  • We know that mqtt is just a protocol, and our websocket is the bottom layer responsible for communication. It is long-connection communication implemented on the front-end JavaScript. Similar to our tcp long connection, when we clearly understand this principle. We are only responsible for the logic of how to send and receive data!

    On the server, I still use EMQ. For the Alipay applet, I still use a well-known library on GitHub: GitHub - mqttjs/MQTT.js: The MQTT client for Node.js and the browser . Mainly because he has already realized the generation and analysis of data.

    4.1 Connection

  • The url must start with wssor ws, but if it is listed, it must be wss!
  •     my.connectSocket({
          url: url,
          success: (res) => {
            console.log('connect url: ' + url)
             console.log('connect fail:'+JSON.stringify(res))

    4.1 Websocket connection and monitoring data reception;

  • What is implemented here is to open the socket and monitor the data!
  • //打开 socket
     my.onSocketOpen(function (res) {
      //被动关闭 socket 的回调
      my.onSocketClose(function (res) {
        console.log('WebSocket onSocketClose !' + res);
      //打开 socket错误回调!
      my.onSocketError(function (res) {
       my.onSocketMessage((res) => {
        if (typeof res.data === 'string') {
          var array = base64.toByteArray(res.data)
          var buffer = Buffer.from(array)
        } else {
          var reader = new FileReader()
            reader.addEventListener('load', function () {
            var data = reader.result
            if (data instanceof ArrayBuffer) data = Buffer.from(data)
            else data = Buffer.from(data, 'utf8')

    4.2 Websocket sending;

  • This step is the most critical. What is different from the WeChat applet is that it must process the data we send into base64encoding and then pass it on sendSocketMessage, and assign a value to the formal isBufferparameter to trueindicate that the current sending is a buffer array. After that, the SDK will automatically process the response. Decrypt and send!
  • I have been in this pit for a long time, so let me explain! ! The official website description link for websocket is here !
  • For specific error codes and usage, you can go to the official website to learn more!
  • //senddata 是经过base64加密的arry数组
          data: senddata,
          success: function (res) {
          fail: function (res) {
            next(new Error())

    5. How to use?

  • Connected server domain name, pay attention to the format! ! ! The prefix is ​​alis, and the port number is not limited. In my case, it is 443, which is the server port I used to connect to using the WeChat applet!
  •     const host = 'alis://www.domain.cn:443/mqtt';


  •       options: {
              protocolVersion: 4, //MQTT连接协议版本
              clientId: 'alis Mini',
              myAli: null,
              clean: true,
              password: 'xuhong123456',
              username: 'admin',
              reconnectPeriod: 1000, //1000毫秒,两次重新连接之间的间隔
              connectTimeout: 30 * 1000, //1000毫秒,两次重新连接之间的间隔
              resubscribe: true //如果连接断开并重新连接,则会再次自动订阅已订阅的主题(默认true)
        this.data.client = mqtt.connect(host, this.data.options);
        this.data.client.on('connect', function (connack) {
          my.showToast({ content: "连接成功", type: 'success' })
        that.data.client.on("message", function (topic, payload) {
          console.log(" 收到 topic:" + topic + " , payload :" + payload)
          my.showToast({ content: " 收到topic:[" + topic + "], payload :[" + payload + "]", type: 'success' })
        that.data.client.on("error", function (error) {
          console.log(" 服务器 error 的回调" + error)
          my.showToast({ content: "连接服务器失败,错误信息:" + error, type: 'exception', })
        that.data.client.on("reconnect", function () {
          console.log(" 服务器 reconnect的回调")
          my.showToast({ content: "连接服务器失败,正在重连...", type: 'exception', })
        that.data.client.on("offline", function (err) {
          console.log(" 服务器offline的回调"+JSON.stringify(err))

  • Connection renderings:


  • Project directory:

Guess you like

Origin blog.csdn.net/hanjiepo/article/details/133253331