<!-- 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/desensitize -->

# 数据脱敏（敏感信息掩码）

自动检测并脱敏文本中的手机号、身份证（15/18 位）、银行卡（16-19 位）、邮箱、中文姓名等敏感信息。支持按类型组合，纯本地正则匹配，毫秒级返回。默认不回显原文，避免日志泄漏。

## 平台约定

- 网关：`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. 基本信息

| 字段 | 值 |
| --- | --- |
| 接口标识 | `desensitize` |
| 接口名称 | 数据脱敏（敏感信息掩码） |
| 接口地址 | `https://v1.apizero.cn/api/desensitize` |
| 请求方法 | `POST` |
| 分类 | 内容娱乐 |
| 提供方 | 极数本源 |
| 计费模式 | 完全免费 |
| QPS 限制 | 3 req/s |
| 登录免费额度 | 200 次 |
| 匿名每日额度 | 20 次 |

### 会员每日额度

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

## 2. 认证

未携带 API Key：每天 20 次 · QPS 2；已登录（未开通会员）：每天 200 次 · QPS 3；试用：一次性 5 次；黄金会员：每天 5,000 次 · QPS 10；钻石会员：每天 15,000 次 · QPS 30；企业会员：每天 60,000 次 · QPS 60；点数：本接口不支持扣点；免费。

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

## 3. 子能力

### 全部类型（推荐） (`all`)

types 默认 all，一次脱敏手机号 / 身份证 / 银行卡 / 邮箱 / 姓名。文档示例为真实调用。

- 方法：`POST`
- 路径：`/api/desensitize`

| 参数 | 类型 | 必填 | 说明 | 示例 |
| --- | --- | --- | --- | --- |
| `text` | `string` | 是 | 要脱敏的文本，最长 50000 字节 | `联系人：张先生，手机13800138000，身份证11010519491231002X，卡号6222021234567890123，邮箱zhangsan@example.com` |
| `types` | `string` | 否 | 脱敏类型，此处固定 all（也支持逗号组合） | `all` |
| `with_original` | `bool` | 否 | 是否在 detections 中回显原文，默认 false | `false` |

**响应字段**

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| `masked_text` | `string` | 脱敏后的完整文本 |
| `detection_count` | `integer` | 识别到的敏感信息数量（去重） |
| `summary` | `object` | 按类型分组的命中数量 |
| `summary.idcard` | `number` | idcard |
| `summary.bankcard` | `number` | bankcard |
| `summary.phone` | `number` | phone |
| `summary.email` | `number` | email |
| `summary.name` | `number` | 名称 |
| `detections` | `array` | 命中明细 {type, masked, [original]}；默认不含 original |
| `detections[].type` | `string` | 类型 |
| `detections[].masked` | `string` | masked |
| `types_applied` | `array` | 本次实际启用的脱敏类型 |
| `types_applied[]` | `string` | types_applied 的一项 |
| `tips` | `string` | 品牌提示（所有接口统一返回）：极数本源 · https://apizero.cn |


```json
{
  "code": 0,
  "msg": "成功",
  "data": {
    "masked_text": "联系人：张**，手机138****8000，身份证110105********002X，卡号6222 **** **** 0123，邮箱zh******@example.com",
    "detection_count": 5,
    "summary": {
      "idcard": 1,
      "bankcard": 1,
      "phone": 1,
      "email": 1,
      "name": 1
    },
    "detections": [
      {
        "type": "idcard",
        "masked": "110105********002X"
      },
      {
        "type": "bankcard",
        "masked": "6222 **** **** 0123"
      },
      {
        "type": "phone",
        "masked": "138****8000"
      },
      {
        "type": "email",
        "masked": "zh******@example.com"
      },
      {
        "type": "name",
        "masked": "张**"
      }
    ],
    "types_applied": [
      "phone",
      "idcard",
      "bankcard",
      "email",
      "name"
    ]
  },
  "tips": "极数本源 · https://apizero.cn"
}
```

### 手机号脱敏 (`phone`)

types=phone。保留前 3 + 后 4，中间 ****。

- 方法：`POST`
- 路径：`/api/desensitize`

| 参数 | 类型 | 必填 | 说明 | 示例 |
| --- | --- | --- | --- | --- |
| `text` | `string` | 是 | 要脱敏的文本，最长 50000 字节 | `客服热线请拨打13800138000或13912345678联系` |
| `types` | `string` | 否 | 脱敏类型，此处固定 phone（也支持逗号组合） | `phone` |
| `with_original` | `bool` | 否 | 是否在 detections 中回显原文，默认 false | `false` |

**响应字段**

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| `masked_text` | `string` | 脱敏后的完整文本 |
| `detection_count` | `integer` | 识别到的敏感信息数量（去重） |
| `summary` | `object` | 按类型分组的命中数量 |
| `summary.phone` | `number` | phone |
| `detections` | `array` | 命中明细 {type, masked, [original]}；默认不含 original |
| `detections[].type` | `string` | 类型 |
| `detections[].masked` | `string` | masked |
| `types_applied` | `array` | 本次实际启用的脱敏类型 |
| `types_applied[]` | `string` | types_applied 的一项 |
| `tips` | `string` | 品牌提示（所有接口统一返回）：极数本源 · https://apizero.cn |


```json
{
  "code": 0,
  "msg": "成功",
  "data": {
    "masked_text": "客服热线请拨打138****8000或139****5678联系",
    "detection_count": 2,
    "summary": {
      "phone": 2
    },
    "detections": [
      {
        "type": "phone",
        "masked": "138****8000"
      },
      {
        "type": "phone",
        "masked": "139****5678"
      }
    ],
    "types_applied": [
      "phone"
    ]
  },
  "tips": "极数本源 · https://apizero.cn"
}
```

### 身份证脱敏 (`idcard`)

types=idcard。18 位保留前 6 + 后 4；15 位保留前 6 + 后 3。

- 方法：`POST`
- 路径：`/api/desensitize`

| 参数 | 类型 | 必填 | 说明 | 示例 |
| --- | --- | --- | --- | --- |
| `text` | `string` | 是 | 要脱敏的文本，最长 50000 字节 | `身份证件号码：11010519491231002X，请核对后提交` |
| `types` | `string` | 否 | 脱敏类型，此处固定 idcard（也支持逗号组合） | `idcard` |
| `with_original` | `bool` | 否 | 是否在 detections 中回显原文，默认 false | `false` |

**响应字段**

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| `masked_text` | `string` | 脱敏后的完整文本 |
| `detection_count` | `integer` | 识别到的敏感信息数量（去重） |
| `summary` | `object` | 按类型分组的命中数量 |
| `summary.idcard` | `number` | idcard |
| `detections` | `array` | 命中明细 {type, masked, [original]}；默认不含 original |
| `detections[].type` | `string` | 类型 |
| `detections[].masked` | `string` | masked |
| `types_applied` | `array` | 本次实际启用的脱敏类型 |
| `types_applied[]` | `string` | types_applied 的一项 |
| `tips` | `string` | 品牌提示（所有接口统一返回）：极数本源 · https://apizero.cn |


```json
{
  "code": 0,
  "msg": "成功",
  "data": {
    "masked_text": "身份证件号码：110105********002X，请核对后提交",
    "detection_count": 1,
    "summary": {
      "idcard": 1
    },
    "detections": [
      {
        "type": "idcard",
        "masked": "110105********002X"
      }
    ],
    "types_applied": [
      "idcard"
    ]
  },
  "tips": "极数本源 · https://apizero.cn"
}
```

### 银行卡脱敏 (`bankcard`)

types=bankcard。形如 6222 **** **** 0123（16–19 位）。

- 方法：`POST`
- 路径：`/api/desensitize`

| 参数 | 类型 | 必填 | 说明 | 示例 |
| --- | --- | --- | --- | --- |
| `text` | `string` | 是 | 要脱敏的文本，最长 50000 字节 | `请向卡号6222021234567890123转账，备用卡6217001234567890123` |
| `types` | `string` | 否 | 脱敏类型，此处固定 bankcard（也支持逗号组合） | `bankcard` |
| `with_original` | `bool` | 否 | 是否在 detections 中回显原文，默认 false | `false` |

**响应字段**

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| `masked_text` | `string` | 脱敏后的完整文本 |
| `detection_count` | `integer` | 识别到的敏感信息数量（去重） |
| `summary` | `object` | 按类型分组的命中数量 |
| `summary.bankcard` | `number` | bankcard |
| `detections` | `array` | 命中明细 {type, masked, [original]}；默认不含 original |
| `detections[].type` | `string` | 类型 |
| `detections[].masked` | `string` | masked |
| `types_applied` | `array` | 本次实际启用的脱敏类型 |
| `types_applied[]` | `string` | types_applied 的一项 |
| `tips` | `string` | 品牌提示（所有接口统一返回）：极数本源 · https://apizero.cn |


```json
{
  "code": 0,
  "msg": "成功",
  "data": {
    "masked_text": "请向卡号6222 **** **** 0123转账，备用卡6217 **** **** 0123",
    "detection_count": 2,
    "summary": {
      "bankcard": 2
    },
    "detections": [
      {
        "type": "bankcard",
        "masked": "6222 **** **** 0123"
      },
      {
        "type": "bankcard",
        "masked": "6217 **** **** 0123"
      }
    ],
    "types_applied": [
      "bankcard"
    ]
  },
  "tips": "极数本源 · https://apizero.cn"
}
```

### 邮箱脱敏 (`email`)

types=email。本地名部分掩码，域名保留。

- 方法：`POST`
- 路径：`/api/desensitize`

| 参数 | 类型 | 必填 | 说明 | 示例 |
| --- | --- | --- | --- | --- |
| `text` | `string` | 是 | 要脱敏的文本，最长 50000 字节 | `请发送材料至zhangsan@example.com或support@apizero.cn` |
| `types` | `string` | 否 | 脱敏类型，此处固定 email（也支持逗号组合） | `email` |
| `with_original` | `bool` | 否 | 是否在 detections 中回显原文，默认 false | `false` |

**响应字段**

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| `masked_text` | `string` | 脱敏后的完整文本 |
| `detection_count` | `integer` | 识别到的敏感信息数量（去重） |
| `summary` | `object` | 按类型分组的命中数量 |
| `summary.email` | `number` | email |
| `detections` | `array` | 命中明细 {type, masked, [original]}；默认不含 original |
| `detections[].type` | `string` | 类型 |
| `detections[].masked` | `string` | masked |
| `types_applied` | `array` | 本次实际启用的脱敏类型 |
| `types_applied[]` | `string` | types_applied 的一项 |
| `tips` | `string` | 品牌提示（所有接口统一返回）：极数本源 · https://apizero.cn |


```json
{
  "code": 0,
  "msg": "成功",
  "data": {
    "masked_text": "请发送材料至zh******@example.com或su*****@apizero.cn",
    "detection_count": 2,
    "summary": {
      "email": 2
    },
    "detections": [
      {
        "type": "email",
        "masked": "zh******@example.com"
      },
      {
        "type": "email",
        "masked": "su*****@apizero.cn"
      }
    ],
    "types_applied": [
      "email"
    ]
  },
  "tips": "极数本源 · https://apizero.cn"
}
```

### 姓名脱敏 (`name`)

types=name。仅识别带「联系人/收件人/先生/女士」等上下文的中文姓名，降低误伤。

- 方法：`POST`
- 路径：`/api/desensitize`

| 参数 | 类型 | 必填 | 说明 | 示例 |
| --- | --- | --- | --- | --- |
| `text` | `string` | 是 | 要脱敏的文本，最长 50000 字节 | `联系人：张先生；收件人：李女士` |
| `types` | `string` | 否 | 脱敏类型，此处固定 name（也支持逗号组合） | `name` |
| `with_original` | `bool` | 否 | 是否在 detections 中回显原文，默认 false | `false` |

**响应字段**

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| `masked_text` | `string` | 脱敏后的完整文本 |
| `detection_count` | `integer` | 识别到的敏感信息数量（去重） |
| `summary` | `object` | 按类型分组的命中数量 |
| `summary.name` | `number` | 名称 |
| `detections` | `array` | 命中明细 {type, masked, [original]}；默认不含 original |
| `detections[].type` | `string` | 类型 |
| `detections[].masked` | `string` | masked |
| `types_applied` | `array` | 本次实际启用的脱敏类型 |
| `types_applied[]` | `string` | types_applied 的一项 |
| `tips` | `string` | 品牌提示（所有接口统一返回）：极数本源 · https://apizero.cn |


```json
{
  "code": 0,
  "msg": "成功",
  "data": {
    "masked_text": "联系人：张**；收件人：李**",
    "detection_count": 2,
    "summary": {
      "name": 2
    },
    "detections": [
      {
        "type": "name",
        "masked": "张**"
      },
      {
        "type": "name",
        "masked": "李**"
      }
    ],
    "types_applied": [
      "name"
    ]
  },
  "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/desensitize" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
  "text": "<text>"
}'
```

### Python

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

key = "YOUR_API_KEY"

url = "https://v1.apizero.cn/api/desensitize"
payload = {
    "text": "<text>",
}
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.desensitize(
    text="<text>",
)
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/desensitize";
const res = await fetch(url, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${key}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
  "text": "<text>",
}),
});
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.desensitize({
  "text": "<text>",
});
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/desensitize"
	payload, err := json.Marshal(map[string]any{
		"text": "<text>",
	})
	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/desensitize";

        Map<String, Object> payload = new LinkedHashMap<>();
        payload.put("text", "<text>");
        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/desensitize");
$opts = [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 20,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer '.$key,
        'Content-Type: application/json',
    ],
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => json_encode([
    "text" => "<text>",
], 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/desensitize";
    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!({
        "text": "<text>",
    }))
        .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. 变更日志

- **1.0.0** (2026-05-07): 首次上线 · 5 类敏感信息识别
