快速上手

KernelHost API

1. 创建 API 密钥

登录客户门户的「KernelHost API」页面并创建一个密钥。只选择您实际需要的权限范围(默认:只读)。该 secret 仅显示一次,请将其妥善保存在您的密钥管理工具中。

2. 存储凭据

将 key 与 secret 存储为环境变量。切勿写入代码,切勿提交到代码仓库。

# .env 或 shell 配置文件
export KH_KEY="kh_live_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
export KH_SECRET="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"

3. 发送第一个请求

列出可用产品。签名基于方法、路径、时间戳、随机数与请求体哈希生成。

TS=$(date +%s)
NONCE=$(openssl rand -hex 16)
BODY_SHA256=$(printf '' | openssl dgst -sha256 -hex | awk '{print $NF}')
SIG_INPUT=$(printf 'GET\n/v1/products\n%s\n%s\n%s' "$TS" "$NONCE" "$BODY_SHA256")
SIG=$(printf '%s' "$SIG_INPUT" | openssl dgst -sha256 -hmac "$KH_SECRET" -hex | awk '{print $NF}')

curl https://www.kernelhost.com/cp/kernelhost_api/v1/products \
  -H "KH-Key: $KH_KEY" \
  -H "KH-Timestamp: $TS" \
  -H "KH-Nonce: $NONCE" \
  -H "KH-Signature: $SIG"

4. 提交订单

重要:POST /v1/orders 必须携带 Idempotency-Key,并指定主机名。若在网络错误后使用同一个 Key 重试,您将收到相同的响应,而不会产生第二笔订单。您未指定的配置选项(例如机房位置或操作系统)将自动采用商店中提供的第一个值。

BODY='{"product_id":42,"billing_cycle":"monthly","hostname":"web01.example.com"}'
IDEM="order-web01-$(date +%Y%m%d)"
BODY_SHA256=$(printf '%s' "$BODY" | openssl dgst -sha256 -hex | awk '{print $NF}')
TS=$(date +%s)
NONCE=$(openssl rand -hex 16)
SIG_INPUT=$(printf 'POST\n/v1/orders\n%s\n%s\n%s' "$TS" "$NONCE" "$BODY_SHA256")
SIG=$(printf '%s' "$SIG_INPUT" | openssl dgst -sha256 -hmac "$KH_SECRET" -hex | awk '{print $NF}')

curl -X POST https://www.kernelhost.com/cp/kernelhost_api/v1/orders \
  -H "KH-Key: $KH_KEY" \
  -H "KH-Timestamp: $TS" \
  -H "KH-Nonce: $NONCE" \
  -H "KH-Signature: $SIG" \
  -H "Idempotency-Key: $IDEM" \
  -H "Content-Type: application/json" \
  --data "$BODY"

5. 查询状态并获取凭据

订单响应中会列出 service_ids。请轮询 GET /v1/services/{id},直到 status 为 active 且已分配 IP 地址;开通通常只需几秒到几分钟。随后,GET /v1/services/{id}/credentials(权限范围 read:credentials)将返回主机名、IP 地址、用户名与密码,例如可用于您的 Ansible 主机清单。

kh_get() {
  TS=$(date +%s)
  NONCE=$(openssl rand -hex 16)
  BODY_SHA256=$(printf '' | openssl dgst -sha256 -hex | awk '{print $NF}')
  SIG_INPUT=$(printf 'GET\n%s\n%s\n%s\n%s' "$1" "$TS" "$NONCE" "$BODY_SHA256")
  SIG=$(printf '%s' "$SIG_INPUT" | openssl dgst -sha256 -hmac "$KH_SECRET" -hex | awk '{print $NF}')
  curl -s "https://www.kernelhost.com/cp/kernelhost_api$1" \
    -H "KH-Key: $KH_KEY" \
    -H "KH-Timestamp: $TS" \
    -H "KH-Nonce: $NONCE" \
    -H "KH-Signature: $SIG"
}

kh_get /v1/services/1234
kh_get /v1/services/1234/credentials

6. 设置 Webhook URL(可选)

您现在即可为每个密钥设置一个 HTTPS URL。事件推送功能正在筹备中;在此之前,请使用第 5 步中的状态查询。