idanalyzer / id-analyzer-php-sdk
ID扫描和验证PHP SDK,用于全球驾照、护照、身份证的扫描和身份验证,使用ID Analyzer API。
Requires
- php: >=5.4
README
这是ID Analyzer身份验证API的PHP SDK,尽管所有API都可以通过简单HTTP请求调用,如文档中所述,但您可以使用此SDK来加速服务器端开发。
我们强烈建议用户不要将客户端应用程序(如移动应用或浏览器中的JavaScript)直接连接到ID Analyzer API端点。您的API密钥可能很容易被泄露,如果您在Vault中存储客户的个人信息,他们可以使用您的API密钥获取所有用户详细信息。因此,最佳实践始终是在客户端连接到您的服务器,并在服务器端调用我们的API。
安装
通过composer安装
composer require idanalyzer/id-analyzer-php-sdk
或者,下载此软件包,并手动在src文件夹下要求PHP文件。
核心API
ID Analyzer核心API允许您使用ID图像(接受JPG、PNG、PDF)和用户自拍照片或视频,执行OCR数据提取、面部生物识别验证、身份验证、年龄验证、文档裁剪、文档验证(假ID检查)、AML/PEP合规性检查以及文件自动化。核心API具有广泛的全球覆盖范围,支持目前全球流通的超过98%的护照、驾照和身份证。
以下示例代码将从这个在加利福尼亚州颁发的样本驾照中提取数据,将其与Lena的照片进行比较,并检查ID是否真实。
// use composer autoload require("vendor/autoload.php"); // or manually load CoreAPI class //require("../src/CoreAPI.php"); use IDAnalyzer\CoreAPI; // Initialize Core API US Region with your credentials $coreapi = new CoreAPI("Your API Key", "US"); // Enable authentication and use 'quick' module to check if ID is authentic $coreapi->enableAuthentication(true, 'quick'); // Analyze ID image by passing URL of the ID image and a face photo (you may also use a local file) $result = $coreapi->scan("https://www.idanalyzer.com/img/sampleid1.jpg","","https://upload.wikimedia.org/wikipedia/en/7/7d/Lenna_%28test_image%29.png"); // All information about this ID will be returned in an associative array $data_result = $result['result']; $authentication_result = $result['authentication']; $face_result = $result['face']; // Print result echo("Hello your name is {$data_result['firstName']} {$data_result['lastName']}<br>"); // Parse document authentication results if($authentication_result){ if($authentication_result['score'] > 0.5) { echo("The document uploaded is authentic<br>"); }else if($authentication_result['score'] > 0.3){ echo("The document uploaded looks little bit suspicious<br>"); }else{ echo("The document uploaded is fake<br>"); } } // Parse face verification results if($face_result){ if($face_result['error']){ // View complete error codes under API reference: https://developer.idanalyzer.com/coreapi.html echo("Face verification failed! Code: {$face_result['error']}, Reason: {$face_result['error_message']}<br>"); }else{ if($face_result['isIdentical'] === true){ echo("Great! Your photo looks identical to the photo on document<br>"); }else{ echo("Oh no! Your photo looks different to the photo on document<br>"); } echo("Similarity score: {$face_result['confidence']}<br>"); } }
在执行ID扫描之前,您可以设置其他参数
$coreapi->enableVault(true,false,false,false); // enable vault cloud storage to store document information and image $coreapi->setBiometricThreshold(0.6); // make face verification more strict $coreapi->enableAuthentication(true, 'quick'); // check if document is real using 'quick' module $coreapi->enableBarcodeMode(false); // disable OCR and scan for AAMVA barcodes only $coreapi->enableImageOutput(true,true,"url"); // output cropped document and face region in URL format $coreapi->enableDualsideCheck(true); // check if data on front and back of ID matches $coreapi->setVaultData("user@example.com",12345,"AABBCC"); // store custom data into vault $coreapi->restrictCountry("US,CA,AU"); // accept documents from United States, Canada and Australia $coreapi->restrictState("CA,TX,WA"); // accept documents from california, texas and washington $coreapi->restrictType("DI"); // accept only driver license and identification card $coreapi->setOCRImageResize(0); // disable OCR resizing $coreapi->verifyExpiry(true); // check document expiry $coreapi->verifyAge("18-120"); // check if person is above 18 $coreapi->verifyDOB("1990/01/01"); // check if person's birthday is 1990/01/01 $coreapi->verifyDocumentNumber("X1234567"); // check if the person's ID number is X1234567 $coreapi->verifyName("Elon Musk"); // check if the person is named Elon Musk $coreapi->verifyAddress("123 Sunny Rd, California"); // Check if address on ID matches with provided address $coreapi->verifyPostcode("90001"); // check if postcode on ID matches with provided postcode $coreapi->enableAMLCheck(true); // enable AML/PEP compliance check $coreapi->setAMLDatabase("global_politicians,eu_meps,eu_cors"); // limit AML check to only PEPs $coreapi->enableAMLStrictMatch(true); // make AML matching more strict to prevent false positives $coreapi->generateContract("Template ID", "PDF", array("email"=>"user@example.com")); // generate a PDF document autofilled with data from user ID
要扫描ID的正反两面
$result = $coreapi->scan("path/to/id_front.jpg", "path/to/id_back.jpg");
要执行生物识别照片验证
$result = $coreapi->scan("path/to/id.jpg", "", "path/to/face.jpg");
要执行生物识别视频验证
$result = $coreapi->scan("path/to/id.jpg", "", "", "path/to/video.mp4", "1234");
查看示例响应数组字段,请访问核心API参考。
DocuPass身份验证API
DocuPass允许您在不设计自己的网页或移动UI的情况下验证您的用户。可以为您的每个用户生成一个唯一的DocuPass URL,您的用户只需在浏览器中打开此URL即可验证自己的身份。DocuPass URL可以直接在任何浏览器中打开,您也可以在网站上的iframe或iOS/Android/Cordova移动应用中的WebView中嵌入此URL。
DocuPass包含4个模块,您需要选择合适的DocuPass模块进行集成。
开始时,我们将假设您正在尝试验证您数据库中ID为“5678”的用户,我们需要为该用户生成一个DocuPass验证请求。将生成唯一的DocuPass参考代码和URL。
// use composer autoload require("vendor/autoload.php"); // or manually load DocuPass class //require("../src/DocuPass.php"); use IDAnalyzer\DocuPass; // Initialize DocuPass with your credential, company name and API region $docupass = new DocuPass("API Key", "My Company Inc.", "US"); // We need to set an identifier so that we know internally who we are verifying, this string will be returned in the callback. You can use your own user/customer id. $docupass->setCustomID("5678"); // Enable vault cloud storage to store verification results, so we can look up the results $docupass->enableVault(true); // Set a callback URL where verification results will be sent, you can use docupass_callback.php in demo folder as a template $docupass->setCallbackURL("https://www.your-website.com/docupass_callback.php"); // We want DocuPass to return document image and user face image in URL format so we can store them on our own server later. $docupass->setCallbackImage(true, true, 1); // We will do a quick check on whether user have uploaded a fake ID $docupass->enableAuthentication(true, "quick", 0.3); // Enable photo facial biometric verification with threshold of 0.5 $docupass->enableFaceVerification(true, 1, 0.5); // Users will have only 1 attempt at verification $docupass->setMaxAttempt(1); // We want to redirect user back to your website when they are done with verification $docupass->setRedirectionURL("https://www.your-website.com/verification_succeeded.php", "https://www.your-website.com/verification_failed.php"); // Get user to review and sign legal document (such as rental contract) prefilled with ID data $docupass->signContract("Template ID", "PDF"); // Create a session using DocuPass Standard Mobile module $result = $docupass->createMobile(); if($result['error']){ // Something went wrong echo("Error Code: {$result['error']['code']}<br/>Error Message: {$result['error']['message']}"); }else{ echo("Scan the QR Code below to verify your identity: <br/>"); echo("<img src=\"{$result['qrcode']}\"><br/>"); echo("Or open your mobile browser and type in: "); echo("<a href=\"{$result['url']}\">{$result['url']}</a>"); }
如果您想将DocuPass嵌入到您的移动应用程序中,只需在WebView中嵌入$result['url']
。要判断验证是否完成,请监控WebView的URL,并检查它是否与在setRedirectionURL
中设置的URL相匹配。(由于操作系统限制,DocuPass Live Mobile目前无法嵌入到原生iOS应用程序中,您需要使用Safari打开它)
查看DocuPass的更多设置
$docupass->setReusable(true); // allow DocuPass URL/QR Code to be used by multiple users $docupass->setLanguage("en"); // override auto language detection $docupass->setQRCodeFormat("000000","FFFFFF",5,1); // generate a QR code using custom colors and size $docupass->setWelcomeMessage("We need to verify your driver license before you make a rental booking with our company."); // Display your own greeting message $docupass->setLogo("https://www.your-website.com/logo.png"); // change default logo to your own $docupass->hideBrandingLogo(true); // hide footer logo $docupass->restrictCountry("US,CA,AU"); // accept documents from United States, Canada and Australia $docupass->restrictState("CA,TX,WA"); // accept documents from california, texas and washington $docupass->restrictType("DI"); // accept only driver license and identification card $docupass->verifyExpiry(true); // check document expiry $docupass->verifyAge("18-120"); // check if person is above 18 $docupass->verifyDOB("1990/01/01"); // check if person's birthday is 1990/01/01 $docupass->verifyDocumentNumber("X1234567"); // check if the person's ID number is X1234567 $docupass->verifyName("Elon Musk"); // check if the person is named Elon Musk $docupass->verifyAddress("123 Sunny Rd, California"); // Check if address on ID matches with provided address $docupass->verifyPostcode("90001"); // check if postcode on ID matches with provided postcode $docupass->setCustomHTML("https://www.yourwebsite.com/docupass_template.html"); // use your own HTML/CSS for DocuPass page $docupass->smsVerificationLink("+1333444555"); // Send verification link to user's mobile phone $docupass->enablePhoneVerification(true); // get user to input their own phone number for verification $docupass->verifyPhone("+1333444555"); // verify user's phone number you already have in your database $docupass->enableAMLCheck(true); // enable AML/PEP compliance check $docupass->setAMLDatabase("global_politicians,eu_meps,eu_cors"); // limit AML check to only PEPs $docupass->enableAMLStrictMatch(true); // make AML matching more strict to prevent false positives $docupass->generateContract("Template ID", "PDF", array("somevariable"=>"somevalue")); // automate paperwork by generating a document autofilled with ID data $docupass->signContract("Template ID", "PDF", array("somevariable"=>"somevalue")); // get user to sign a document as part of the identity verification process
现在我们需要编写一个回调脚本,如果您愿意称之为webhook,以接收验证结果。此脚本将在用户完成身份验证后立即调用。在本指南中,我们将将其命名为docupass_callback.php
// use composer autoload require("vendor/autoload.php"); // or manually load DocuPass class //require("../src/DocuPass.php"); use IDAnalyzer\DocuPass; try{ // Get raw post body $input_raw = file_get_contents('php://input'); // Parse JSON into associative array $data = json_decode($input_raw, true); // If we didn't get an array abort the script if(!is_array($data)) die(); // Check if we've gotten required data for validation against DocuPass server, we do this to prevent someone spoofing a callback if($data['reference'] =="" || $data['hash'] == "") die(); // Initialize DocuPass with your credentials and company name $docupass = new DocuPass("Your API Key", "My Company Inc.", "US"); // Validate result with DocuPass API Server $validation = $docupass->validate($data['reference'], $data['hash']); if($validation){ $userID = $data['customid']; // This value should be "5678" matching the User ID in your database if($data['success'] === true){ // User has completed identity verification successfully, or has signed legal document // Get some information about your user $firstName = $data['data']['firstName']; $lastName = $data['data']['lastName']; $dob = $data['data']['dob']; // Additional steps to store identity data into your own database }else{ // User did not pass identity verification $fail_code = $data['failcode']; $fail_reason = $data['failreason']; // Save failed reason so we can investigate further file_put_contents("failed_verifications.txt", "$userID has failed identity verification, DocuPass Reference: {$data['reference']}, Fail Reason: {$fail_reason} Fail Code: {$fail_code}\n", FILE_APPEND); // Additional steps to store why identity verification failed into your own database } }else{ throw new Exception("Failed to validate DocuPass results against DocuPass server"); } }catch(Exception $ex){ file_put_contents("docupass_exception.txt", $ex->getMessage()."\n", FILE_APPEND); }
访问DocuPass回调参考以查看DocuPass返回的完整有效负载。
在最后一步,您可以创建两个网页(通过setRedirectionURL
设置的URL),向用户显示结果。当用户被重定向时,DocuPass参考将作为GET参数传递,例如:https://www.your-website.com/verification_succeeded.php?reference=XXXXXXXXX,您可以使用参考代码从数据库中检索结果。P.S. 我们将在重定向用户到设置的URL之前始终向您的服务器发送回调。
DocuPass签名API
您可以在不进行身份验证的情况下让用户在DocuPass中审查和远程签署法律文件,为此,您需要创建一个DocuPass签名会话。
$docupass = new DocuPass($apikey, "My Company Inc.", $api_region); // Raise exceptions for API level errors $docupass->throwAPIException(true); // We need to set an identifier so that we know internally who is signing the document, this string will be returned in the callback. You can use your own user/customer id. $docupass->setCustomID($_POST['email']); // Enable vault cloud storage to store signed document $docupass->enableVault(true); // Set a callback URL where signed document will be sent, you can use docupass_callback.php under this folder as a template to receive the result $docupass->setCallbackURL("https://www.your-website.com/docupass_callback.php"); // We want to redirect user back to your website when they are done with document signing, there will be no fail URL unlike identity verification $docupass->setRedirectionURL("https://www.your-website.com/document_signed.html", ""); /* * more settings $docupass->setReusable(true); // allow DocuPass URL/QR Code to be used by multiple users $docupass->setLanguage("en"); // override auto language detection $docupass->setQRCodeFormat("000000","FFFFFF",5,1); // generate a QR code using custom colors and size $docupass->hideBrandingLogo(true); // hide default branding footer $docupass->setCustomHTML("https://www.yourwebsite.com/docupass_template.html"); // use your own HTML/CSS for DocuPass page $docupass->smsContractLink("+1333444555"); // Send signing link to user's mobile phone */ // Assuming in your contract template you have a dynamic field %{email} and you want to fill it with user email $prefill = array( "email" => $_POST['email'] ); // Create a signature session $result = $docupass->createSignature("Template ID", "PDF", $prefill); if ($result['error']) { // Something went wrong die("Error Code: {$result['error']['code']}<br/>Error Message: {$result['error']['message']}"); } else { // Redirect browser to DocuPass URL, the URL will work on both Desktop and Mobile header("Location: " . $result['url']); die(); }
一旦用户已审查并签署文件,签署的文件将通过回调在contract.document_url
字段下发送回您的服务器,如果已启用保险库,合约也将被保存在保险库中。
保险库API
ID Analyzer为通过Core API和DocuPass获取的数据提供免费的云数据库存储(保险库)。您可以通过PHP SDK在执行API请求时设置是否将用户数据存储到保险库中。您可以通过Web门户或通过保险库API检索存储在保险库中的数据。
如果您已启用保险库,Core API和DocuPass都将返回一个名为vaultid
的保险库条目标识符字符串,您可以使用该标识符查找您的用户数据
// use composer autoload require("vendor/autoload.php"); // or manually load DocuPass class //require("../src/Vault.php"); use IDAnalyzer\Vault; // Initialize Vault API with your credentials $vault = new Vault("API Key", "US"); // Get the vault entry using Vault Entry Identifier received from Core API/DocuPass $vaultdata = $vault->get("VAULT_ID");
您还可以列出保险库中的项目,以下示例列出了2021/02/25或之后创建的5个项目,按姓氏升序排序,从第一个项目开始
$vaultItems = $vault->list(array("createtime>=2021/02/25"), "firstName","ASC", 5, 0);
或者,您可能有一个DocuPass参考代码,您想要在保险库中搜索以检查用户是否已完成身份验证
$vaultItems = $vault->list(["docupass_reference=XXXXXXXXXXXXX"]);
了解有关保险库API的更多信息。
AML API
ID Analyzer提供了从全球当局汇集的反洗钱AML数据库,AML API允许我们的订阅者使用名称或文件编号来查找数据库。它允许您立即检查个人或公司是否列入任何类型的制裁、犯罪记录或是否是政治显要人物(PEP),作为您的AML合规性KYC的一部分。您还可以使用内置在Core API和DocuPass中的自动化检查。
// use composer autoload require("vendor/autoload.php"); // or manually load DocuPass class //require("../src/AMLAPI.php"); use IDAnalyzer\AMLAPI; // Initialize AML API with your credentials $aml = new AMLAPI($apikey, $api_region); // Make API error raise exceptions for API level errors $aml->throwAPIException(true); // Set AML database to only search the PEP category $aml->setAMLDatabase("global_politicians,eu_cors,eu_meps"); // Search for a politician $result = $aml->searchByName("Joe Biden"); print_r($result); // Set AML database to all databases $aml->setAMLDatabase(""); // Search for a sanctioned ID number $result = $aml->searchByIDNumber("AALH750218HBCLPC02"); print_r($result);
了解有关AML API的更多信息。
错误捕获
API服务器可能会返回错误响应,例如当文档无法识别时。您可以手动检查API返回的响应,或者您可以将$api->throwAPIException(true);
设置为在遇到API错误时抛出APIException
。然后您可以在调用API的函数(如scan
、createMobile
、createLiveMobile
、createIframe
、createRedirection
以及所有Vault相关的函数)上使用try/catch块来捕获错误。InvalidArgumentException
在您向任何函数传递错误参数时抛出。
try{ ... }catch(\IDAnalyzer\APIException $ex){ echo("Error Code: " . $ex->getCode() . ", Error Message: " . $ex->getMessage()); // View complete list of error codes under API reference: https://developer.idanalyzer.com/ switch($ex->getCode()){ case 1: // Invalid API Key break; case 8: // Out of API quota break; case 9: // Document not recognized break; default: // Other error } }catch(InvalidArgumentException $ex){ echo("Argument Error! " . $ex->getMessage()); }catch(Exception $ex){ echo("Unexpected Error! " . $ex->getMessage()); }
演示
查看/demo
文件夹以获取更多PHP演示代码。