使用 curl 发起 POST 请求调用百度 AI 或阿里云 OCR API,解析返回的 JSON 数据并映射为结构化对象。

API 选择与认证配置
身份证识别通常依赖第三方云服务,推荐使用百度智能云或阿里云。需在控制台创建应用获取 AppID、APIKey 和 SecretKey。

不同厂商的接口路径和鉴权方式略有差异。百度 API 需要先用 AK/SK 换取 Access Token,阿里云则直接使用 STS 或 AccessKey 签名。封装类库时,应将密钥配置外置,避免硬编码在代码中。
核心请求与响应处理
将身份证图片转为 Base64 编码,构造符合 API 规范的 JSON Payload,通过 HTTPS 发送请求。

<?php
class IdCardOcrService
{
private $apiKey;
private $secretKey;
private $url;
public function __construct($apiKey, $secretKey, $url)
{
$this->apiKey = $apiKey;
$this->secretKey = $secretKey;
$this->url = $url;
}
public function recognize(string $imagePath): array
{
if (!file_exists($imagePath)) {
throw new Exception("Image file not found: {$imagePath}");
}
$base64Img = base64_encode(file_get_contents($imagePath));
$payload = json_encode([
'image' => $base64Img,
'id_card_side' => 'front'
]);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $this->getAccessToken()
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200) {
throw new Exception("HTTP Error: {$httpCode}");
}
$data = json_decode($response, true);
if (isset($data['error_code']) && $data['error_code'] != 0) {
throw new Exception("API Error: " . $data['error_msg']);
}
return $this->mapFields($data['result']);
}
private function getAccessToken(): string
{
// 简化版:实际应缓存 Token
$tokenUrl = 'https://aip.baidubce.com/oauth/2.0/token';
$params = http_build_query([
'grant_type' => 'client_credentials',
'client_id' => $this->apiKey,
'client_secret' => $this->secretKey
]);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $tokenUrl . '?' . $params);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$res = curl_exec($ch);
curl_close($ch);
$json = json_decode($res, true);
return $json['access_token'];
}
private function mapFields(array $result): array
{
return [
'name' => $result['name'] ?? null,
'gender' => $result['gender'] ?? null,
'ethnicity' => $result['ethnicity'] ?? null,
'address' => $result['address'] ?? null,
'id_number' => $result['num'] ?? null
];
}
}
// 使用示例
try {
$service = new IdCardOcrService('YOUR_API_KEY', 'YOUR_SECRET_KEY', 'YOUR_OCR_URL');
$result = $service->recognize('./id_card.jpg');
print_r($result);
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
}
程序输出为包含 name、gender 等字段的关联数组。若图片路径错误或 API 返回业务错误码,将抛出异常。修改 id_card_side 参数可识别背面信息。
重点处理网络超时、HTTP 状态码非 200 以及业务错误码(如图片模糊、格式不支持)。返回结果需提取姓名、性别、民族、地址、身份证号等关键字段,并进行基础格式校验。
字段映射与异常捕获
针对 API 返回的非标准字段名进行统一映射,确保输出结构稳定。
部分 API 返回的字段可能包含额外描述信息,需剥离冗余数据。对于缺失或识别置信度低的字段,应返回 null 或抛出特定异常,便于上层业务逻辑判断。