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

Docker configuration Alibaba Cloud image acceleration pull implementation

Today I used docker to pull the image, but the sp...

Introduction to the usage of exists and except in SQL Server

Table of contents 1. exists 1.1 Description 1.2 E...

Detailed steps to configure my.ini for mysql5.7 and above

There is no data directory, my-default.ini and my...

Detailed explanation of the loading rules of the require method in node.js

Loading rules of require method Prioritize loadin...

Reasons why MySQL cancelled Query Cache

MySQL previously had a query cache, Query Cache. ...

jQuery realizes dynamic particle effect

This article shares the specific code of jQuery t...

Flex layout makes adaptive pages (syntax and examples)

Introduction to Flex Layout Flex in English means...

Web componentd component internal event callback and pain point analysis

Table of contents Written in front What exactly i...

Win32 MySQL 5.7.27 installation and configuration method graphic tutorial

The installation tutorial of MySQL 5.7.27 is reco...

TypeScript namespace merging explained

Table of contents Merge namespaces with the same ...

Detailed explanation of redundant and duplicate indexes in MySQL

MySQL allows you to create multiple indexes on th...

XHTML Getting Started Tutorial: Using the Frame Tag

<br />The frame structure allows several web...

Nginx URL rewriting mechanism principle and usage examples

URL rewriting helps determine the preferred domai...

js uses Canvas to merge multiple pictures into one implementation code

Solution function mergeImgs(list) { const imgDom ...