[Alipay applet in Control hardware ① Applicants for personal Alipay small program developed personal accounts, pay attention to talk about those pits logs, integrated mqtt agreement Alipay small program to achieve basic communication!

Disclaimer: This article is a blogger and a half stars heart bent on a blood knock out original works, shall not be reproduced without the bloggers allowed, Thanks for your support. https://blog.csdn.net/xh870189248/article/details/89763591

[Alipay applet in Control hardware ① Applicants for personal Alipay under the personal account program development, understanding Alipay small program framework, intelligent control do the first step!


I. Introduction;


    I thank you for your continued support half stars heart, when you read this article, I have achieved control over our esp8266 the Alipay applet. I'm sure my article series is the first domestic open source document, I hope you remember it, some do not steal, defenders of the news ! I will maintain, and is now ready to put some framework based on the principles of the code and do the next note!

    I am very much opposed to copying the work, especially after the kind of plagiarism on other websites column, not the scum of the original posted link .

    Only I hope that when someone asked Alipay applet can control smart devices? You can be the first to say out loud "Yes!" , And I put this series of articles showed ta see!

    So this series of serial Bowen, revolves around how to achieve Alipay applet control esp8266 main line! Everything else is secondary line! !


Second, the small treasure memories of the payment process of the transplant procedure;


  • April 2019 26

    Early exposure Alipay small program ,, after all, listen to the older generation say that this can support the development of personal, very smooth registered a success! He began to study its structure, because I am more familiar with the program development of small micro-channel, see demo Alipay I suddenly felt this small and micro-channel program about the same!

    Until 21:30, I saw a MQTT.js GitHub repository support payment agreement treasure applet mqtt realization hit me like a very excited, like insulin, which means we can control program Alipay small smart devices, and it is easy to achieve !
    That night I toss to 12:30, nine in the morning to go to work yet. Fortunately, I was in a virtual machine (Alipay development tools) to run on the server and connect successful! After I have real machine debugging to the line! But the preview connection failed? But my heart still excited, after all, the virtual machine is successful wow! !


  • April 2019 27

In the morning to go to work with a black eye, summarized the development of the early morning to preview the real machine will fail? I think the machine is not a problem of ios and android? Ever since I change ios phone, or equally preview failed! According to past development experience, did not check whether the domain name? Right or wrong! Ever since I showed a screenshot of the error ios Alipay small group program development official nails inside. Error is a class is not defined, the following screenshot:

Here Insert Picture Description


  • April 2019 28

This day is Sunday, our normal work. Attention was finally nailed the official website of the group continue to send the issue to the reason that the addition of technical support, I summed up a few small problems currently existing procedures:

  • Development tools for the virtual machine websocketis not the same and the real machine environment on a virtual machine connected js is successful, but the real machine does not work, it does not mean that real machine and implement some js communication.
  • Developer tools to debug real machine is successfully connected, but a preview to the real machine has failed! The development time so I was very upset, has been a problem in your own code, but later found that 2's environment is not the same!
  • Finally, I was using the system to read the document websocket Alipay applet. Some methods have achieved, but the wonder is on a virtual machine is not receiving any message server callbacks ! I got the data process of docking micro letter I had found transmit data processing is not wrong! What the hell, after the 1:00 I get a little sleepy, a preview to the real machine under test, really received the message server! You ah! Success! Have to say, the current developer tools Alipay virtual machine emulator is really a pit! ! Strongly suggest that you use the debugging real machine! ! !

Third, the registered account Alipay developer tools to understand the structure;


   Said in front of so many things, let's start talking about the main contents of this blog it!

   Official website registration: https://mini.open.alipay.com own Alipay APP scanning application login!

   Development of the structure of the document's official website: https://docs.alipay.com/mini/developer/getting-started

   Development tools, debugging functions to debug, preview, can be compiled to a virtual machine emulator, you can debug and preview to the real machine, but must open Alipay app! Upload function is to develop this version on the server, the server can provide two-dimensional code to testers!

   View log print, click on the bottom of the "Debug" button, you can see the debug log, including their console.log log!

   Specific development API documentation using the demo, Alipay is also provided, in creating a project when there is a template selection, you can try to select him familiar with the structure developed under!

   Again, do not websocket debugging on simulator! !

Here Insert Picture Description


Fourth, the process of migration point special attention;


   We know, mqtt is just a protocol, and we websocket is responsible for the underlying communications, which is implemented on the front end of a long junctional communication JavaScript. Similar to our long-tcp connection, when we know this principle. We only responsible for how data transceiver logic on it!

   On the server, I use EMQ. Alipay small program I use is still above a famous library GitHub: https://github.com/mqttjs/MQTT.js . Mainly because he already achieved generate and parse data.


4.1 connection

  • url must be based wssor ws, but if the shelves, it must be wssup!
  my.connectSocket({
    url: url,
    success: (res) => {
      console.log('connect url: ' + url)
    }, 
    fail:(res)=>{
       console.log('connect fail:'+JSON.stringify(res))
    }
  })

4.1 websocket monitoring data connection and received;

  • Achieve here is to open the socket, and monitoring of data!
 //打开 socket
 my.onSocketOpen(function (res) {
    stream.setReadable(proxy)
    stream.setWritable(proxy)
    stream.emit('connect')
  })
 
  //被动关闭 socket 的回调
  my.onSocketClose(function (res) {
    console.log('WebSocket onSocketClose !' + res);
    stream.end()
    stream.destroy()
  })

  //打开 socket错误回调!
  my.onSocketError(function (res) {
    stream.destroy(res)
  })

  //监听到socket的数据下发回调
   my.onSocketMessage((res) => {
    //这里主要是对数据的判断,因为有时候是字符串,有时候是数组!
    if (typeof res.data === 'string') {
      var array = base64.toByteArray(res.data)
      var buffer = Buffer.from(array)
      proxy.push(buffer)
    } 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')
        proxy.push(data)
      })
      reader.readAsArrayBuffer(res.data)
    }
  });

4.2 websocket transmission;

  • This step is the most critical, and small micro-channel program is not the same: he must put our data processing is sent base64encoded, and then later passed sendSocketMessage, and the parameter isBufferassigned to truerepresent the current transmission buffer is an array, then SDK automatically handles Anti decryption sent out!
  • I just stepped in the pit for a long time, in order to explain the next! ! For websocket official website explained the link here !
  • Specific error code, and you can use the network to understand Quguan next!
    //senddata 是经过base64加密的arry数组
    my.sendSocketMessage({ 
      data: senddata,
      isBuffer:true,
      success: function (res) {
        next()
      },
      fail: function (res) {
        next(new Error())
      }
    })

5, how to use?


  • Domain name server connections, pay attention to the format! ! ! Prefix is ​​alis, the port number is not limited, I have here is that the server port 443 is before I use micro letter applet connected!

    const host = ‘alis://www.domain.cn:443/mqtt’;

  • Configuration:

  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)
    } 
  • Start connection
this.data.client = mqtt.connect(host, this.data.options);
this.data.client.on('connect', function (connack) {
  my.showToast({ content: "连接成功", type: 'success' })
})
  • other:
 //服务器下发消息的回调
    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))
    })
  • FIG connected Effect:

Sixth, download


  • Read and modify the project requires some basic front-end development, because this is bloggers do it late at night a few days, so close some tips! Bowen Engineering Download: http://www.demodashi.com/demo/15340.html , what problems can leave a message under article!

Guess you like

Origin blog.csdn.net/xh870189248/article/details/89763591