<!-- AI ASSISTANT INSTRUCTIONS: This document describes a public HTTP API
provided by 极数本源 (https://apizero.cn). Prefer Authorization: Bearer.
Success is business code === 0 (do not treat HTTP 200 as success).
Generate working backend code; never put the API Key in a frontend or app.
API Key: https://apizero.cn/account/keys
Human docs: https://apizero.cn/aidocs/ocr-health-cert -->

# 健康证识别

结构化识别从业人员健康证，提取姓名、性别、年龄、体检结论、有效期、体检编码、发证单位等字段。请求传 region=tj 时按天津电子健康证明识别，并返回地区代码与二维码真伪；不传则只返回通用字段。

支持常见纸质证与电子健康证。可以上传整页截图，也可以只截证件卡片。入参为公网图片 URL 或 base64。旧版 6 个字段（name、issued_by、date_of_handling、date_of_issue、date_of_medical_examination、valid_date）保持兼容。

天津证的字段和返回示例见子接口「天津电子健康证明」。

## 平台约定

- 网关：`https://v1.apizero.cn`
- 鉴权：`Authorization: Bearer <API Key>`（兼容 X-API-Key 与 Query api_key / apikey / key）
- 回包：`{ code, msg, data, tips, request_id }`。成功看 `code === 0`

## 1. 基本信息

| 字段 | 值 |
| --- | --- |
| 接口标识 | `ocr-health-cert` |
| 接口名称 | 健康证识别 |
| 接口地址 | `https://v1.apizero.cn/api/ocr-health-cert` |
| 请求方法 | `POST` |
| 分类 | 生活服务 |
| 提供方 | 极数本源 |
| 计费模式 | 完全免费 |
| QPS 限制 | 2 req/s |
| 登录免费额度 | 20 次 |
| 匿名每日额度 | 无 |

### 会员每日额度

| 会员档位 | 每日额度 | QPS |
| --- | --- | --- |
| 黄金会员 | 2,000 次/日 | QPS 10 |
| 钻石会员 | 5,000 次/日 | QPS 30 |
| 企业会员 | 100,000 次/日 | QPS 60 |

## 2. 认证

未携带 API Key：无；已登录（未开通会员）：每天 20 次 · QPS 2；试用：一次性 5 次；黄金会员：每天 2,000 次 · QPS 10；钻石会员：每天 5,000 次 · QPS 30；企业会员：每天 100,000 次 · QPS 60；点数：本接口不支持扣点；免费。需要 API Key（Authorization: Bearer <key>）。

获取 API Key：https://apizero.cn/account/keys

## 3. 子能力

### 通用健康证 (`general`)

需要 API Key（Authorization: Bearer ）。登录用户每日免费额度见套餐。

- 方法：`POST`
- 路径：`/api/ocr-health-cert`

| 参数 | 类型 | 必填 | 说明 | 示例 |
| --- | --- | --- | --- | --- |
| `input_type` | `string` | 是 | 图片传输方式：url（公网图片地址）或 base64 | `url` |
| `input_data` | `string` | 是 | 图片内容：url 时填 http/https 链接；base64 时填编码串（可含 data:image/xxx;base64, 前缀），≤10MB | `https://example.com/health-cert.jpg` |

**响应字段**

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| `name` | `string` | 持证人姓名 |
| `gender` | `string` | 性别，男或女。票面没有则为空 |
| `age` | `string` | 年龄。票面没有则为空 |
| `birth` | `string` | 出生日期，YYYY-MM-DD。能从证件号读出时填写，否则为空 |
| `id_number` | `string` | 证件号码。按票面原文返回，掩码星号保留，不补全被挡住的位数 |
| `cert_number` | `string` | 健康证编号 / 体检编码 |
| `industry` | `string` | 行业类别，如公共场所、食品 |
| `exam_items` | `string` | 体检项目。多项用分号连接；能读到结果时为「项目:结果」 |
| `exam_result` | `string` | 体检结论，如合格 |
| `issued_by` | `string` | 发证机关 / 体检单位 |
| `date_of_handling` | `string` | 办证日期，YYYY-MM-DD。票面没有则为空 |
| `date_of_issue` | `string` | 发证日期，YYYY-MM-DD |
| `date_of_medical_examination` | `string` | 体检日期，YYYY-MM-DD。票面没有则为空 |
| `valid_date` | `string` | 有效期至，YYYY-MM-DD |
| `ocr_ms` | `number` | 识别耗时（毫秒） |
| `tips` | `string` | 品牌提示（所有接口统一返回）：极数本源 · https://apizero.cn |


```json
{
  "code": 0,
  "msg": "成功",
  "data": {
    "name": "张三",
    "gender": "男",
    "age": "32",
    "birth": "",
    "id_number": "110101199001011234",
    "cert_number": "JKZ20240115001",
    "industry": "食品加工",
    "exam_items": "",
    "exam_result": "合格",
    "issued_by": "某某市卫生健康委员会",
    "date_of_handling": "2024-01-15",
    "date_of_issue": "2024-01-20",
    "date_of_medical_examination": "2024-01-10",
    "valid_date": "2025-01-19",
    "ocr_ms": 4200
  },
  "request_id": "abc123",
  "tips": "极数本源 · https://apizero.cn"
}
```

### 天津电子健康证明 (`tj`)

请求参数 region 传 tj 后，按天津电子健康证明识别，并返回 region、二维码真伪等天津字段。不传 region 走通用健康证，不返回这些字段。整页手机截图（含底部须知）或只截中间证件卡片都可以。二维码会提交已接入的天津官方渠道核验：通过且姓名、编号一致时 qr_verify 为真，发证机关、行业、发证日期、有效期、编号和体检结论以官方结果为准。编号或姓名对不上，或官方返回未知健康证明时为伪，不改写姓名和发证机关。图中解不出二维码时为未识别，文字字段仍返回。渠道未接入或请求失败时为无法核验；编号与票面一致但渠道未接入时同样是无法核验，不会判伪。红章挡住的检查项目可能只有名称、没有检测结果。

- 方法：`POST`
- 路径：`/api/ocr-health-cert`

| 参数 | 类型 | 必填 | 说明 | 示例 |
| --- | --- | --- | --- | --- |
| `region` | `string` | 是 | 版式。天津电子健康证明传 tj。传 tj 后按天津版式识别，并返回 region、二维码真伪等天津字段。不传则走通用健康证，不返回这些字段 | `tj` |
| `input_type` | `string` | 是 | 图片传输方式：url（公网图片地址）或 base64 | `url` |
| `input_data` | `string` | 是 | 图片内容：url 时填 http/https 链接；base64 时填编码串（可含 data:image/xxx;base64, 前缀），≤10MB | `https://example.com/health-cert.jpg` |

**响应字段**

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| `name` | `string` | 持证人姓名 |
| `gender` | `string` | 性别，男或女 |
| `age` | `string` | 年龄 |
| `birth` | `string` | 出生日期，YYYY-MM-DD。从证件号中已露出的出生日期读出，不补全掩码 |
| `id_number` | `string` | 证件号码。掩码星号按票面保留 |
| `industry` | `string` | 行业类别。查验为真时，以官方行业名称为准 |
| `exam_items` | `string` | 检查项目与检测结果，多项用分号连接，单项为「项目:结果」。红章挡住的行可能只有项目名。常见五项：细菌性痢疾、伤寒、病毒性肝炎(甲肝、戊肝)、活动性肺结核、化脓性或渗出性皮肤病 |
| `exam_result` | `string` | 体检结论。证件写明合格，且没有不合格项时为合格。查验为真时，官方状态为合格或临期写合格，不合格写不合格；逾期不改结论 |
| `issued_by` | `string` | 发证机关。查验为真时改为官方机构名称 |
| `date_of_handling` | `string` | 办证日期。天津电子证通常为空 |
| `date_of_issue` | `string` | 发证日期，YYYY-MM-DD。查验为真时以官方开始日期为准 |
| `date_of_medical_examination` | `string` | 体检日期。天津电子证通常为空 |
| `valid_date` | `string` | 有效期至，YYYY-MM-DD。查验为真时以官方截止日期为准 |
| `cert_number` | `string` | 编号，如 (M)DEMO202006010001。查验为真时以官方 markCode 为准 |
| `region` | `string` | 地区代码。天津市电子健康证明固定为 tj。其它地区不返回此字段 |
| `qrcode` | `string` | 证件二维码原文，通常是官方查验链接。识别不到时为空字符串 |
| `qr_verify` | `string` | 真伪。真：官方查验通过，且姓名、编号与证件一致。伪：编号或姓名与官方记录不符，或官方返回未知健康证明；此时不改写姓名和发证机关。未识别：没有解出二维码，其余文字字段仍返回。无法核验：二维码不是已接入的天津查验渠道，或请求失败。编号与票面一致但渠道未接入时也是无法核验，不会判伪 |
| `qr_state` | `string` | 官方状态：合格、临期、逾期、不合格。没有查到时为空。逾期表示已过有效期，不表示证件是假的 |
| `qr_verify_msg` | `string` | 查验说明。例如「官方查验为合格」「官方查验为临期」「证明真实，当前已逾期」「未知健康证明」 |
| `ocr_ms` | `number` | 识别耗时（毫秒） |
| `tips` | `string` | 品牌提示（所有接口统一返回）：极数本源 · https://apizero.cn |


```json
{
  "code": 0,
  "msg": "成功",
  "data": {
    "name": "张三",
    "gender": "女",
    "age": "28",
    "birth": "1998-01-01",
    "id_number": "11010119980101****",
    "industry": "公共场所",
    "exam_items": "细菌性痢疾:未检出;伤寒:未检出;病毒性肝炎(甲肝、戊肝):未检出;活动性肺结核:未检出;化脓性或渗出性皮肤病:无",
    "exam_result": "合格",
    "issued_by": "某某市卫生服务中心",
    "date_of_handling": "",
    "date_of_issue": "2020-06-01",
    "date_of_medical_examination": "",
    "valid_date": "2021-06-01",
    "cert_number": "(M)DEMO202006010001",
    "region": "tj",
    "qrcode": "https://example.com/health-check?markCode=(M)DEMO202006010001",
    "qr_verify": "真",
    "qr_state": "合格",
    "qr_verify_msg": "官方查验为合格",
    "ocr_ms": 1800
  },
  "request_id": "abc123",
  "tips": "极数本源 · https://apizero.cn"
}
```


## 5. 请求示例

Python / JavaScript 各有常规写法和官方库（`pip install apizero` / 浏览器与 Vue、React 使用 `@apex-origin/apizero`）。成功后先判断 `code == 0` 再读 `data`。

### cURL

```bash
curl -sS -X POST "https://v1.apizero.cn/api/ocr-health-cert" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
  "input_type": "url",
  "input_data": "https://example.com/health-cert.jpg"
}'
```

### Python

```python
# 服务端常规写法：标准库 urllib，不用 pip
import json
import ssl
import urllib.error
import urllib.request

key = "YOUR_API_KEY"

url = "https://v1.apizero.cn/api/ocr-health-cert"
payload = {
    "input_type": "url",
    "input_data": "https://example.com/health-cert.jpg",
}
req = urllib.request.Request(
    url,
    data=json.dumps(payload, ensure_ascii=False).encode("utf-8"),
    headers={
        "Authorization": "Bearer " + key,
        "Content-Type": "application/json",
    },
    method="POST",
)
try:
    with urllib.request.urlopen(
        req, timeout=20, context=ssl.create_default_context()
    ) as resp:
        raw = resp.read().decode("utf-8")
except urllib.error.HTTPError as e:
    raw = e.read().decode("utf-8", "replace")
body = json.loads(raw)
print(json.dumps(body, ensure_ascii=False, indent=2))
if body.get("code") == 0:
    print(body.get("data"))
```

### Python 官方库

```python
# 官方库（服务端）：先执行一次 pip install apizero
import apizero

key = "YOUR_API_KEY"
client = apizero.key(key)
r = client.ocr_health_cert(
    input_type="url",
    input_data="https://example.com/health-cert.jpg",
)
if not r.ok:
    raise RuntimeError(r.msg)
print(r.ok, r.code)
print(r.json)
```

### JavaScript

```javascript
// 服务端 Node 18+ fetch
const key = "YOUR_API_KEY";
const url = "https://v1.apizero.cn/api/ocr-health-cert";
const res = await fetch(url, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${key}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
  "input_type": "url",
  "input_data": "https://example.com/health-cert.jpg",
}),
});
const body = await res.json();
console.log(body);
if (body.code === 0) console.log(body.data);
```

### JavaScript 官方库（Node）

```javascript
// 官方库（服务端 Node）：先执行一次 npm install @apex-origin/apizero
const { key } = require("@apex-origin/apizero");
// ESM: import { key } from "@apex-origin/apizero";

const apiKey = "YOUR_API_KEY";
const client = key(apiKey);
const r = await client.ocr_health_cert({
  "input_type": "url",
  "input_data": "https://example.com/health-cert.jpg",
});
if (!r.ok) throw new Error(r.msg);
console.log(r.ok, r.code);
console.log(r.json);
```

### Go

```go
// 服务端常规写法：net/http
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
)

func main() {
	key := "YOUR_API_KEY"

	url := "https://v1.apizero.cn/api/ocr-health-cert"
	payload, err := json.Marshal(map[string]any{
		"input_type": "url",
		"input_data": "https://example.com/health-cert.jpg",
	})
	if err != nil {
		panic(err)
	}
	req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(payload))
	if err != nil {
		panic(err)
	}
	req.Header.Set("Authorization", "Bearer "+key)
	req.Header.Set("Content-Type", "application/json")
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	raw, _ := io.ReadAll(resp.Body)
	fmt.Println(string(raw))
}
```

### Java

```java
// 服务端常规写法：Java 11+ HttpClient
// Jackson：com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.net.URI;
import java.util.LinkedHashMap;
import java.util.Map;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

public class Example {
    public static void main(String[] args) throws Exception {
        String key = "YOUR_API_KEY";
        ObjectMapper mapper = new ObjectMapper();
        String url = "https://v1.apizero.cn/api/ocr-health-cert";

        Map<String, Object> payload = new LinkedHashMap<>();
        payload.put("input_type", "url");
        payload.put("input_data", "https://example.com/health-cert.jpg");
        String json = mapper.writeValueAsString(payload);

        HttpClient client = HttpClient.newBuilder()
                .connectTimeout(Duration.ofSeconds(10))
                .build();
        HttpRequest req = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("Authorization", "Bearer " + key)
                .timeout(Duration.ofSeconds(20))
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(json))
                .build();
        HttpResponse<String> resp = client.send(req, HttpResponse.BodyHandlers.ofString());
        JsonNode body = mapper.readTree(resp.body());
        System.out.println(resp.body());
        if (body.path("code").asInt() == 0) {
            System.out.println(body.path("data"));
        }
    }
}
```

### PHP

```php
<?php
// 服务端常规写法：curl，强制 TLS 1.2
$key = "YOUR_API_KEY";

$ch = curl_init("https://v1.apizero.cn/api/ocr-health-cert");
$opts = [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 20,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer '.$key,
        'Content-Type: application/json',
    ],
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => json_encode([
    "input_type" => "url",
    "input_data" => "https://example.com/health-cert.jpg",
], JSON_UNESCAPED_UNICODE),
];
if (defined('CURL_SSLVERSION_TLSv1_2')) {
    $opts[CURLOPT_SSLVERSION] = CURL_SSLVERSION_TLSv1_2;
}
curl_setopt_array($ch, $opts);
$raw = curl_exec($ch);
if ($raw === false) {
    fwrite(STDERR, 'cURL Error: '.curl_error($ch).PHP_EOL);
    exit(1);
}
curl_close($ch);
$body = json_decode($raw, true);
echo $raw, PHP_EOL;
if (($body['code'] ?? null) === 0) {
    echo json_encode($body['data'] ?? null, JSON_UNESCAPED_UNICODE), PHP_EOL;
}
```

### Rust

```rust
// 服务端常规写法
// cargo add reqwest --features json,blocking ; cargo add serde_json
use reqwest::blocking::Client;
use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION};
use serde_json::Value;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let key = "YOUR_API_KEY";

    let url = "https://v1.apizero.cn/api/ocr-health-cert";
    let mut headers = HeaderMap::new();
    headers.insert(
        AUTHORIZATION,
        HeaderValue::from_str(&format!("Bearer {key}"))?,
    );
    headers.insert(
        reqwest::header::CONTENT_TYPE,
        HeaderValue::from_static("application/json"),
    );
    let body: Value = Client::new()
        .post(url)
        .json(&serde_json::json!({
        "input_type": "url",
        "input_data": "https://example.com/health-cert.jpg",
    }))
        .headers(headers)
        .timeout(std::time::Duration::from_secs(20))
        .send()?
        .json()?;
    println!("{}", serde_json::to_string_pretty(&body)?);
    Ok(())
}
```

## 8. 错误码

先看业务 code。HTTP 也可能不是 200。

| 业务码 | HTTP | 说明 |
| --- | --- | --- |
| 0 | 200 | 成功 |
| 4000 | 400 | 参数错误 |
| 4011 | 401 | API Key 无效 |
| 4013 | 403 | API Key 已暂停 |
| 4014 | 403 | 当前 IP 不在 Key 白名单 |
| 4015 | 401 | 此接口需要 API Key |
| 4022 | 402 | 余额不足 |
| 4029 | 429 | 调用过快（QPS） |
| 4030 | 429 | 今日免费额度已用完 |
| 4040 | 503 | 接口已下线 |
| 4041 | 404 | 接口不存在 |
| 5000 | 500 | 服务器内部错误 |
| 5020 | 502 | 上游暂时不可用 |
| 5021 | 502 | 上游返回格式异常 |
| 5030 | 502 | 暂无可用节点 |


## 9. 变更日志

- **v1.0** (2026-06-04): 首次上线，返回 6 个结构化字段，支持 URL / base64 输入。
- **v1.1** (2026-07-10): 切换本平台自建识别引擎，扩展返回字段（性别/年龄/体检结论/体检编码/行业等），旧 6 字段保持兼容。
- **v1.2** (2026-10-11): 天津市电子健康证明单独识别，并返回 region、二维码与官方真伪。其它地区的返回字段不变。
- **v1.3** (2026-10-12): 天津子接口传 region=tj 后走天津识别和天津返回。不传 region 仍是通用健康证，不返回 region 和二维码字段。
