手机H5上传身份证图片+阿里云身份证正反面照片识别

热门
173

首先界面如下所示:

IDCard
H5代码中引用了ZUI和Layer的js
大致思路就是点击身份证正面或者反面时候出发选中或者拍照事件上传图片
由于现在手机拍照的图片都很大,所以我这里为了客户没有传完图就进行下一步操作所以这里下一步按钮初始值是灰色的

在上传过程中使用了ZUI的加载指示器
加载指示器
加载指示器

代码如下

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

在ajax上传完成后更新隐藏input中的值

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

我这里成功返回的格式如下所示:

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

当2张图片都上传了的时候js才会把下一步改为蓝色并执行一下步
同样我们在身份证验证的时候也要加上加载指示器避免客户不知道进程

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


        }

    } 

这里身份证正反面验证我们用到了阿里云云市场的身份证识别API

身份证识别API
网址如下:身份证识别

由于我是用的.net写后台这里只能贴点.net代码其他的代码的请参考修改:
由于我们系统之前是录入了身份证号的所以我们识别出来过后还会拿识别出来的身份证号和
系统内的对比避免使用他人身份证蒙混过关的情况

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

前端下载请点击我

后端代码我就不贴了要是需要的话可以在阿里云简介的详情页面下面的请求实例下面看各个语言的源码
详情页
在这里插入图片描述

最近热帖
MVC的博客开发(一)登录注册 1611
关于 1058
c# asp.net mvc 开发的正方教务助手(二) 1019
MVC的博客开发(二)登录注册 960
MVC的博客开发(三)登录注册 891
c# asp.net mvc 开发的正方教务助手(一) 881
安卓注册手机短信验证码验证的案例-02 802
安卓注册手机短信验证码验证的案例-01 715