OCR ID Card Recognition Process in WeChat Mini Program

request for access

Log in to the WeChat applet development platform

Settings -> Third Party Settings -> Plug-in Management

Insert picture description here

Click Add, search for OCR to add, as shown in the figure below
Insert picture description here

Click on the details to see the development documentation of the plugin

Document portal

It is worth noting here that we must purchase WeChat OCR recognition from the open platform

Insert picture description here
Calling the identification interface directly without purchasing will report error 101003. The official document does not explain that 101003 is because there is no purchase.

Buy here one hundred times a day, free for up to a year

Code

If it is written in the native WeChat applet, just import it directly according to the development document

OCR.idcard as an example

Because uni-app does not have a plug-in that can support the OCR function of WeChat applets, we directly use WeChat's native api method in uni-app for adaptation

According to official documents, we divide the steps into three steps

  1. Get accessToken
  2. Select a local picture (or select the network address of the successfully uploaded picture)
  3. Call the interface for identification

Obtaining accesstoken requires appId and secret, these two parameters can be viewed on the Mini Program Open Platform

Code directly

// 获取accessToken
    getAccessToken() {
    
    
      return new Promise((resolve, reject) => {
    
    
        uni.request({
    
    
          url: 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=*****&secret=***',
        }).then(response => {
    
    
          // 这里的返回结果是经过我们自己封装的,请根据自己的实际情况返回
          if(response[1].statusCode === 200) {
    
    
            resolve(response[1].data.access_token)
          } else {
    
    
            reject(error)
          }
        }).catch(error => {
    
    
          reject(error)
        })
      }) 
    }
    // OCR证件识别 - 仅用于微信小程序
    async identifyIDcard() {
    
    
      const accessToken = await this.getAccessToken()
      console.log(accessToken)
      // 这里使用的是uni,但并不影响,改成wx也可行,不比纠结
      uni.chooseMedia({
    
    
        count: 1,
        sourceType: ['album', 'camera'],
        success(res) {
    
    
          console.log(res.tempFiles[0].tempFilePath)
          // 这里亲测了使用上传文件的临时缓存地址不可辨别!!!
          // 请使用上传成功后的网络地址或将图片作为 FormData 直接上传
          uni.request({
    
    
            url: 'https://api.weixin.qq.com/cv/ocr/idcard?type=photo&img_url=' + encodeURIComponent('https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2582405855,2667866727&fm=26&gp=0.jpg') + '&access_token=' + accessToken,
            method: 'POST',
            success: function(response) {
    
    
              console.log(response)
              if(response.statusCode === 200 && response.data.errcode === 0) {
    
    
                wx.showToast({
    
    
                  title: response.data.name + '识别成功'
                })
              } else {
    
    
                wx.showToast({
    
    
                  title: response.data.errmsg
                })
              }
            },
            fail: function(error) {
    
    
              wx.showToast({
    
    
                title: error
              })
            }
          })
        }
      })
    }

I randomly found a sample picture from the Internet:

Insert picture description here

At this point, what we need is enough

It is worth noting that although I wrote chooseImage, it is actually not used

Let's take a look at the execution result

Insert picture description here
Recognition is successful!

Remember: The reason for the 101003 error is that you did not apply for a free trial permission

Use the encapsulated button directly

This method can only use online scanning, and cannot use online addresses

The logic is: upload to the server after the scan is successful

The rest of the application permissions are the same, the JS method does not need to be written

Add the modules used in app.json and page.json respectively

"usingComponents": {
    
    
        "ocr-navigator": "plugin://ocr-plugin/ocr-navigator"
      }

Then write in wxml:

<!-- 直接调用按钮,无需自己写方法 -->
    <ocr-navigator bind:onSuccess="success" certificateType="idCard" :opposite="false">
      <button type="primary" class="mainBtn">拍摄身份证头像面</button>
    </ocr-navigator>

Insert picture description here

The style is as above, you can modify it yourself

Let's debug it on the real machine

This is the identity information returned after the call is successfully recognized

Insert picture description here

After the recognition is successful, we can upload the correct license picture to the server

Guess you like

Origin blog.csdn.net/lb1135909273/article/details/108747092