---
title: "API 密钥 | Tajo"
description: "Brevo API 密钥身份认证完整指南"
url: https://tajo.io/zh-cn/docs/authentication/api-keys/
markdown: https://tajo.io/zh-cn/docs/authentication/api-keys.md
lang: zh-CN
author: "Set Noa"
author_url: https://tajo.io/zh-cn/set-noa/
robots: noindex
---

申请抢先体验

请输入您的名字和公司电子邮箱地址。我们会发送确认 Tajo 访问申请的链接。

# API 密钥

[Set Noa](https://tajo.io/zh-cn/set-noa/)

API 密钥是 Brevo API 的主要身份认证方式。它以简单且安全的方式，让程序化访问你的账号成为可能。

## 什么是 API 密钥？

API 密钥是唯一标识符，在向 Brevo API 发起请求时用于认证你的应用。每个密钥都是一个 64 位字符串，同时充当标识符和密码。

```
Example API key: xkeysib-a1b2c3d4e5f6789012345678901234567890abcdef1234567890abcdef123456-Ab1Cd2Ef3Gh4
```

## 生成 API 密钥

### 分步指南

1. **登录 Brevo**：打开你的 [Brevo 仪表板](https://app.brevo.com/)
2. **进入设置**：点击个人头像 → 设置
3. **打开 API 密钥页**：在左侧菜单中选择 “API Keys”
4. **创建新密钥**：点击 “Generate a New API Key”
5. **为密钥命名**：起一个说明用途的名称（例如 “Production App”、“Development Testing”）
6. **设置权限**：选择合适的访问级别
7. **生成**：点击 “Generate” 并立即复制密钥

### API 密钥命名约定

使用能说明密钥用途的描述性名称：

- `production-web-app`
- `staging-environment`
- `mobile-app-ios`
- `webhook-listener`
- `data-sync-service`

## API 密钥类型与权限

### 完全访问密钥

```
Permissions: All API endpoints
Use cases: Complete application integration
Risk level: High - protect carefully
```

### 只读密钥

```
Permissions: GET requests only
Use cases: Analytics, reporting, dashboards
Risk level: Low - limited access
```

### 仅发送密钥

```
Permissions: Transactional email sending
Use cases: Application notifications, receipts
Risk level: Medium - can send emails
```

### 联系人管理密钥

```
Permissions: Contact CRUD operations
Use cases: CRM integrations, form submissions
Risk level: Medium - data modification
```

## 使用 API 密钥

### 请求头认证

在 `api-key` 请求头中携带你的 API 密钥：

```http
GET /v3/account HTTP/1.1
Host: api.brevo.com
Accept: application/json
Content-Type: application/json
api-key: YOUR_API_KEY
```

### 代码示例

#### JavaScript/Node.js

```javascript
const brevo = require('@getbrevo/brevo');

const apiInstance = new brevo.AccountApi();
apiInstance.setApiKey(brevo.AccountApiApiKeys.apiKey, process.env.BREVO_API_KEY);

// Make authenticated request
apiInstance.getAccount()
  .then(data => console.log('Account info:', data))
  .catch(error => console.error('Error:', error));
```

#### Python

```python
import sib_api_v3_sdk
from sib_api_v3_sdk.rest import ApiException

# Configure API key
configuration = sib_api_v3_sdk.Configuration()
configuration.api_key['api-key'] = 'YOUR_API_KEY'

# Create API instance
api_instance = sib_api_v3_sdk.AccountApi(sib_api_v3_sdk.ApiClient(configuration))

try:
    # Get account info
    api_response = api_instance.get_account()
    print(api_response)
except ApiException as e:
    print("Exception when calling AccountApi->get_account: %s\n" % e)
```

#### PHP

```php
<?php
require_once(__DIR__ . '/vendor/autoload.php');

// Configure API key
$config = SendinBlue\Client\Configuration::getDefaultConfiguration()->setApiKey('api-key', 'YOUR_API_KEY');

// Create API instance
$apiInstance = new SendinBlue\Client\Api\AccountApi(
    new GuzzleHttp\Client(),
    $config
);

try {
    $result = $apiInstance->getAccount();
    print_r($result);
} catch (Exception $e) {
    echo 'Exception when calling AccountApi->getAccount: ', $e->getMessage(), PHP_EOL;
}
?>
```

#### Ruby

```ruby
require 'sib-api-v3-sdk'

# Configure API key
SibApiV3Sdk.configure do |config|
  config.api_key['api-key'] = 'YOUR_API_KEY'
end

# Create API instance
api_instance = SibApiV3Sdk::AccountApi.new

begin
  # Get account info
  result = api_instance.get_account
  puts result
rescue SibApiV3Sdk::ApiError => e
  puts "Exception when calling AccountApi->get_account: #{e}"
end
```

## API 密钥安全

### 安全存储

**环境变量**（推荐）

```bash
# .env file
BREVO_API_KEY=xkeysib-your-api-key-here

# Usage in code
const apiKey = process.env.BREVO_API_KEY;
```

**云端密钥管理服务**

- AWS Secrets Manager
- Google Secret Manager
- Azure Key Vault
- HashiCorp Vault

### 安全最佳实践

1. **切勿硬编码密钥**

   ```javascript
   // ❌ Bad - hardcoded
   const apiKey = "xkeysib-a1b2c3d4...";

   // ✅ Good - environment variable
   const apiKey = process.env.BREVO_API_KEY;
   ```

2. **为每个环境使用不同的密钥**

   ```
   Production:  BREVO_API_KEY_PROD
   Staging:     BREVO_API_KEY_STAGING
   Development: BREVO_API_KEY_DEV
   ```

3. **定期轮换密钥**

   - 设置日历提醒，每季度轮换一次
   - 使用自动化工具完成密钥轮换
   - 准备好回滚方案

4. **监控密钥使用情况**

   - 为异常活动配置告警
   - 每月审查密钥使用日志
   - 追踪访问来源的地理分布

## 密钥管理

### 活跃密钥监控

在仪表板中监控你的活跃密钥：

```
Key Name: production-web-app
Created: 2024-01-15
Last Used: 2024-01-20 14:30 UTC
Requests Today: 1,247
Status: Active
```

### 密钥轮换流程

1. **生成新密钥**：创建替换用的密钥
2. **更新配置**：使用新密钥完成部署
3. **观察运行**：确认新密钥工作正常
4. **过渡期**：让旧密钥继续保持有效 24 至 48 小时
5. **吊销旧密钥**：删除此前的密钥

### 紧急吊销密钥

如果密钥已泄露：

1. **立即吊销**：在仪表板中删除该密钥
2. **生成替换密钥**：立刻创建新密钥
3. **更新应用**：尽快用新密钥完成部署
4. **监控活动**：排查是否存在未授权使用
5. **事件报告**：记录此次安全事件

## 速率限制与 API 密钥

Brevo 按端点限制请求，而不是按天限制。在每种套餐都适用的通用档位上，`POST /v3/smtp/email` 允许每秒 1,000 次请求，`/v3/contacts` 端点允许每秒 10 次、每小时 36,000 次，没有自身限制的端点允许每小时 100 次。Professional 和 Enterprise 套餐可解锁更高的档位。完整表格请参阅[速率限制](https://tajo.io/zh-cn/docs/rate-limits/)。

### 速率限制响应头

```http
HTTP/1.1 200 OK
x-sib-ratelimit-limit: 1000
x-sib-ratelimit-remaining: 750
x-sib-ratelimit-reset: 1
```

### 处理速率限制

```javascript
async function makeApiCall() {
  try {
    const response = await fetch(url, { headers });

    if (response.status === 429) {
      // Seconds until the window resets
      const waitTime = Number(response.headers.get('x-sib-ratelimit-reset') || 1);

      console.log(`Rate limited. Waiting ${waitTime} seconds`);
      await new Promise(resolve => setTimeout(resolve, waitTime * 1000));

      // Retry the request
      return makeApiCall();
    }

    return response.json();
  } catch (error) {
    console.error('API call failed:', error);
    throw error;
  }
}
```

## API 密钥问题排查

### 常见错误信息

**API 密钥无效 (401)**

```json
{
  "code": "unauthorized",
  "message": "Invalid API key provided"
}
```

**权限不足 (403)**

```json
{
  "code": "permission_denied",
  "message": "API key does not have required permissions"
}
```

**超出速率限制 (429)**

```json
{
  "code": "too_many_requests",
  "message": "Rate limit exceeded for API key"
}
```

### 排查清单

- 密钥格式正确（64 位字符）
- 没有多余空格或隐藏字符
- 密钥具备所需权限
- 密钥处于有效状态（未被吊销）
- 未超出速率限制
- 使用了正确的 API 端点
- 请求头格式正确

## 后续步骤

- [了解 OAuth 2.0](https://tajo.io/zh-cn/docs/authentication/oauth/)
- 了解 JWT 令牌
- [查看速率限制](https://tajo.io/zh-cn/docs/rate-limits/)
- [体验 SDK](https://tajo.io/zh-cn/docs/sdks-libraries/)
