Detailed explanation of WeChat Mini Program official face verification

Detailed explanation of WeChat Mini Program official face verification

The mini program collected user personal information and uploaded it, but was rejected:

Hello, the functions of the Mini Program page involve: collecting user biometrics (face photos or videos) and other sensitive information for identity recognition or identification,

In order to protect users' sensitive privacy identity information, the platform does not currently support this function. Please remove the relevant features and submit again.

Then I searched on Baidu and found out that I needed to apply for

wx.startFacialRecognitionVerify({})

https://api.weixin.qq.com/cgi-bin/token?appid=appid&secret=secret&grant_type=client_credential

https://api.weixin.qq.com/cityservice/face/identify/getinfo?access_token=access_token

https://api.weixin.qq.com/cityservice/face/identify/getimage?access_token=access_token

First, you need to send two parameters to the interface you applied for: name and ID number

photo.js

data: {
    openid: '',
    custName: 'Name',
    custIdCard: 'ID card number',
    verifyImg: ''
  },
  /**
   * Life cycle function--listen for page loading*/
  onLoad: function (options) {
    this.setData({
      custName: options.custName,
      custIdCard: options.custIdCard
    });
    var _this = this;
    wx.checkIsSupportFacialRecognition({
      checkAliveType: 2,
      success: function (res) {
        if (res.errCode === 0 || res.errMsg === "checkIsSupportFacialRecognition:ok") {
          //Call face recognition_this.startface(_this.data.custName.replace(/(^\s*)|(\s*)$/g, ""), _this.data.custIdCard); //ID card name, ID card number return;
        }
        wx.showToast('The WeChat version is too low, this function cannot be used temporarily, please upgrade to the latest version of WeChat')
      },
      fail: function(res){
        wx.showToast('The WeChat version is too low, this function cannot be used temporarily, please upgrade to the latest version of WeChat')
      }

    })
  },
  startface(name, idcard) {
    console.log('I'm in!!!');
    var _this = this;
    wx.startFacialRecognitionVerify({
      name: _this.data.custName, //ID card name idCardNumber: _this.data.custIdCard, //ID card number success: function (res) {
        var verifyResult = res.verifyResult; //Authentication result //Call interface wx.request({
          url: 'https://api.weixin.qq.com/cgi-bin/token?appid=wx2cafec51ec4c2153&secret=8d3e68a5a2c702673340d72d1c7db4cc&grant_type=client_credential',
          data: {

          },
          method: 'POST',
          header: {
            'content-type': 'application/json;charset=utf-8'
          },
          success: function (res) {
            console.log(res.data);
            console.log(res.data.access_token)
            var token = res.data.access_token;
            wx.request({
              url: 'https://api.weixin.qq.com/cityservice/face/identify/getinfo?access_token=' + res.data.access_token,
              data: {
                verify_result: verifyResult
              },
              method: 'POST',
              header: {
                'content-type': 'application/json;charset=utf-8'
              },
              success: function (res) {
                console.log(res.data)
                console.log('I finally succeeded...')
                wx.request({
                  url: 'https://api.weixin.qq.com/cityservice/face/identify/getimage?access_token=' + token,
                  data: {
                    verify_result: verifyResult
                  },
                  method: 'POST',
                  responseType: 'arraybuffer',
                  header: {
                    'content-type': 'application/json;charset=utf-8',
                  },
                  success: (res) => {
                    // console.log('data:image/png;base64,'+wx.arrayBufferToBases64(res))

                    console.log(res.data);
                    var base64 = wx.arrayBufferToBase64(res.data);
                    _this.setData({ verifyImg:'data:image/png;base64,'+base64})
                    wx.navigateTo({
                      url: '../msg/msg?msg=Congratulations, your information verification is successful&verifyImg=' + _this.data.verifyImg
                    });
                  },
                  fail: function (res) {
                    console.log('failed', res.data)
                  }
                })

              },
              fail: function (res) {

              }
            })
          },
          fail: function (res) {

          }
        })



        console.log(verifyResult)
        // wx.navigateTo({
        // url: '../msg/msg?msg=Face verification successful'
        // });
      },
      checkAliveType: 2, //Screen flashes (interaction mode for face verification, default 0, read numbers)
      fail: err => {
        wx.showToast('Please keep the light sufficient, face the phone directly, and without any obstruction')
        wx.navigateTo({
          url: '../msg/msg?msg=Please keep the light sufficient, face the phone directly, and without any obstruction, please exit and try again'
        });
      }
    })
  }

The main pitfall is that you have to apply for the interface several times, and the final business still needs a unionid, so you have to apply for authentication on the WeChat open platform.

Then if you want to pull the image of the verification result, you need the above https://api.weixin.qq.com/cityservice/face/identify/getimage?access_token=access_token

The returned data needs to be converted into base64 code and then displayed on the image tag. I directly pass it to the backend.

Below is my msg js code

msg.js

const app = getApp();
Page({

  /**
   * Initial data of the page */
  data: {
    msg:'',
    verifyImg:'',
    url:app.globalData.PostData
  },

  /**
   * Life cycle function--listen for page loading*/
  onLoad: function (options) {
    var timestamp = Date.parse(new Date());
    timestamp = timestamp/1000
    console.log(options)
    var that = this;
    that.setData({
      msg:options.msg,
      verifyImg:options.verifyImg
    });
    console.log(that.data.url)
    console.log(that.data.verifyImg)
    
      wx.request({
        url: that.data.url+'fileUpload!upBase64.do', //Just an example, not a real interface addressdata: {
          file:that.data.verifyImg,
          filename:timestamp,
          filedata:that.data.verifyImg
        },
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
        },
        success:function (res){
          const data = res.data
          console.log('success',data);
          //do something
        },
       fail:function(res){
         console.log('failed',res)
       }
        
      })
  }

Background upload base64 conversion code

public void upBase64() {
         System.out.println("======Start uploading pictures====");
         System.out.println(file);
        Json j = new Json();
        String FilePath = ServletActionContext.getServletContext().getRealPath(Constants.IMGPATH+"/"+Constants.PHOTOPATH);  
        File PathFile = new File(FilePath);
        try {
            // If it is IE, you need to set it to text/html, otherwise a pop-up window will pop up to download // response.setContentType("text/html;charset=UTF-8");
            response.setContentType("application/json;charset=UTF-8");

            String FileName = request.getParameter("filename");
            String FileData = request.getParameter("filedata");
            System.out.println(FileName+"**************"+FileData);
            if (null == FileData || FileData.length() < 50) {
                j.setMsg("Upload failed, data is too short or does not exist");
                j.setSuccess(false);
            } else {
                // Remove the unreasonable data at the beginning FileData = FileData.substring(30);
                FileData = URLDecoder.decode(FileData, "UTF-8");
                System.out.println("FileData="+FileData);
                byte[] data = FileUtil.decode(FileData);
                /*if (null == FileName || FileName.length() < 1) {
                    FileName = System.currentTimeMillis() + ".jpg";
                }*/
                // Write to file FileOutputStream outputStream = new FileOutputStream(new File(PathFile,FileName)); 
                outputStream.write(data); 
                outputStream.flush(); 
                outputStream.close(); 
                System.out.println(FileName+"**************"+FileData);
                j.setMsg("Upload successful");
                j.setSuccess(true);
            }
        } catch (Exception err) {
            j.setMsg("Upload failed");
            j.setSuccess(false);
            err.printStackTrace();
        }
        writeJson(j);
    }

The above is a detailed explanation of the official face authentication of WeChat Mini Program. For more information about the official face authentication of WeChat Mini Program, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • WeChat applet face recognition function code example
  • WeChat applet implements facial recognition login sample code
  • Mini Program to implement face recognition function (Baidu AI)
  • WeChat applet implements face detection function
  • WeChat applet implements face recognition
  • PHP implements WeChat applet face recognition login function

<<:  Correct use of MySQL partition tables

>>:  How to use firewall iptables strategy to forward ports on Linux servers

Recommend

Super detailed MySQL8.0.22 installation and configuration tutorial

Hello everyone, today we are going to learn about...

Vue uses Canvas to generate random sized and non-overlapping circles

Table of contents Canvas related documents Effect...

Sharing of experience on repairing MySQL innodb exceptions

A set of MySQL libraries for testing. The previou...

Prevent HTML and JSP pages from being cached and re-fetched from the web server

After the user logs out, if the back button on the...

Vue implements nested routing method example

1. Nested routing is also called sub-routing. In ...

64-bit CentOs7 source code installation mysql-5.6.35 process sharing

First install the dependent packages to avoid pro...

Solve the problem of garbled Chinese characters in Mysql5.7

When using MySQL 5.7, you will find that garbled ...

Implementation of CentOS8.0 network configuration

1. Differences in network configuration between C...

Problems and solutions when installing and using VMware

The virtual machine is in use or cannot be connec...

An example of the calculation function calc in CSS in website layout

calc is a function in CSS that is used to calcula...

Use of Linux relative and absolute paths

01. Overview Absolute paths and relative paths ar...

A detailed discussion on detail analysis in web design

In design work, I often hear designers participati...

How to use VirtualBox to simulate a Linux cluster

1. Set up HOST on the host Macbook The previous d...

How to implement simple data monitoring with JS

Table of contents Overview first step Step 2 Why ...

Learning Vue instructions

Table of contents 1. v-text (v-instruction name =...