身份证照片获取个人信息与银行卡4要素验证

目录

通过身份证照片获取个人信息

银行卡4要素验证(腾讯接口)


通过身份证照片获取个人信息

百度API接口文档

图片走丢了

 

百度的接口免费适合学习和应用前期初步的使用,

如果验证的图片为空或不为身份证则不计算在次数当中。

 

将文档的内容转化成代码:

<?php
/**
 * 通过上传到服务器的图片路径进行图片识别
 * 发起http post请求(REST API), 并获取REST请求的结果
 * @param string $url
 * @param string $param
 * @return - http response body if succeeds, else false.
 */
function request_post($url = '', $param = '')
{
    if (empty($url) || empty($param)) {
        return false;
    }

    $postUrl = $url;
    $curlPost = $param;
    // 初始化curl
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $postUrl);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    // 要求结果为字符串且输出到屏幕上
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    // post提交方式
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
    // 运行curl
    $data = curl_exec($curl);
    curl_close($curl);

    return $data;
}
function get_access_token(){
    $url_t = 'https://aip.baidubce.com/oauth/2.0/token';

    $client_id = "你的 Api Key";
    $client_secret = "你的 Secret Key";

    $body_t = array(
        "grant_type" => "client_credentials",//固定参数
        "client_id" => $client_id,
        "client_secret"=> $client_secret
    );

    $res_t = request_post($url_t, $body_t);
    
    $target = json_decode($res_t,true)['access_token'];

    return $target;
}

$imgurl = $_GET['imgurl'];//图片的绝对路径

$token = get_access_token();
$url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=' . $token;
$img = file_get_contents($imgurl);

$img = base64_encode($img);
$id_card_side ="front";

    $bodys = array(
        "image" => $img,
        "id_card_side" =>$id_card_side
    );
$res = request_post($url, $bodys);

var_dump($res);
$id_card_side ="front";

front:身份证含照片的一面;back:身份证带国徽的一面

因项目只需要身份证正面信息所以没做判断,直接写死了。

个人写法 —— 无需将图片存储至服务器

<body>
    <input type="file" id="upLoad" name="image">
    <!-- 显示上传之后的图片 -->
    <div id='previewImg'>
        <img src="" id='viewImg' />
</body>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
    $('#upLoad').on('change', function() {
        var filePath = $(this).val(), //获取到input的value,里面是文件的路径
            fileFormat = filePath.substring(filePath.lastIndexOf(".")).toLowerCase(),
            imgBase64 = '', //存储图片的imgBase64
            fileObj = document.getElementById('upLoad').files[0];
        //上传文件的对象,要这样写才行,用jquery写法获取不到对象
        // 检查是否是图片
        if (!fileFormat.match(/.png|.jpg|.jpeg/)) {
            alert('上传错误,文件格式必须为:png/jpg/jpeg');
            return;
        }
        // 调用函数,对图片进行压缩
        directTurnIntoBase64(fileObj, function(imgBase64) {
            imgBase64 = imgBase64; //存储转换的base64编码
            apitest(imgBase64);
            // console.log(imgBase64);
            $('#viewImg').attr('src', imgBase64); //显示预览图片
        });
    });
    // 不对图片进行压缩,直接转成base64
    function directTurnIntoBase64(fileObj, callback) {
        var r = new FileReader();
        // 转成base64
        r.onload = function() {
            //变成字符串
            imgBase64 = r.result;
            // console.log(imgBase64);
            callback(imgBase64);
        }
        r.readAsDataURL(fileObj); //转成Base64格式
    }
    // 对图片进行压缩
    function compress(fileObj, callback) {
        if (typeof(FileReader) === 'undefined') {
            console.log("当前浏览器内核不支持base64图标压缩");
            //调用上传方式不压缩
            directTurnIntoBase64(fileObj, callback);
        } else {
            try {
                var reader = new FileReader();
                reader.onload = function(e) {
                    var image = $('<img/>');
                    image.load(function() {
                        square = 700, //定义画布的大小,也就是图片压缩之后的像素
                            canvas = document.createElement('canvas'),
                            context = canvas.getContext('2d'),
                            imageWidth = 0, //压缩图片的大小
                            imageHeight = 0,
                            offsetX = 0,
                            offsetY = 0,
                            data = '';
                        canvas.width = square;
                        canvas.height = square;
                        context.clearRect(0, 0, square, square);
                        if (this.width > this.height) {
                            imageWidth = Math.round(square * this.width / this.height);
                            imageHeight = square;
                            offsetX = -Math.round((imageWidth - square) / 2);
                        } else {
                            imageHeight = Math.round(square * this.height / this.width);
                            imageWidth = square;
                            offsetY = -Math.round((imageHeight - square) / 2);
                        }
                        context.drawImage(this, offsetX, offsetY, imageWidth, imageHeight);
                        var data = canvas.toDataURL('image/jpeg');
                        //压缩完成执行回调
                        callback(data);
                    });
                    image.attr('src', e.target.result);
                };
                reader.readAsDataURL(fileObj);
            } catch (e) {
                console.log("压缩失败!");
                //调用直接上传方式 不压缩
                directTurnIntoBase64(fileObj, callback);
            }
        }
    }
});
function apitest(img64) {
    $.ajax({
        url: '接口的路径',
        type: 'POST',
        data: {
            imgurl: img64
        },
        dataType: 'json',
        success: function(data) {
            console.log(data);
        },
        error:function(xhr){
        console.log(xhr);
    }
    })
}
</script>

图片失踪了

图片在后端处理时是将获取的图片先base64编码后再请求接口,所以我在前端把图片进行编码压缩通过Ajax传参的形式到后台直接使用,这种方法可以无需将图片上传存储至服务器依然可以使用接口获取身份证上的信息。

<?php
header("Access-Control-Allow-Origin: *");
/**
 * 发起http post请求(REST API), 并获取REST请求的结果
 * @param string $url
 * @param string $param
 * @return - http response body if succeeds, else false.
 */
function request_post($url = '', $param = '')
{
    if (empty($url) || empty($param)) {
        return false;
    }
    $postUrl = $url;
    $curlPost = $param;
    // 初始化curl
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $postUrl);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    // 要求结果为字符串且输出到屏幕上
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    // post提交方式
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
    // 运行curl
    $data = curl_exec($curl);
    curl_close($curl);
    return $data;
}
function get_access_token(){
    $url_t = 'https://aip.baidubce.com/oauth/2.0/token';
    $client_id = "你的 Api Key";
    $client_secret = "你的 Secret Key";
    $body_t = array(
        "grant_type" => "client_credentials",//固定参数
        "client_id" => $client_id,
        "client_secret"=> $client_secret
    );
    $res_t = request_post($url_t, $body_t);
    
    $target = json_decode($res_t,true)['access_token'];
    // var_dump($target);
    return $target;
}
    // 可以直接用base64编码的图片
    // $imgurl = $_GET['imgurl'];
    $imgurl = $_POST['imgurl'];
    if(!$imgurl){
        return "empty image";
    }
    $token = get_access_token();
    $url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=' . $token;
    $img = file_get_contents($imgurl);
    $img = base64_encode($img);
    $id_card_side ="front";
   
    $bodys = array(
        "image" => $img,
        "id_card_side" =>$id_card_side
    );
    $res = request_post($url, $bodys);
    $data =json_decode($res,true);

    $identity_front = array(
        'idcard' =>$data["words_result"]['公民身份号码']['words'],
        'name' =>$data["words_result"]['姓名']['words'],
        'sex' =>$data["words_result"]['性别']['words'],
        'birth' =>$data["words_result"]['出生']['words'],
        'address' =>$data["words_result"]['住址']['words'],
        'nation' =>$data["words_result"]['民族']['words']
    );
    // var_dump($identity);
    echo json_encode($identity_front);
?>

银行卡4要素验证(腾讯接口) 好贵千万别乱玩

腾讯云开发者工具套件(SDK)下载

需要配合此包使用

密钥地址管理/生成密匙

将此PHP与SDK放在同级目录下。

BankCardVerification.php:

<?php
header("Access-Control-Allow-Origin: *");

require_once 'tencentcloud-sdk-php/TCloudAutoLoader.php';
use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Faceid\V20180301\FaceidClient;
use TencentCloud\Faceid\V20180301\Models\BankCard4EVerificationRequest;

try {

    $cred = new Credential("你的 SecretId",     
    "你的 SecretKey");
    $httpProfile = new HttpProfile();
    $httpProfile->setEndpoint("faceid.tencentcloudapi.com");
      
    $clientProfile = new ClientProfile();
    $clientProfile->setHttpProfile($httpProfile);
    $client = new FaceidClient($cred, "ap-guangzhou", $clientProfile);

    $req = new BankCard4EVerificationRequest();
    
    // 测试数据
    //$params = '{"Name":"三",
    //"BankCard":"6222222222222222222",
    //"Phone":"15776965623",
    //"IdCard":"431003199512051916"}';
    $params= $_POST['params'];

    $req->fromJsonString($params);

    $resp = $client->BankCard4EVerification($req);

    print_r($resp->toJsonString());

}
    catch(TencentCloudSDKException $e) {
        echo $e;
    }

    // 认证结果码:Result(String)
    // '0': '认证通过'
    // '-1'    : '认证未通过'
    // '-2': '姓名校验不通过'
    // '-3': '身份证号码有误'
    // '-4': '银行卡号码有误'
    // '-5': '手机号码不合法'
    // '-6': '持卡人信息有误'
    // '-7': '未开通无卡支付'
    // '-8': '此卡被没收'
    // '-9': '无效卡号'
    // '-10': '此卡无对应发卡行'
    // '-11': '该卡未初始化或睡眠卡'
    // '-12': '作弊卡、吞卡'
    // '-13': '此卡已挂失'
    // '-14': '该卡已过期'
    // '-15': '受限制的卡'
    // '-16': '密码错误次数超限'
    // '-17': '发卡行不支持此交易'
    // '-18': '服务繁忙'
// 4个输入框和样式就省略了

<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
function apitest() {
    var name = $('#name').val();
    var bankcard = $('#bankcard').val();
    var phone = $('#phone').val();
    var idcard = $('#idcard').val();
    var params = '{"Name":"' + name + 
    '","BankCard":"' + bankcard + '","Phone":"' + phone + 
    '","IdCard":"' + idcard + '"}'

    $.ajax({
        url:  'xxx/xxx/BankCardVerification.php',
        type: 'POST',
        data: {
            params: params
        },
        dataType: 'json',
        success: function(data) {
            console.log(data.Description);
        }
    })
}
</script>

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值