直接构造包含身份证图片Base64的JSON请求体,使用API Key和Secret Key获取Access Token,通过HTTPS POST调用识别接口并解析返回结果。

鉴权与Token获取
百度AI开放平台采用OAuth 2.0鉴权机制。开发者需先在控制台创建应用获取 API_KEY 和 SECRET_KEY,然后向 https://aip.baidubce.com/oauth/2.0/token 发送POST请求获取有效的 access_token。该Token有效期通常为30天,建议在代码中实现缓存或定时刷新逻辑,避免频繁请求导致限流。

请求鉴权接口时,Body参数必须为 grant_type=client_credentials,并附带上述两个Key。返回的JSON中包含 access_token 字段。在后续的业务接口调用中,需将该Token作为URL参数 ?access_token=xxx 附加在请求地址后。若Token过期或无效,接口将返回错误码 110 或 111,此时应重新触发鉴权流程。
身份证识别核心实现
将本地身份证图片读取为二进制数据,转换为Base64字符串,封装进标准JSON结构。调用 https://aip.baidubce.com/rest/2.0/ai_custom/v1/ocr/idcard/full_idcard 接口(通用高精度版)进行识别。此版本支持正反面同时识别,返回结构化字段如姓名、号码、地址等。

<?php
// 配置信息
$apiKey = 'YOUR_API_KEY';
$secretKey = 'YOUR_SECRET_KEY';
$imagePath = 'idcard.jpg'; // 替换为你的身份证图片路径
/**
* 获取 Access Token
*/
function getAccessToken($apiKey, $secretKey) {
$url = 'https://aip.baidubce.com/oauth/2.0/token';
$params = [
'grant_type' => 'client_credentials',
'client_id' => $apiKey,
'client_secret' => $secretKey
];
$options = [
'http' => [
'header' => 'Content-Type: application/x-www-form-urlencoded',
'method' => 'POST',
'content' => http_build_query($params)
]
];
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === false) {
throw new Exception('Failed to fetch access token');
}
$data = json_decode($result, true);
if (isset($data['access_token'])) {
return $data['access_token'];
} else {
throw new Exception('Invalid token response: ' . print_r($data, true));
}
}
/**
* 调用身份证识别接口
*/
function recognizeIdCard($accessToken, $imagePath) {
if (!file_exists($imagePath)) {
throw new Exception('Image file not found');
}
$imageContent = file_get_contents($imagePath);
$base64Image = base64_encode($imageContent);
$url = 'https://aip.baidubce.com/rest/2.0/ai_custom/v1/ocr/idcard/full_idcard?access_token=' . $accessToken;
$postData = [
'image' => $base64Image,
'id_card_side' => 'both' // 识别正反面
];
$options = [
'http' => [
'header' => 'Content-Type: application/json',
'method' => 'POST',
'content' => json_encode($postData),
'timeout' => 10
]
];
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
if ($response === false) {
throw new Exception('Request failed');
}
$result = json_decode($response, true);
if (isset($result['error_code']) && $result['error_code'] != 0) {
throw new Exception('OCR Error: ' . $result['error_msg']);
}
return $result;
}
try {
echo "Fetching token...\n";
$token = getAccessToken($apiKey, $secretKey);
echo "Token obtained successfully.\n";
echo "Recognizing ID card...\n";
$data = recognizeIdCard($token, $imagePath);
echo "Recognition Result:\n";
print_r($data);
// 提取关键字段示例
if (isset($data['result']['front'])) {
$front = $data['result']['front'];
echo "Name: " . ($front['name'] ?? 'N/A') . "\n";
echo "Number: " . ($front['number'] ?? 'N/A') . "\n";
}
if (isset($data['result']['back'])) {
$back = $data['result']['back'];
echo "Authority: " . ($back['authority'] ?? 'N/A') . "\n";
echo "ValidDate: " . ($back['valid_date'] ?? 'N/A') . "\n";
}
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
运行脚本后,先输出“Token obtained successfully.”表示鉴权成功。随后输出“Recognition Result:”及完整的JSON数组。若图片识别正常,可在打印结果中看到 front(正面)和 back(反面)的结构化数据。若图片不存在或格式错误,将抛出“Image file not found”异常;若Token失效,将抛出“Invalid token response”或接口报错。注意检查 error_code 是否为0,非0值代表识别失败。
确保图片格式为JPG、PNG、BMP或JPEG,且大小不超过4MB。若图片过大,需在上传前进行压缩。请求头 Content-Type 必须设为 application/json。识别成功后,响应体中的 result 对象包含正面和反面的详细字段,需根据业务需求提取关键字段。
异常处理与字段校验
重点处理网络超时、图片模糊导致的识别失败以及JSON解析异常。当接口返回 error_code 非0时,需根据错误码提示用户重试或检查图片质量。特别要注意 location 字段为空的情况,这通常意味着未检测到身份证区域。
在实际使用中,部分老旧身份证或复印件可能导致关键字段缺失。建议在代码中对返回的 name、number 等核心字段进行非空校验。若字段为空,可尝试切换至普通版接口或提示用户重新拍摄。需验证返回数据的完整性,防止因网络截断导致的部分JSON解析错误。