跳至主要内容

Webhooks API

Webhooks API 提供了 7 个方法,用于管理 Webhook 订阅。Webhook 允许你的应用在事件发生时(交易确认、兑换完成、订单完成等)接收实时通知。

方法

方法参数返回值描述
listWebhooks()--ApiResponse<Webhook[]>列出当前项目配置的所有 Webhook。
getWebhook(webhookId)webhookId: stringApiResponse<Webhook>返回单个 Webhook 的详细信息。
createWebhook(input)input: CreateWebhookInputApiResponse<Webhook>创建新的 Webhook 订阅。
updateWebhook(webhookId, input)webhookId: string, input: UpdateWebhookInputApiResponse<Webhook>更新现有 Webhook 的配置。
deleteWebhook(webhookId)webhookId: stringApiResponse<{ deleted: boolean }>删除 Webhook 订阅。
getWebhookDeliveries(webhookId, options?)webhookId: string, options?: DeliveryListOptionsApiResponse<WebhookDelivery[]>返回 Webhook 的投递历史。
testWebhook(webhookId)webhookId: stringApiResponse<WebhookDelivery>向 Webhook endpoint 发送测试负载。

类型

Webhook

interface Webhook {
id: string;
/** Project this webhook belongs to. */
projectId: string;
/** HTTPS URL that receives POST requests. */
url: string;
/** Events this webhook subscribes to. */
events: WebhookEventType[];
/** Secret used to sign payloads (HMAC-SHA256). */
secret: string;
/** Whether the webhook is active. */
active: boolean;
/** Optional description. */
description?: string;
/** Number of consecutive failures. Webhook is auto-disabled after 10. */
failureCount: number;
createdAt: string;
updatedAt: string;
}

WebhookEventType

type WebhookEventType =
| 'transaction.confirmed'
| 'transaction.failed'
| 'swap.completed'
| 'swap.failed'
| 'onramp.completed'
| 'onramp.failed'
| 'offramp.completed'
| 'offramp.failed'
| 'bridge.completed'
| 'bridge.failed'
| 'ai_order.created'
| 'ai_order.completed'
| 'ai_order.redeemed'
| 'ai_trade.executed'
| 'forex_investment.created'
| 'forex_investment.redeemed'
| 'staking.reward_claimed'
| 'contract.event'
| 'nft.transferred';

CreateWebhookInput

interface CreateWebhookInput {
/** HTTPS endpoint URL. */
url: string;
/** Events to subscribe to. */
events: WebhookEventType[];
/** Optional description. */
description?: string;
/** Whether the webhook starts active. Default true. */
active?: boolean;
}

UpdateWebhookInput

interface UpdateWebhookInput {
/** Update the endpoint URL. */
url?: string;
/** Replace the event subscriptions. */
events?: WebhookEventType[];
/** Update the description. */
description?: string;
/** Enable or disable the webhook. */
active?: boolean;
}

WebhookDelivery

interface WebhookDelivery {
id: string;
webhookId: string;
/** Event that triggered the delivery. */
event: WebhookEventType;
/** HTTP status code returned by the endpoint. */
statusCode: number;
/** Whether the delivery was successful (2xx response). */
success: boolean;
/** Request payload sent to the endpoint. */
requestBody: Record<string, unknown>;
/** Response body returned by the endpoint (truncated). */
responseBody?: string;
/** Response time in milliseconds. */
durationMs: number;
/** Delivery attempt number (retries increment this). */
attempt: number;
createdAt: string;
}

DeliveryListOptions

interface DeliveryListOptions {
/** Filter by success/failure. */
success?: boolean;
/** Filter by event type. */
event?: WebhookEventType;
limit?: number;
cursor?: string;
}

Webhook 负载格式

每次 Webhook 投递都会发送一个包含 JSON 正文的 POST 请求:

interface WebhookPayload {
/** Unique delivery ID. */
id: string;
/** Event type. */
event: WebhookEventType;
/** ISO 8601 timestamp. */
timestamp: string;
/** Project ID. */
projectId: string;
/** Event-specific data. */
data: Record<string, unknown>;
}

签名验证

负载使用 Webhook 的 secret 通过 HMAC-SHA256 进行签名。签名通过 X-Webhook-Signature 请求头发送。

import crypto from 'crypto';

function verifyWebhookSignature(
payload: string,
signature: string,
secret: string
): boolean {
const expected = crypto
.createHmac('sha256', secret)
.update(payload)
.digest('hex');
return crypto.timingSafeEqual(
Buffer.from(signature),
Buffer.from(expected)
);
}

示例

创建 Webhook

const res = await engine.createWebhook({
url: 'https://myapp.com/webhooks/one',
events: [
'transaction.confirmed',
'swap.completed',
'ai_order.completed',
],
description: 'Production webhook for order notifications',
});

if (res.success && res.data) {
console.log('Webhook created:', res.data.id);
console.log('Secret:', res.data.secret);
// Store the secret securely for payload verification
}

列出 Webhook

const res = await engine.listWebhooks();

if (res.success && res.data) {
for (const wh of res.data) {
console.log(`${wh.id} | ${wh.url} | Active: ${wh.active} | Events: ${wh.events.length}`);
}
}

更新 Webhook

const res = await engine.updateWebhook('wh_abc123', {
events: [
'transaction.confirmed',
'transaction.failed',
'swap.completed',
'swap.failed',
'ai_order.completed',
'ai_order.redeemed',
],
active: true,
});

测试 Webhook

const res = await engine.testWebhook('wh_abc123');

if (res.success && res.data) {
console.log(`Test delivery: ${res.data.success ? 'OK' : 'FAILED'}`);
console.log(`Status: ${res.data.statusCode} | ${res.data.durationMs}ms`);
}

查看投递历史

const res = await engine.getWebhookDeliveries('wh_abc123', {
success: false,
limit: 20,
});

if (res.success && res.data) {
for (const d of res.data) {
console.log(`${d.createdAt} | ${d.event} | ${d.statusCode} | Attempt: ${d.attempt}`);
}
}

删除 Webhook

const res = await engine.deleteWebhook('wh_abc123');

if (res.success && res.data?.deleted) {
console.log('Webhook deleted');
}

重试策略

失败的投递将使用指数退避进行重试:

尝试次数延迟
1立即
21 分钟
35 分钟
430 分钟
52 小时

连续失败 10 次后,Webhook 将自动禁用。通过调用 updateWebhook 并设置 active: true 可以重新启用。

后续步骤