---
title: "宝塔域名 API 概览与签名认证"
description: "宝塔域名 API 调用总览：接口地址 https://dmp.bt.cn/，仅支持 HTTPS，每账号每日 2000 次限额，含 HMAC-SHA256 签名计算示例与 API 密钥获取入口说明。"
---

> Documentation Index
> Fetch the complete documentation index at: https://docs.bt.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# 宝塔域名 API 概览与签名认证

## 概览

## 操作场景

欢迎使用堡塔域名 API，您可以使用本文档介绍的 API 对域名服务进行相关操作。

接口地址：
```text
https://dmp.bt.cn/
```

:::warning 限制说明
- 接口仅支持 HTTPS 。
- 请合理使用 API 接口，注意请求频率，超限将在一定时间内暂停 API 权限，每个账号每日最多可调用 2000 次 API 接口。
- 请勿使用 API 接口来抢注过期域名，若短时间内重复提交相同域名尝试注册，会被禁用 API 权限。
:::

## API签名认证
API 密钥可前往[堡塔域名管理后台](https://www.bt.cn/domain/domain-security) - "域名安全" 页面获取。

### 签名计算步骤

#### 1. 准备参数

```python
account_id = "acct_abc123def456"
access_key = "ak_789ghi012jkl345mno678pqr901stu"
secret_key = "sk_234vwx567yza890bcd123efg456hij"
timestamp = str(int(time.time()))
method = "POST"
path = "/api/v1/dns/record/create"
body = '{"domain_id":123,"record":"www","type":"A","value":"192.168.1.1"}'
```

#### 2. 构建签名字符串

```python
signing_string = f"{account_id}\n{timestamp}\n{method}\n{path}\n{body}"
```

#### 3. 计算HMAC-SHA256签名

```python
import hmac
import hashlib

signature = hmac.new(
    secret_key.encode(), 
    signing_string.encode(), 
    hashlib.sha256
).hexdigest()
```

#### 4. 发送请求

```python
headers = {
    "Content-Type": "application/json",
    "X-Account-ID": account_id,
    "X-Access-Key": access_key,
    "X-Timestamp": timestamp,
    "X-Signature": signature
}
```

## 完整示例代码

### Python示例

```python
#!/usr/bin/env python3
import requests
import hmac
import hashlib
import time
import json

class DNSApiClient:
    def __init__(self, account_id, access_key, secret_key, base_url):
        self.account_id = account_id
        self.access_key = access_key
        self.secret_key = secret_key
        self.base_url = base_url.rstrip('/')
    
    def _generate_signature(self, method, path, body=""):
        """生成 API 签名"""
        timestamp = str(int(time.time()))
        
        # 构建签名字符串
        signing_string = f"{self.account_id}\n{timestamp}\n{method.upper()}\n{path}\n{body}"
        
        # 计算 HMAC-SHA256 签名
        signature = hmac.new(
            self.secret_key.encode(),
            signing_string.encode(),
            hashlib.sha256
        ).hexdigest()
        
        return timestamp, signature
    
    def _make_request(self, method, path, data=None):
        """发起 API 请求"""
        url = f"{self.base_url}{path}"
        body = json.dumps(data) if data else ""
        
        # 生成签名
        timestamp, signature = self._generate_signature(method, path, body)
        
        # 构建请求头
        headers = {
            "Content-Type": "application/json",
            "X-Account-ID": self.account_id,
            "X-Access-Key": self.access_key,
            "X-Timestamp": timestamp,
            "X-Signature": signature
        }
        
        # 发送请求
        response = requests.request(
            method=method,
            url=url,
            headers=headers,
            data=body if body else None
        )
        
        return response.json()
    
    def create_dns_record(self, domain_id, record, record_type, value, ttl=600):
        """创建 DNS 记录"""
        data = {
            "domain_id": domain_id,
            "record": record,
            "type": record_type,
            "value": value,
            "ttl": ttl
        }
        return self._make_request("POST", "/api/v1/dns/record/create", data)
    
    def list_dns_records(self, domain_id):
        """获取 DNS 记录列表"""
        data = {"domain_id": domain_id}
        return self._make_request("POST", "/api/v1/dns/record/list", data)
    
    def create_domain(self, domain_id):
        """初始化域名 DNS"""
        data = {"domain_id": domain_id}
        return self._make_request("POST", "/api/v1/dns/domain/create", data)

# 使用示例
if __name__ == "__main__":
    # 初始化客户端
    client = DNSApiClient(
        account_id="acct_abc123def456",
        access_key="ak_789ghi012jkl345mno678pqr901stu", 
        secret_key="sk_234vwx567yza890bcd123efg456hij",
        base_url="https://your-domain.com"
    )
    
    # 创建 DNS 记录
    result = client.create_dns_record(
        domain_id=123,
        record="www",
        record_type="A", 
        value="192.168.1.1"
    )
    print("创建 DNS 记录结果:", result)
    
    # 获取 DNS 记录列表
    records = client.list_dns_records(domain_id=123)
    print("DNS 记录列表:", records)
```

### PHP示例

```php
<?php
class DNSApiClient {
    private $accountId;
    private $accessKey;
    private $secretKey;
    private $baseUrl;
    
    public function __construct($accountId, $accessKey, $secretKey, $baseUrl) {
        $this->accountId = $accountId;
        $this->accessKey = $accessKey;
        $this->secretKey = $secretKey;
        $this->baseUrl = rtrim($baseUrl, '/');
    }
    
    private function generateSignature($method, $path, $body = '') {
        $timestamp = (string)time();
        
        // 构建签名字符串
        $signingString = implode("\n", [
            $this->accountId,
            $timestamp,
            strtoupper($method),
            $path,
            $body
        ]);
        
        // 计算 HMAC-SHA256 签名
        $signature = hash_hmac('sha256', $signingString, $this->secretKey);
        
        return [$timestamp, $signature];
    }
    
    private function makeRequest($method, $path, $data = null) {
        $body = $data ? json_encode($data) : '';
        list($timestamp, $signature) = $this->generateSignature($method, $path, $body);
        
        $headers = [
            'Content-Type: application/json',
            'X-Account-ID: ' . $this->accountId,
            'X-Access-Key: ' . $this->accessKey,
            'X-Timestamp: ' . $timestamp,
            'X-Signature: ' . $signature
        ];
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->baseUrl . $path);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        
        if ($body) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
        }
        
        $response = curl_exec($ch);
        curl_close($ch);
        
        return json_decode($response, true);
    }
    
    public function createDnsRecord($domainId, $record, $type, $value, $ttl = 600) {
        $data = [
            'domain_id' => $domainId,
            'record' => $record,
            'type' => $type,
            'value' => $value,
            'ttl' => $ttl
        ];
        return $this->makeRequest('POST', '/api/v1/dns/record/create', $data);
    }
}

// 使用示例
$client = new DNSApiClient(
    'acct_abc123def456',
    'ak_789ghi012jkl345mno678pqr901stu',
    'sk_234vwx567yza890bcd123efg456hij',
    'https://your-domain.com'
);

$result = $client->createDnsRecord(123, 'www', 'A', '192.168.1.1');
echo json_encode($result, JSON_PRETTY_PRINT);
?>
```


## 错误处理

### 常见错误码

| 错误码 | 错误信息               | 解决方法                               |
| ------ | ---------------------- | -------------------------------------- |
| 401    | 缺少 API 签名参数      | 检查请求头是否包含所有必需参数         |
| 401    | 时间戳格式错误         | 确保时间戳为 Unix 时间戳格式           |
| 401    | 请求时间戳无效         | 检查客户端时间是否同步                 |
| 401    | API 配置无效           | 检查 Account ID 和 Access Key 是否正确 |
| 403    | IP 地址不在白名单中    | 将客户端 IP 添加到白名单               |
| 401    | API 签名验证失败       | 检查签名计算是否正确                   |


## 支持的接口

### 域名管理

- `POST /api/v1/dns/manage/list_domains`        - 获取域名列表
- `POST /api/v1/dns/manage/add_external_domain` - 添加外部域名
- `POST /api/v1/dns/manage/remove_domain`       - 删除外部域名
- `POST /api/v1/dns/manage/check_domain_status` - 检查域名状态

### 解析记录管理

- `POST /api/v1/dns/record/create` - 创建解析记录
- `POST /api/v1/dns/record/update` - 更新解析记录  
- `POST /api/v1/dns/record/delete` - 删除解析记录
- `POST /api/v1/dns/record/list` - 获取解析记录列表
- `POST /api/v1/dns/record/pause` - 暂停解析记录
- `POST /api/v1/dns/record/start` - 启动解析记录

更多接口详情请参考 API 文档。

Source: https://docs.bt.cn/domain/api/overview/index.mdx
