Telefone móvel H5 upload de imagem do cartão de identificação + Alibaba Cloud ID card frente e verso reconhecimento de foto

Primeiro, a interface é a seguinte:

Carteira de identidade
A
idéia geral da ZUI e da camada js citadas no código H5 é clicar na parte frontal ou traseira do cartão de identificação para selecionar ou tirar um evento fotográfico para fazer upload de
fotos.Como as fotos tiradas pelo celular são muito grandes, darei o próximo passo para o cliente sem concluir a imagem Operação então aqui o valor inicial do próximo botão é cinza

O indicador de carregamento da ZUI foi usado durante o upload
Indicador de carregamento
Indicador de carregamento

O código é o seguinte

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

Atualize o valor na entrada oculta após a conclusão do upload do ajax

  $.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", "");
                }
            }
        });

O formato do meu retorno bem-sucedido aqui é o seguinte:

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

Quando as duas imagens são carregadas, js muda a próxima etapa para azul e executa a
mesma etapa. Da mesma forma, também devemos adicionar um indicador de carregamento quando o cartão de identificação for verificado para evitar que o cliente não conheça o processo

  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");
                    }
                }
            });


        }

    }

Aqui, a frente e a parte de trás do cartão de identificação verificam se usamos a API de reconhecimento de cartão de identificação do Alibaba Cloud Market

API de reconhecimento de cartão de identificação
O URL é o seguinte: Identificação do cartão de identificação

Como usei .net para escrever o plano de fundo, só posso postar aqui.Para outros códigos da rede, consulte a modificação:
Como nosso sistema inseriu o número de identificação anteriormente, também usaremos o número de identificação identificado depois que o reconhecermos.
Contraste com o sistema para evitar o uso de cartões de identificação de outras pessoas para confundir a situação

   [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;
        }
    }
}

Download front-end, por favor clique em mim

Não publicarei o código de back-end.Se necessário, você pode ver a página de detalhes do código-fonte de cada idioma no exemplo de solicitação abaixo da página de detalhes do perfil do Alibaba Cloud
.
Insira a descrição da imagem aqui

Se você não entender em outros lugares, adicione o QQ do blogueiro: 864015769 para consulta e adicione notas à sua atenção ao adicionar (como consulta de identificação com foto do cartão de identificação)

Publicado 29 artigos originais · Gosto 11 · Visita 10.000+

Acho que você gosta

Origin blog.csdn.net/u010840685/article/details/105245479
Recomendado
Clasificación