API 文档API Reference
控制台里的功能都可以通过 HTTP API 调用:添加域名、修改配置、刷新缓存、上传证书、管理黑白名单、查询用量。接口使用 JSON,鉴权采用 AccessKey / SecretKey 签名。Everything in the console is available over the HTTP API: adding domains, changing configuration, purging cache, uploading certificates, managing IP lists and querying usage. Requests and responses are JSON, authenticated with an AccessKey / SecretKey signature.
快速开始Quick start
- 登录控制台,在右上角账户菜单 →「API 密钥」创建密钥,得到
AccessKey和SecretKey。SecretKey 只显示一次,请妥善保存;建议同时设置 IP 白名单。 - 接口地址:
{ORIGIN}/api,所有请求使用 HTTPS(或控制台当前访问的地址)。 - 每个请求带上 4 个签名请求头(见下节),写操作请求体为 JSON,加
Content-Type: application/json。
- Sign in to the console and open the account menu → "API Keys" to create a key. You get an
AccessKeyand aSecretKey. The SecretKey is shown only once, so store it safely. Setting an IP allowlist is recommended. - Base URL:
{ORIGIN}/api - Add the four signature headers (next section) to every request. Write requests send a JSON body with
Content-Type: application/json.
签名方法Signing requests
| 请求头Header | 说明Description |
|---|---|
X-PS-AccessKey | AccessKey(24 位)Your AccessKey (24 characters) |
X-PS-Timestamp | 当前 Unix 时间戳(秒),与服务器时间相差不能超过 5 分钟Current Unix time in seconds. Must be within 5 minutes of server time. |
X-PS-Nonce | 8~64 位随机字符串,每个请求不同(10 分钟内重复会被拒绝)Random string, 8–64 characters, unique per request (reuse within 10 minutes is rejected) |
X-PS-Signature | 签名:hex(HMAC-SHA256(SecretKey, StringToSign)),小写十六进制Signature: hex(HMAC-SHA256(SecretKey, StringToSign)), lowercase hex |
待签名字符串 StringToSignString to sign
按顺序用换行符 \n 连接以下 6 项(末尾不加换行):
Join these six parts with a newline \n, in order, with no trailing newline:
METHOD GET / POST (uppercase)
PATH /api/domains/12/purge
QUERY range=7d&domain=12 (raw query string after "?", empty if none)
TIMESTAMP 1764316800
NONCE 9f1c2a7d4e
BODY_SHA256 hex(SHA256(request body)) (empty body: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855)
- PATH 使用实际发送的路径(不含域名和查询串,未经解码)。
- QUERY 与 URL 中
?后面的内容完全一致,不需要排序;签名后不要再改动 URL。 - BODY_SHA256 对实际发送的请求体原始字节计算;GET 请求为空串的哈希。
- PATH is the path exactly as sent (no host, no query string, not URL-decoded).
- QUERY must match the part of the URL after
?byte for byte. No sorting is required; don't modify the URL after signing. - BODY_SHA256 is computed over the exact bytes you send. For GET it is the hash of the empty string.
各语言示例Code samples
import hashlib, hmac, json, secrets, time, requests
BASE = "https://cdn.example.com" # console address
AK, SK = "your-access-key", "your-secret-key"
def call(method, path, query="", body=None):
data = json.dumps(body).encode() if body is not None else b""
ts, nonce = str(int(time.time())), secrets.token_hex(8)
s = "\n".join([method.upper(), path, query, ts, nonce, hashlib.sha256(data).hexdigest()])
sig = hmac.new(SK.encode(), s.encode(), hashlib.sha256).hexdigest()
headers = {"X-PS-AccessKey": AK, "X-PS-Timestamp": ts, "X-PS-Nonce": nonce,
"X-PS-Signature": sig, "Content-Type": "application/json"}
url = BASE + path + ("?" + query if query else "")
r = requests.request(method, url, data=data or None, headers=headers, timeout=30)
r.raise_for_status()
return r.json()
print(call("GET", "/api/domains", "q=example.com"))
print(call("POST", "/api/domains/12/purge", body={"urls": ["https://www.example.com/a.jpg"]}))package main
import (
"bytes"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
)
const base, ak, sk = "https://cdn.example.com", "your-access-key", "your-secret-key"
func call(method, path, query string, body []byte) (string, error) {
ts := strconv.FormatInt(time.Now().Unix(), 10)
nb := make([]byte, 8)
rand.Read(nb)
nonce := hex.EncodeToString(nb)
bh := sha256.Sum256(body)
s := strings.Join([]string{method, path, query, ts, nonce, hex.EncodeToString(bh[:])}, "\n")
m := hmac.New(sha256.New, []byte(sk))
m.Write([]byte(s))
url := base + path
if query != "" {
url += "?" + query
}
req, _ := http.NewRequest(method, url, bytes.NewReader(body))
req.Header.Set("X-PS-AccessKey", ak)
req.Header.Set("X-PS-Timestamp", ts)
req.Header.Set("X-PS-Nonce", nonce)
req.Header.Set("X-PS-Signature", hex.EncodeToString(m.Sum(nil)))
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
b, _ := io.ReadAll(resp.Body)
return string(b), nil
}
func main() {
fmt.Println(call("GET", "/api/domains", "", nil))
fmt.Println(call("POST", "/api/domains/12/purge", "", []byte(`{"urls":["https://www.example.com/a.jpg"]}`)))
}// Node.js 18+
const crypto = require('crypto');
const BASE = 'https://cdn.example.com', AK = 'your-access-key', SK = 'your-secret-key';
async function call(method, path, query = '', body) {
const data = body === undefined ? '' : JSON.stringify(body);
const ts = String(Math.floor(Date.now() / 1000)), nonce = crypto.randomBytes(8).toString('hex');
const s = [method, path, query, ts, nonce, crypto.createHash('sha256').update(data).digest('hex')].join('\n');
const sig = crypto.createHmac('sha256', SK).update(s).digest('hex');
const r = await fetch(BASE + path + (query ? '?' + query : ''), {
method, body: data || undefined,
headers: { 'X-PS-AccessKey': AK, 'X-PS-Timestamp': ts, 'X-PS-Nonce': nonce, 'X-PS-Signature': sig, 'Content-Type': 'application/json' },
});
return r.json();
}
call('GET', '/api/domains').then(console.log);
call('POST', '/api/domains/12/purge', '', { urls: ['https://www.example.com/a.jpg'] }).then(console.log);<?php
const BASE = 'https://cdn.example.com', AK = 'your-access-key', SK = 'your-secret-key';
function call($method, $path, $query = '', $body = null) {
$data = $body === null ? '' : json_encode($body, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
$ts = (string)time(); $nonce = bin2hex(random_bytes(8));
$s = implode("\n", [$method, $path, $query, $ts, $nonce, hash('sha256', $data)]);
$sig = hash_hmac('sha256', $s, SK);
$ch = curl_init(BASE . $path . ($query !== '' ? '?' . $query : ''));
curl_setopt_array($ch, [
CURLOPT_CUSTOMREQUEST => $method, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30,
CURLOPT_HTTPHEADER => ["X-PS-AccessKey: " . AK, "X-PS-Timestamp: $ts", "X-PS-Nonce: $nonce",
"X-PS-Signature: $sig", "Content-Type: application/json"],
]);
if ($data !== '') curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$out = curl_exec($ch); curl_close($ch);
return json_decode($out, true);
}
print_r(call('GET', '/api/domains'));
print_r(call('POST', '/api/domains/12/purge', '', ['urls' => ['https://www.example.com/a.jpg']]));#!/usr/bin/env bash
BASE=https://cdn.example.com AK=your-access-key SK=your-secret-key
METHOD=POST P=/api/domains/12/purge Q=''
BODY='{"urls":["https://www.example.com/a.jpg"]}'
TS=$(date +%s); NONCE=$(openssl rand -hex 8)
BH=$(printf '%s' "$BODY" | openssl dgst -sha256 -hex | awk '{print $NF}')
SIG=$(printf '%s\n%s\n%s\n%s\n%s\n%s' "$METHOD" "$P" "$Q" "$TS" "$NONCE" "$BH" | openssl dgst -sha256 -hmac "$SK" -hex | awk '{print $NF}')
curl -sS -X $METHOD "$BASE$P${Q:+?$Q}" -H "X-PS-AccessKey: $AK" -H "X-PS-Timestamp: $TS" \
-H "X-PS-Nonce: $NONCE" -H "X-PS-Signature: $SIG" -H 'Content-Type: application/json' -d "$BODY"返回与错误Responses & errors
成功时返回 HTTP 200 和 JSON 数据;失败时返回对应状态码,正文为 {"error": "错误说明"}。
Successful calls return HTTP 200 with a JSON body. Errors return the matching status code with {"error": "message"}.
| 状态码Status | 含义Meaning |
|---|---|
| 400 | 参数错误(错误说明会指出具体字段)Invalid parameters (the message names the field) |
| 401 | 签名错误、时间戳过期、Nonce 重复、AccessKey 不存在Bad signature, expired timestamp, reused nonce or unknown AccessKey |
| 403 | 来源 IP 不在密钥白名单内、账号已停用、无权操作该资源或套餐不含该功能Source IP not in the key's allowlist, account disabled, no access to the resource, or feature not in your plan |
| 404 | 资源不存在Not found |
| 429 | 请求过于频繁,请稍后重试Too many requests, retry later |
域名Domains
| 接口Endpoint | 说明Description |
|---|---|
GET/api/groups | 可用的节点集群(添加域名时的 group_id)。icp_required 为 true 的集群需要域名已备案Available node clusters (the group_id for new domains). Clusters with icp_required: true need an ICP filing. |
GET/api/domains | 域名列表。参数 q 按域名搜索List domains. q searches by hostname. |
POST/api/domains | 添加域名:{"host","group_id","config"},返回 CNAMEAdd a domain: {"host","group_id","config"}. Returns the CNAME. |
POST/api/domains/batch-create | 批量添加:{"hosts":[],"group_id","config"},逐个返回结果Bulk add: {"hosts":[],"group_id","config"}, with a result per host. |
GET/api/domains/{id} | 域名详情与完整配置Domain details and full configuration |
POST/api/domains/{id} | 修改配置:{"config":{...}}(传完整配置,建议先 GET 再改)Update: {"config":{...}}. Send the full config; GET it first and modify. |
POST/api/domains/{id}/delete | 删除域名Delete the domain |
POST/api/domains/{id}/dns-check | 立即检测 CNAME 是否已生效Check now whether the CNAME is in effect |
GET/api/domains/{id}/versions | 配置历史版本;POST /api/domains/{id}/rollback 回滚Config history. Roll back with POST /api/domains/{id}/rollback. |
常用 config 字段:
Common config fields:
| 字段Field | 说明Description |
|---|---|
origins | 源站列表 [{"addr":"1.2.3.4:80","weight":10,"backup":false}]Origins: [{"addr":"1.2.3.4:80","weight":10,"backup":false}] |
origin_proto | http / https / follow |
origin_host | 回源 Host,留空跟随访问域名Host header sent to origin; empty = the requested hostname |
https | {"cert_id":0,"auto":true,"force":true,"hsts":0} |
cc_level | off / loose / normal / strict / attack |
enabled | 是否开启加速Whether acceleration is on |
adv.auth | URL 鉴权,见 鉴权对接文档URL signing, see URL Signing |
POST /api/domains
{"host": "www.example.com", "group_id": 1,
"config": {"origins": [{"addr": "1.2.3.4:80", "weight": 10}], "origin_proto": "http", "enabled": true}}
缓存刷新与预热Purge & preload
| 接口Endpoint | 说明Description |
|---|---|
POST/api/domains/{id}/purge | {"urls":[]} 刷新 URL;{"dirs":[]} 刷新目录;{"all":true} 刷新全站;{"urls":[],"preload":true} 预热{"urls":[]} purge URLs; {"dirs":[]} purge directories; {"all":true} purge everything; {"urls":[],"preload":true} preload |
POST /api/domains/12/purge
{"urls": ["https://www.example.com/a.jpg", "https://www.example.com/b.css"]}
证书Certificates
| 接口Endpoint | 说明Description |
|---|---|
GET/api/certs | 证书列表(域名、到期时间)List certificates (names, expiry) |
POST/api/certs | 上传证书:{"cert":"PEM","key":"PEM"},返回证书 ID,填到域名 https.cert_idUpload: {"cert":"PEM","key":"PEM"}. Returns an ID to use as the domain's https.cert_id. |
POST/api/certs/apply | 申请免费证书(域名需已 CNAME 到本平台)Request a free certificate (the domain must already CNAME to us) |
GET/api/certs/jobs | 证书申请进度Certificate request progress |
POST/api/certs/{id}/delete | 删除证书Delete a certificate |
防护与黑白名单Protection & IP lists
| 接口Endpoint | 说明Description |
|---|---|
GET/api/bans | 黑白名单列表List IP block/allow entries |
POST/api/bans | {"scope":"domain","domain_id":12,"cidrs":["1.2.3.4"],"action":"block","minutes":0,"reason":""};action 为 block(拉黑)或 allow(白名单);minutes 为 0 表示永久{"scope":"domain","domain_id":12,"cidrs":["1.2.3.4"],"action":"block","minutes":0,"reason":""}. action is block or allow; minutes: 0 = permanent. |
POST/api/bans/delete | 删除条目Remove entries |
GET/api/domains/{id}/rules | 自定义防护规则;POST 同地址保存Custom protection rules; POST to the same path to save |
POST/api/domains/{id}/uam | 开关被攻击模式Turn Under-Attack mode on/off |
POST/api/domains/{id}/unban-ip | 解封被自动封禁的 IPRelease an automatically banned IP |
统计与日志Stats & logs
| 接口Endpoint | 说明Description |
|---|---|
GET/api/stats/series | 流量、请求数、命中、状态码时间序列。参数:range=1h/24h/7d/30d,或 from、to(Unix 秒);domain=域名 ID(可选)。bytes 为该时间点流量(字节)Time series of traffic, requests, hits and status codes. Params: range=1h/24h/7d/30d, or from/to (Unix seconds); domain=domain ID (optional). bytes is traffic in bytes. |
GET/api/stats/top | TOP IP / URL / 国家,参数同上Top IPs / URLs / countries, same params |
GET/api/stats/codes | 状态码分布,参数同上Status code breakdown, same params |
POST/api/domains/{id}/logs | 查询访问日志Query access logs |
GET/api/domains/{id}/logs/download | 下载访问日志Download access logs |
GET /api/stats/series?range=7d&domain=12
账户与流量包Account & packages
| 接口Endpoint | 说明Description |
|---|---|
GET/api/me | 当前账户信息Current account |
GET/api/overview | 概览:域名数、今日流量等Overview: domain count, today's traffic, etc. |
GET/api/packages | 流量包及剩余量Traffic packages and remaining quota |
GET/api/bills | 账单列表Bills |
旧版令牌Legacy tokens
早期创建的密钥是令牌形式 KeyID.Secret,仍可通过 Authorization: Bearer KeyID.Secret 调用,写操作需另加 X-Requested-With: cdnps。新接入请使用 AK/SK 签名;新创建的密钥两种方式都可用(令牌即 AccessKey.SecretKey)。
Keys created earlier are tokens of the form KeyID.Secret. They still work with Authorization: Bearer KeyID.Secret; write requests also need X-Requested-With: cdnps. Use AK/SK signing for new integrations. New keys support both (the token is AccessKey.SecretKey).