This is the 14th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

📢 Hello everyone, I am Xiao Cheng, a sophomore front-end enthusiast

📢 this article will talk about how to access the official scan CODE SDK in the wechat public account page

📢 Thank you very much for reading

📢 May you be true to yourself and love life

In my recent project, I need to realize a scan code input function. The specific effect is to retrieve the camera after clicking the scan code button, scan the barcode and fill the decoded data into the input box. I believe that this function is very common in the daily use of mobile phones, let’s see how I step by step to achieve the pit

💡 content preview

  1. usingQuaggaProblems and bottlenecks encountered in library implementation
  2. The tap hole connected to wechat SDK points north
  3. Final solution

First, scan code preliminary Quagga

When I first came into contact with the business of scanning code, everything was brand new. I didn’t know where to start. I searched in each community first

The search term at that time was probably like this, and the result was realized by using THE API provided by HTML5. Then, I saw libraries such as Quagga and barCode. After checking the official description on NPM, I thought Quagga might be more suitable for the needs of this project. So Quagga was studied. Quagga

This library is not difficult to use, first need to introduce the library Quagga

yarn add quagga
Copy the code

Since I developed it under the React project, we need to add a DOM node in the JSX of return, which can be used to customize the placing area of camera images opened by the camera

The yourElement node in the code is used to do the camera image

Next, you need to start using Quagga, which is basically tune the method, configure the decoding, scan the area, and then you can wake up the camera, scan the code, and process the results. As a beginner, I am not very familiar with its specific code writing, so I knocked on the code all night and found an open source code entry project 👇👇👇 in a big guy’s Github warehouse

Took a look at its implementation code and then started my trample pit

First we need to initialize Quagga

We need to customize our decoding method. As for the type of code we need to scan, we can find a testing website to test it. Mine is Code39 type

Quagga.init({
  inputStream: {
    name: "Live".type: "LiveStream"./ / way
    constraints: {
      width: '790'.height: '490'
    }, // Decode area
    numberOfWorkers: navigator.hardwareConcurrency,
    target: document.querySelector('#barcodeScan') // Image output to the node
  },
  locate: true.decoder: {
    readers: ["code_39_reader"] // Decoding mode}},function (err) {
  if (err) {
    return 
  }
  Quagga.start() / / open
})
Quagga.onDetected(this.onDetect)
Copy the code

OnDetected method is called when the code is scanned successfully, which is a bit like the lifecycle, all defined and we can receive the result returned and get the codeResult scan result in this function

onDetect(res){
  // console.log(res.codeResult.code)
  Quagga.stop()
  Quagga.offProcessed()
  console.log(res.codeResult);
}
Copy the code

And then we can start crazy code, test, one night after the test, I found that it doesn’t like others in the video flow accurately decode, largely the result of the output is few right on, so that the road is not work, start had to give up the idea of, later found can directly obtain WeChat sweep code function, to achieve our demand, Therefore, the wechat SDK began to step on the road of pit

Ii. Fight wechat SDK

After the failure of Quagga, I started to integrate wechat SDK to achieve it.

First we need to introduce weixin-js-SDK so that we can use some official WX apis, such as scanQRcode

Here we call the API, which receives a configuration object, as described in the official documentation

What is more important is needResult, which determines who will process the result of code scanning. If it is 0, it will be processed by wechat. For example, when scanning an express code, it will jump to the corresponding page after scanning, which is not what we want. We can get this result in the SUCCESS callback, resultStr, which is an array, the first item is the type of the scan, the second item is the decoded value, so let’s deal with that

wx.scanQRCode({
    needResult: 1.// The default value is 0, the scan result is processed by wechat, 1 directly returns the scan result,
    scanType: ["qrCode"."barCode"].// You can specify whether to scan a two-dimensional code or a one-dimensional code
    success: function (res) {
        let result = res.resultStr.split(', ') [1]; // If needResult is 1, scan the result
    },
    fail: function (err) {
        console.log('error');
        console.log(err); }})Copy the code

So we have a simple sweep function written, which is really convenient, just need to bind to the event handling callback can be called. Is it really that simple?

Since we are using wechat open capability, we need to configure and use the official wx.config

We need to configure our appId and a signature and we need to configure the API that we need to use

wx.config({
    debug: false.// If debug mode is enabled, the return value of all API calls will be displayed in the client alert. If you want to view the parameters passed in, you can open it in the PC, and the parameter information will be printed in the log.
    appId, // Mandatory, the unique identifier of the public account
    timestamp, // Mandatory to generate the timestamp of the signature
    nonceStr, // Mandatory to generate a random string of signatures
    signature,// Mandatory, signature
    jsApiList: ["scanQRCode"] // Mandatory, a list of JS interfaces to be used
});
Copy the code

Signing these configuration items requires the background brother to return, and we need to pass our current URL to the back end, which is used to generate the pinout

Note: must be dynamic, write dead will have bugs

So we call the interface and the back end returns a few arguments

const data = await getWxKey({ url: window.location.href.split(The '#') [0]})Copy the code

There are a few things to be aware of here

  1. Obtain WeChatAPIYou need to useaccess_tokenI don’t know how to solve this problem. It should be through wechat public numberaddIdTo apply for the
  2. Passed to the back endurlIs required to passDynamic accessYes, or there might beinvalid signatureSignature error

At the code level, that’s all we can do. There’s not much front-end code logic, it’s all API calls. The complete code is as follows

const openCamera = async() = > {const data = await getWxKey({ url: window.location.href.split(The '#') [0]})const { appId, timestamp, nonceStr, jsKey: signature } = data.data
    wx.config({
        debug: false.// If debug mode is enabled, the return value of all API calls will be displayed in the client alert. If you want to view the parameters passed in, you can open it in the PC, and the parameter information will be printed in the log.
        appId, // Mandatory, the unique identifier of the public account
        timestamp, // Mandatory to generate the timestamp of the signature
        nonceStr, // Mandatory to generate a random string of signatures
        signature,// Mandatory, signature
        jsApiList: ["scanQRCode"] // Mandatory, a list of JS interfaces to be used
    });
    wx.ready(() = > {
        wx.scanQRCode({
            needResult: 1.// The default value is 0, the scan result is processed by wechat, 1 directly returns the scan result,
            scanType: ["qrCode"."barCode"].// You can specify whether to scan a two-dimensional code or a one-dimensional code
            success: function (res) {
                let result = res.resultStr.split(', ') [1]; // If needResult is 1, scan the result
                form.setFieldsValue({ orderNumber: result })
            },
            fail: function (err) {
                console.log(err); }})})}Copy the code

However, our scanning function is still not available. We also need to configure our interface domain name on wechat public platform, otherwise we will get 👇👇👇

We need to configure the JS interface security domain name on the wechat public platform

In this way, our problem can be solved easily. When configuring the secure domain name, pay attention to the access domain name do not start the proxy, otherwise the binding will fail


So far our requirements have been completed, the article may look easy, but the actual operation will use a lot of various problems, I hope this article can help you with similar needs

Tips: When you encounter a question, you can try to find the answer on wechat, or you can check the official documents

Finally, I may not be clear enough in many places, please forgive me

💌 if the article has any mistakes, or have any questions, welcome to leave a message, also welcome private letter exchange