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

# SSL 证书检测

通过域名远程探测其 HTTPS/SSL 证书信息：颁发者、颁发机构、签名算法、覆盖域名、有效期、是否过期、距过期天数、SHA-1 指纹、远端 IP 等。

• 智能预处理：自动剥离 http(s):// 前缀、路径、查询串、端口、www. 子域
• 严格域名校验：合法域名格式（最长 253 字符 + RFC 1123 标签规则）才打服务
• 三态响应：有 SSL（is_ssl=true）→ 完整信息；无 SSL/连接失败 → is_ssl=false 其余字段 null；服务异常 → 502
• 字段标准化：服务 null 字段透传 null 不补 0；自动转 int/string 类型；is_expire 重命名 is_expired
• 缓存策略：成功 6h（证书短期不变）；无证书 30min（避免错误域名反复打服务）

## 平台约定

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

| 字段 | 值 |
| --- | --- |
| 接口标识 | `ssl` |
| 接口名称 | SSL 证书检测 |
| 接口地址 | `https://v1.apizero.cn/api/ssl` |
| 请求方法 | `GET` |
| 分类 | 开发工具 |
| 提供方 | 极数本源 |
| 计费模式 | 完全免费 |
| QPS 限制 | QPS 3 |
| 登录免费额度 | 10,000 次 |
| 匿名每日额度 | 3,000 次 |

### 会员每日额度

| 会员档位 | 每日免费 | QPS |
| --- | --- | --- |
| 黄金会员 | 50,000 次/日 | QPS 10 |
| 钻石会员 | 100,000 次/日 | QPS 30 |
| 企业会员 | 1,000,000 次/日 | QPS 120 |

## 2. 认证

匿名每日 30 次、QPS 2；登录用户每日 100 次、QPS 5（全部免费）。命中 6 小时缓存不计入服务配额。

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

## 3. 请求参数

| 参数 | 类型 | 必填 | 说明 | 示例 |
| --- | --- | --- | --- | --- |
| `domain` | `string` | 是 | 要检测的域名。可带 http(s):// 前缀、路径、端口、www.，会自动剥离 | `apizero.cn` |

## 6. 响应字段

顶层固定 code / msg / data。下表一般是 data 内字段。

| 字段 | 类型 | 说明 |
| --- | --- | --- |
| `domain` | `string` | 查询的域名（已剥离协议/路径/端口/www） |
| `common_name` | `string?` | 证书 Common Name（CN），如 *.apizero.cn |
| `domains` | `string[]` | 证书覆盖的所有域名（SAN 列表）；无证书时为空数组 |
| `issuing_agency` | `string?` | 颁发机构（公司名），如 Asseco Data Systems S.A. |
| `issuer` | `string?` | 颁发者 CA 名称，如 Certum DV TLS G2 R39 CA；自签名时与 common_name 相同 |
| `signature_algorithm` | `string?` | 签名算法，如 RSA-SHA256 / ecdsa-with-SHA256 |
| `is_ssl` | `boolean` | 域名是否能成功探测到 SSL 证书：true=有证书 / false=无证书或 443 不可达 |
| `is_expired` | `boolean?` | 证书是否已过期；is_ssl=false 时为 null |
| `life_span_days` | `number?` | 证书总有效期天数（颁发到过期），如 198；无证书时为 null |
| `expire_days` | `number?` | 距过期还有多少天（已过期为负数）；无证书时为 null |
| `start_date` | `string?` | 颁发起始时间（YYYY-MM-DD HH:MM:SS）；无证书时为 null |
| `expire_date` | `string?` | 过期时间（YYYY-MM-DD HH:MM:SS）；无证书时为 null |
| `fingerprint` | `string?` | 证书 SHA-1 指纹（40 位十六进制字符串）；无证书时为 null |
| `remote_address` | `string?` | 远端服务器 IP:端口，如 119.36.225.184:443；无证书时为 null |
| `tips` | `string` | 品牌提示（所有接口统一返回）：极数本源 · https://apizero.cn |

## 7. 响应示例

```json
{
  "code": 0,
  "msg": "成功",
  "data": {
    "domain": "apizero.cn",
    "common_name": "*.apizero.cn",
    "domains": [
      "*.apizero.cn",
      "apizero.cn"
    ],
    "issuing_agency": "Asseco Data Systems S.A.",
    "issuer": "Certum DV TLS G2 R39 CA",
    "signature_algorithm": "RSA-SHA256",
    "is_ssl": true,
    "is_expired": false,
    "life_span_days": 198,
    "expire_days": 184,
    "start_date": "2026-04-22 17:05:00",
    "expire_date": "2026-11-07 17:04:59",
    "fingerprint": "f4633adfd1cb59185ba094dc3edeef5a8ea26889",
    "remote_address": "119.36.225.184:443"
  },
  "request_id": "abc123def456",
  "tips": "极数本源 · https://apizero.cn"
}
```


## 5. 请求示例

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

### cURL

```bash
curl -sS -H "Authorization: Bearer YOUR_API_KEY" "https://v1.apizero.cn/api/ssl?domain=apizero.cn"
```

### Python

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

key = "YOUR_API_KEY"

url = "https://v1.apizero.cn/api/ssl"
params = {
    "domain": "apizero.cn",
}
query = urllib.parse.urlencode({k: "" if v is None else str(v) for k, v in params.items()})
req = urllib.request.Request(
    url + ("?" + query if query else ""),
    headers={"Authorization": "Bearer " + key},
    method="GET",
)
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.ssl(
    domain="apizero.cn",
)
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/ssl?domain=apizero.cn";
const res = await fetch(url, {
  headers: { Authorization: `Bearer ${key}` },
});
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.ssl({
  "domain": "apizero.cn",
});
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 (
	"fmt"
	"io"
	"net/http"
)

func main() {
	key := "YOUR_API_KEY"

	url := "https://v1.apizero.cn/api/ssl?domain=apizero.cn"
	req, err := http.NewRequest(http.MethodGet, url, nil)
	if err != nil {
		panic(err)
	}
	req.Header.Set("Authorization", "Bearer "+key)
	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.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/ssl?domain=apizero.cn";

        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))
                .GET()
                .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/ssl?domain=apizero.cn");
$opts = [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 20,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer '.$key,
    ],
];
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/ssl?domain=apizero.cn";
    let mut headers = HeaderMap::new();
    headers.insert(
        AUTHORIZATION,
        HeaderValue::from_str(&format!("Bearer {key}"))?,
    );
    let body: Value = Client::new()
        .get(url)
        .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): 首次上线，/api/domain/checkssl
智能 domain 预处理：自动剥离 http(s):// 前缀 / 路径 / 端口 / www. 子域
严格 RFC 1123 域名格式校验，无效输入直接 4000，节省服务配额
字段重命名：is_expire → is_expired（更地道英文）；sn → signature_algorithm；life_span_in_days → life_span_days
类型规范化：服务 null 字段保留 null（不像源码无脑 ?? "" / ?? 0），前端可正确判空
不返回服务 raw_json 字段（含 10K+ X.509 详细信息，绝大多数前端用不到）
缓存策略：成功 6h / 无证书 30min（避免错误域名反复打付费服务）
