Mobile phone H5 upload ID card picture + Alibaba Cloud ID card front and back photo recognition

First, the interface is as follows:

IDCard
The
general idea of ZUI and Layer js quoted in the H5 code is to click on the front or back of the ID card to select or take a photo event to upload pictures.
Since the pictures taken by the mobile phone are very large, I will take the next step for the customer without finishing the picture Operation so here the initial value of the next button is gray

The ZUI loading indicator was used during the upload
Loading indicator
Loading indicator

code show as below

  $("#faceenddiv").attr("data-loading", "正在努力上传中...");
  $("#faceenddiv").attr("class", "panel load-indicator loading");
  $("#backenddiv").attr("data-loading", "正在努力上传中...");
  $("#backenddiv").attr("class", "panel load-indicator loading");

Update the value in hidden input after ajax upload is complete

  $.ajax({
            url: "你上传图片的地址",
            type: 'POST',
            cache: false,
            data: data,
            processData: false,
            contentType: false,
            success: function (data) {
                isupload = false;//上传成功后标识上传中字段为false
                if (el === "face-result") {
                    $("#faceenddiv").attr("data-loading", "");
                    $("#faceenddiv").attr("class", "");
                } else {
                    $("#backenddiv").attr("data-loading", "");
                    $("#backenddiv").attr("class", "");
                }
                var item = JSON.parse(data);
                if(item.issuccess == false) {
                    layer.msg(item.mess, { icon: 5 });
                    return;
                } else {
                    layer.msg('上传图片成功', { icon: 6 });
                    if (el === "face-result") {
                        $("#IdCardFaceImg").val(item.mess);
                    } else {
                        $("#IdCardbackImg").val(item.mess);
                    }
                    var faceimgurl = $("#IdCardFaceImg").val();
                    var backimgurl = $("#IdCardbackImg").val();

                    if (faceimgurl != null && faceimgurl.length > 0 && backimgurl != null && backimgurl.length > 0) {
                        $("#btnssure").css("background-color", "#1E90FF");
;                    }
                }
               
               
            },
            error: function (r) {
                isupload = false;//上传失败后标识上传中字段为false

                layer.msg('上传图片发生错误', { icon: 5 });
                if (el === "face-result") {
                    $("#faceenddiv").attr("data-loading", "");
                    $("#faceenddiv").attr("class", "");
                } else {
                    $("#backenddiv").attr("data-loading", "");
                    $("#backenddiv").attr("class", "");
                }
            }
        });

The format of my successful return here is as follows:

{
    "mess": "/Uploads/58097734-e2c3-4022-a5e9-a62b01204248/image/20200401/1457195468.jpg",//图片地址或者错误原因
    "issuccess": true//是否成功
}

When both pictures are uploaded, js will change the next step to blue and perform the
same step. Similarly, we must also add a loading indicator when the ID card is verified to avoid the customer not knowing the process

  function sure() {
        var Guid = $("#Guid").val();
        var idcardfaceimgurl = $("#IdCardFaceImg").val();
        var idcardbackimgurl = $("#IdCardbackImg").val();
        if (idcardfaceimgurl == null || idcardfaceimgurl.length <= 0 || idcardbackimgurl == null || idcardbackimgurl.length <= 0) {

            layer.msg('请先上传身份证正反面图片!', { icon: 5 });
        } else {
            $("#content").attr("data-loading", "正在验证身份证中...");
            $("#content").attr("class", "panel load-indicator loading");
          
            $.ajax({
                type: 'post',
                url: '后台验证地址',
                data: { Guid: Guid, IdCardFaceImg: idcardfaceimgurl, IdCardbackImg:idcardbackimgurl},
                dataType: "json",
                success: function (result) {
                    if (result.id > 0) {
                        layer.msg(result.result, { icon: 6 });
                        $("#content").attr("data-loading", "");
                        $("#content").attr("class", "content");
                        location.href = "xxxxx/handletype?Guid=" + Guid;
                    }else {
                        layer.msg(result.result, { icon: 5 });

                        $("#content").attr("data-loading", "");
                        $("#content").attr("class", "content");
                    }
                }
            });


        }

    }

Here the front and back of the ID card verify that we used the ID card recognition API of Alibaba Cloud Market

ID card recognition API
The URL is as follows: ID card identification

Since I used .net to write the background, I can only post here. For other codes of the net, please refer to the modification:
Since our system has previously entered the ID number, we will also take the identified ID number after we recognize it.
Contrast with the system to avoid using other people's ID cards to confuse the situation

   [HttpPost]
        public ActionResult ToValidateIDcard(string Guid,string IdCardFaceImg,string IdCardbackImg)
        {
         
            if (Guid.IsNullOrEmpty())
            {
                return Json(new { id = -1, result = "Guid不能为空!" });
            }

            if (IdCardFaceImg.IsNullOrEmpty())
            {
                return Json(new { id = -1, result = "身份证正面不能为空!" });
            }
            if (IdCardbackImg.IsNullOrEmpty())
            {
                return Json(new { id = -1, result = "身份证反面不能为空!" });
            }
            CarInfo carinfo = DataService.GetModel<CarInfo>(o => o.Guid == Guid);
            carinfo.IdCardFaceImg = IdCardFaceImg;
            carinfo.IdCardbackImg = IdCardbackImg;
            string idcardnum = carinfo.CarOwnerIdCard;

            string Validateback = IDCardValidate.Validate(TLConfig.OOS_URL + IdCardbackImg, "face");
            string Validateface = IDCardValidate.Validate(TLConfig.OOS_URL + IdCardFaceImg, "back");

            try
            {

                IDCardFace face = JsonConvert.DeserializeObject<IDCardFace>(Validateback);
                IDCardBack back = JsonConvert.DeserializeObject<IDCardBack>(Validateface);
                if (face.success == "true")
                {
                    if (face.num != idcardnum)
                    {
                        return Json(new { id = -1, result = "身份证背面验证失败照片识别身份证号和系统中不匹配!" });
                    }
                }
                else
                {
                    return Json(new { id = -1, result = "身份证背面验证失败请上传正确清晰的照片!" });
                }
                if (back.success != "true")
                {

                    return Json(new { id = -1, result = "身份证正面验证失败请上传正确清晰的照片!" });
                }
            }
            catch (Exception e)
            {
                return Json(new { id = -1, result = "身份证验证失败请重新上传照片!" });
            }
            int result = DataService.Update(carinfo);
            if (result > 0)
            {
                return Json(new { id = result, result = "身份证验证成功!" });
            }
            return Json(new { id = -1, result = "身份证验证失败!" });
        }
        #endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Security.Cryptography.X509Certificates;
using System.Net;
using System.Net.Security;

namespace Answer2u.Web.Admin.Controllers
{
    public class IDCardValidate
    {
        public static string Validate(string imgurl,string side)
        {
            String url = "https://dm-51.data.aliyun.com/rest/160601/ocr/ocr_idcard.json";
            String appcode = "你的appcode";
            //如果输入带有inputs, 设置为True,否则设为False
            bool is_old_format = false;
            //如果没有configure字段,config设为''
            //String config = '';
            String config = "{\\\"side\\\":\\\""+ side +"\\\"}";
            String method = "POST";
            String querys = "";
            String bodys;
            if (is_old_format)
            {
                bodys = "{\"inputs\" :" +
                                    "[{\"image\" :" +
                                        "{\"dataType\" : 50," +
                                         "\"dataValue\" :\"" + imgurl + "\"" +
                                         "}";
                if (config.Length > 0)
                {
                    bodys += ",\"configure\" :" +
                                    "{\"dataType\" : 50," +
                                     "\"dataValue\" : \"" + config + "\"}" +
                                     "}";
                }
                bodys += "]}";
            }
            else
            {
                bodys = "{\"image\":\"" + imgurl + "\"";
                if (config.Length > 0)
                {
                    bodys += ",\"configure\" :\"" + config + "\"";
                }
                bodys += "}";
            }
            HttpWebRequest httpRequest = null;
            HttpWebResponse httpResponse = null;

            if (0 < querys.Length)
            {
                url = url + "?" + querys;
            }

            if (url.Contains("https://"))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                httpRequest = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
            }
            else
            {
                httpRequest = (HttpWebRequest)WebRequest.Create(url);
            }
            httpRequest.Method = method;
            httpRequest.Headers.Add("Authorization", "APPCODE " + appcode);
            //根据API的要求,定义相对应的Content-Type
            httpRequest.ContentType = "application/json; charset=UTF-8";
            if (0 < bodys.Length)
            {
                byte[] data = Encoding.UTF8.GetBytes(bodys);
                using (Stream stream = httpRequest.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            try
            {
                httpResponse = (HttpWebResponse)httpRequest.GetResponse();
            }
            catch (WebException ex)
            {
                httpResponse = (HttpWebResponse)ex.Response;
            }

            if (httpResponse.StatusCode != HttpStatusCode.OK)
            {
                Console.WriteLine("http error code: " + httpResponse.StatusCode);
                Console.WriteLine("error in header: " + httpResponse.GetResponseHeader("X-Ca-Error-Message"));
                Console.WriteLine("error in body: ");
                Stream st = httpResponse.GetResponseStream();
                StreamReader reader = new StreamReader(st, Encoding.GetEncoding("utf-8"));
                Console.WriteLine(reader.ReadToEnd());
                ErrorWriteLog.WriteHTLog("验证身份证失败码", httpResponse.StatusCode.ToString()+",img:" + imgurl);
                ErrorWriteLog.WriteHTLog("验证身份证失败", reader.ReadToEnd());
                return reader.ReadToEnd();
            }
            else
            {

                Stream st = httpResponse.GetResponseStream();
                StreamReader reader = new StreamReader(st, Encoding.GetEncoding("utf-8"));
                return reader.ReadToEnd();
            }
        
        }
        public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true;
        }
    }
}

Front-end download please click me

I will not post the back-end code. If necessary, you can see the source code details page of each language under the request example below the details page of Alibaba Cloud profile
.
Insert picture description here

If you do n’t understand in other places, you can add the blogger QQ: 864015769 for consultation, and add notes to your attention when adding (such as ID card photo identification consultation)

Published 29 original articles · Like 11 · Visits 10,000+

Guess you like

Origin blog.csdn.net/u010840685/article/details/105245479