腾讯E证通实现人脸核验(.Net6)

在使用E证通之前,首先要安装腾讯的两个组件包TencentCloudSDK.Common和TencentCloudSDK.Faceid以及Ch.Gmsm

(1)获取token(此接口在我们业务中是供我们小程序或公众号调用,然后使用token调起腾讯的人脸核实小程序进行人脸核实)

 public EidTokenDto GetEidToken()
        {
            // 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey,此处还需注意密钥对的保密
            // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
            Credential cred = new()
            {
                SecretId = "",
                SecretKey = ""
            };
            // 实例化一个client选项,可选的,没有特殊需求可以跳过
            ClientProfile clientProfile = new();
            // 实例化一个http选项,可选的,没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.Endpoint = ("faceid.tencentcloudapi.com");
            clientProfile.HttpProfile = httpProfile;

            // 实例化要请求产品的client对象,clientProfile是可选的
            FaceidClient client = new(cred, "", clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            GetEidTokenRequest req = new();
            req.MerchantId = "";//商户id
            req.Config = new() { InputType = "3" };
            //添加实名认证成功以后回调结果
            Log.Information($"realnameCallbackUrl is {_config["realnameCallbackUrl"]}");//人脸核实完以后小程序或公众号的跳转地址
            req.RedirectUrl = _config["realnameCallbackUrl"];
            // 返回的resp是一个GetEidTokenResponse的实例,与请求对象对应
            GetEidTokenResponse resp = client.GetEidTokenSync(req);
            // 输出json格式的字符串回包
            Console.WriteLine(AbstractModel.ToJsonString(resp));
            Log.Information("GetEidToken @resp", resp);
            var mapperDto = _mapper.Map<EdiTokenDto>(resp);
            return mapperDto;
        }

EdiTokenDto

 /// <summary>
    /// Eid Token
    /// </summary>
    public class EdiTokenDto
    {
        /// <summary>
        /// 一次核身流程的标识,有效时间为600秒;完成核身后,可用该标识获取验证结果信息。
        /// </summary>
        [JsonProperty(propertyName: "EidToken")]
        public string EidToken { get; set; }
        /// <summary>
        /// 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
        /// </summary>
        [JsonProperty(propertyName: "RequestId")]
        public string RequestId { get; set; }
        /// <summary>
        /// 发起核身流程的URL,用于H5场景核身。
        /// </summary>
        [JsonProperty(propertyName: "Url")]
        public string Url { get; set; }
    }

(2)小程序或公众号调用此方法可查询人脸核实以后的结果

public async Task<EidStatus> GetEidResult(EidResultRequestDto eidResultRequestDto)
        {
            // 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey,此处还需注意密钥对的保密
            // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
            Credential cred = new()
            {
                SecretId = "",
                SecretKey = ""
            };
            // 实例化一个client选项,可选的,没有特殊需求可以跳过
            ClientProfile clientProfile = new();
            // 实例化一个http选项,可选的,没有特殊需求可以跳过
            HttpProfile httpProfile = new();
            httpProfile.Endpoint = ("faceid.tencentcloudapi.com");
            clientProfile.HttpProfile = httpProfile;

            // 实例化要请求产品的client对象,clientProfile是可选的
            FaceidClient client = new(cred, "", clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            GetEidResultRequest req = new GetEidResultRequest();
            req.EidToken = eidResultRequestDto.EidToken;
            // 返回的resp是一个GetEidResultResponse的实例,与请求对象对应
            GetEidResultResponse resp = client.GetEidResultSync(req);
            Log.Information("EidResult is {@resp}", resp);

            //身份核验成功
            if (resp.Text?.LiveStatus is 0)
            {
                if (resp.EidInfo?.DesKey is { Length: > 0 })
                {
                    Log.Information($"resp.EidInfo.DesKey is {resp.EidInfo.DesKey}");
                    var sessionKey = new SM2("", SM2Mode.C1C3C2)//填入自己的私钥
                  .DecryptByBase64String(resp.EidInfo.DesKey);
                    var data = new SM4(sessionKey).DecryptByBase64String(resp.EidInfo.UserInfo);
                    var result = Encoding.UTF8.GetString(data);
                    Log.Information("decryptInfo is {@result}", result);
                    JObject JObjectResult = JObject.Parse(result);
                    if (JObjectResult["idnum"] is not null)
                    {
                        //自定义业务逻辑
                        var idNumber = JObjectResult["idnum"]?.ToString();
                        ArgumentNullException.ThrowIfNull("id", idNumber);
                        var name = JObjectResult["name"]?.ToString();
                        ArgumentNullException.ThrowIfNull("name", name);
                        //用户未满18周岁也要做保存;
                        Log.Information($"Live Check Succcess");
                        //ArgumentNullException.ThrowIfNull("idNumber", idNumber);
                        IScheduler threadNew = new NewThreadScheduler(x => new Thread(x) { Name = "new program" });
                        if (IdNumberHelper.IsUnderAge(idNumber))
                        {
                            //未满18岁
                        }
                        try
                        {
                            //自定义业务逻辑
                        }
                        catch (Exception ex)
                        {
                            Log.Error("CreateUserIdAsync error {@ex}", ex);
                        }
                    }
                }
                
            }
            EidStatus eidStatus = new EidStatus();
            return eidStatus;
            // 输出json格式的字符串回包
            //Console.WriteLine(AbstractModel.ToJsonString(resp));
        }

相关类和方法

 /// <summary>
    /// 用户结果
    /// </summary>
    public class EidResultRequestDto
    {
        /// <summary>
        /// E证通流程的唯一标识,调用GetEidToken接口时生成。
        /// </summary>
        public string EidToken { get; set; }
        /// <summary>
        /// 指定拉取的结果信息,取值(0:全部;1:文本类;2:身份证信息;3:最佳截图信息;5:意愿核身朗读模式相关结果;6:意愿核身问答模式相关结果)。
        /// </summary>
        public string InfoType { get; set; } = "0";
        /// <summary>
        /// 从活体视频中截取一定张数的最佳帧。默认为0,最大为3,超出3的最多只给3张。(InfoType需要包含3)
        /// </summary>
        public int BestFramesCount { get; set; } = 0;

    }

根据身份证号码判断是否成年的方法

 /// <summary>
        /// 使用身份证号码判断用户是否未成年
        /// </summary>
        /// <param name="num"></param>
        /// <returns>true 未成年  false 成年</returns>
        public static bool IsUnderAge(string? num)
        {
            bool state = true;
            if (num != "")
            {
                string d = "";
                TimeSpan ts = new TimeSpan();
                DateTime dt = new DateTime();
                if (num.Length == 18)
                {
                    d = num.Substring(6, 8);
                    dt = DateTime.ParseExact(d, "yyyyMMdd", null);
                }
                else if (num.Length == 15)
                {
                    d = num.Substring(6, 6);
                    dt = DateTime.ParseExact(d, "yyMMdd", null);
                }
                ts = DateTime.Now.Subtract(dt);
                DateTime today = DateTime.Today;
                int age = today.Year - dt.Year;
                if (dt > today.AddYears(-age))
                    age--;
                if(age>=18)
                {
                    state = false;
                }
            }
            return state;
        }

 

posted @ 2023-01-12 16:27  tuohaibei  阅读(790)  评论(1编辑  收藏  举报