API 密钥
Spell APIAPI KeysAPI Secrets
介绍了如何使用 API Key 进行身份验证,并使用 API Secrets 对请求进行签名。
API密钥用于验证您向 Spell API 发起的请求。每个账户最多可创建10个API密钥对。
API密钥包含两个部分:
- API Key:密钥的唯一标识
- API Secret:用于请求签名。该密钥仅在创建时显示一次,请务必妥善保管。
🚨 警告:请将 API Key 和 API Secret 视为机密信息。切勿公开分享或在前端代码中暴露。
使用 API Key 认证
使用 Spell API时,您需要在请求头的 X-API-Key
中包含您的 API Key,格式如下:
X-API-Key: <API Key>
以下是使用 curl
的示例:
curl --request GET
--url https://api.spell.im/v1/account
--header 'X-API-Key: <您的API Key>'
给请求签名
在请求安全等级更高的 API 时(POST
请求),您需要对请求进行签名,以便 Spell 验证请求的安全性。
签名生成规则
- 准备请求体:在请求体中,添加一个
timestamp
的参数,其值为当前 UNIX 毫秒级时间戳(例如:1698765432340
),用于防止重放攻击。 - 序列化:将包含
timestamp
的请求体按字母顺序排序,然后序列化为字符串。 - 计算签名:使用您的
API Secret
对序列化后的字符串进行HMAC-SHA256
签名。
在请求头中包含签名
将计算好的签名添加到请求头 X-Signature
中,格式如下:
X-API-Key: <API Key>
X-Signature: <SIGNATURE>
以下是使用 Node.js
的 crypto
模块的示例:
import * as crypto from 'crypto';
// 构造签名数据
const timestamp = Date.now();
const signedBody = { ...body, timestamp };
const serializedBodyString = serializeData(signedBody);
const xSignature = createSignature(serializedBodyString);
// 以下为工具函数:serializeData() 和 createSignature()
/**
* 数据序列化
* @param data - 原始数据
* @returns 序列化后的数据,格式:key1=value1&key2=value2...
*/
function serializeData(data: Record<string, any>): string {
return Object.keys(data)
.sort()
.map(key => {
const value = data[key];
const strValue = typeof value === 'object'
? JSON.stringify(value)
: String(value);
return `${key}=${strValue}`;
})
.join('&');
}
/**
* 计算签名
* @param serializedData - 序列化后的数据
* @param secretKey - 您的密钥密文
* @returns 十六进制格式的签名
*/
function calculateSignature(serializedData: string, secretKey: string): string {
const hmac = crypto.createHmac('sha256', secretKey);
hmac.update(serializedData);
return hmac.digest('hex');
}
发送带签名的请求
这是一个使用 curl
发送 POST
请求的完整示例:
curl --request POST
--url https://api.spell.im/v1/order/create
--header 'Content-Type: application/json'
--header 'X-API-Key: <您的API Key>'
--header 'X-Signature: 02b0c2a7134d1...'
--data '{
"order_no": "A001",
"timestamp": 1698765432236,
"timeout": 3600,
...
}'