身份證照片獲取個人信息與銀行卡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>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章