Webhook集成与管理Skill webhooks

Webhook是一种API技术,允许应用程序接收外部事件和数据,用于自动化流程、系统集成和触发操作,广泛应用于量化交易、数据分析、实时通知和DevOps自动化等领域。关键词:Webhook, API集成, 自动化, 实时数据, 信号处理, 交易系统, DevOps, 后端开发

后端开发 0 次安装 0 次浏览 更新于 3/9/2026

名称: webhooks 描述: “用于自定义数据和信号接收的传入Webhooks” 表情符号: “🪝”

Webhooks - 完整API参考

创建传入Webhook端点以接收外部信号、数据并触发操作。


聊天命令

创建Webhooks

/webhook create trading-signals             创建新Webhook
/webhook create alerts --secret abc123      使用自定义密钥
/webhook list                               列出所有Webhooks

管理Webhooks

/webhook info <name>                        查看Webhook详情
/webhook url <name>                         获取Webhook URL
/webhook regenerate <name>                  生成新的URL/密钥
/webhook delete <name>                      删除Webhook

测试

/webhook test <name>                        发送测试负载
/webhook test <name> '{"signal":"BUY"}'     自定义测试负载
/webhook logs <name>                        查看最近负载
/webhook debug <name>                       启用调试模式

操作

/webhook action <name> add notify           添加触发时的通知操作
/webhook action <name> add execute          添加交易操作
/webhook action <name> remove <id>          删除操作
/webhook action <name> list                 列出操作

TypeScript API参考

创建Webhook管理器

import { createWebhookManager } from 'clodds/webhooks';

const webhooks = createWebhookManager({
  // Webhooks的基础URL
  baseUrl: 'https://your-domain.com',

  // 默认设置
  defaultSecret: process.env.WEBHOOK_SECRET,
  validateSignatures: true,

  // 存储
  storage: 'sqlite',
  dbPath: './webhooks.db',

  // 日志
  logPayloads: true,
  maxLogEntries: 1000,
});

创建Webhook

// 创建简单Webhook
const hook = await webhooks.create({
  name: 'trading-signals',
  description: '接收外部交易信号',
});

console.log(`Webhook URL: ${hook.url}`);
console.log(`密钥: ${hook.secret}`);

// 使用模式验证创建
const hook = await webhooks.create({
  name: 'price-alerts',
  description: '价格警报触发',
  schema: {
    type: 'object',
    properties: {
      symbol: { type: 'string' },
      price: { type: 'number' },
      direction: { enum: ['above', 'below'] },
    },
    required: ['symbol', 'price', 'direction'],
  },
});

处理Webhook

// 注册处理器
webhooks.onReceive('trading-signals', async (payload, metadata) => {
  console.log(`收到信号: ${JSON.stringify(payload)}`);
  console.log(`来自IP: ${metadata.ip}`);
  console.log(`时间戳: ${metadata.timestamp}`);

  // 处理信号
  if (payload.action === 'BUY') {
    await tradingBot.buy(payload.symbol, payload.amount);
  }

  // 返回响应
  return { status: 'processed', id: metadata.id };
});

添加操作

// 添加通知操作
await webhooks.addAction('trading-signals', {
  type: 'notify',
  channels: ['telegram', 'discord'],
  template: '新信号: {{action}} {{symbol}} @ {{price}}',
});

// 添加交易操作
await webhooks.addAction('trading-signals', {
  type: 'execute',
  condition: (payload) => payload.confidence > 0.8,
  action: async (payload) => {
    return await tradingBot.execute({
      platform: 'polymarket',
      market: payload.market,
      side: payload.side,
      size: payload.size,
    });
  },
});

// 添加日志操作
await webhooks.addAction('trading-signals', {
  type: 'log',
  destination: 'database',
  table: 'signal_history',
});

获取Webhook信息

const info = await webhooks.get('trading-signals');

console.log(`名称: ${info.name}`);
console.log(`URL: ${info.url}`);
console.log(`创建时间: ${info.createdAt}`);
console.log(`触发次数: ${info.triggerCount}`);
console.log(`最后触发: ${info.lastTrigger}`);
console.log(`操作数量: ${info.actions.length}`);

查看日志

// 获取最近负载
const logs = await webhooks.getLogs('trading-signals', {
  limit: 50,
  since: Date.now() - 24 * 60 * 60 * 1000,  // 过去24小时
});

for (const log of logs) {
  console.log(`[${log.timestamp}] ${log.status}`);
  console.log(`  负载: ${JSON.stringify(log.payload)}`);
  console.log(`  响应: ${JSON.stringify(log.response)}`);
}

测试Webhook

// 发送测试负载
const result = await webhooks.test('trading-signals', {
  action: 'BUY',
  symbol: 'BTC',
  price: 100000,
  confidence: 0.95,
});

console.log(`测试结果: ${result.status}`);
console.log(`响应: ${JSON.stringify(result.response)}`);

删除Webhook

await webhooks.delete('trading-signals');

Webhook安全

签名验证

// Webhooks使用HMAC-SHA256签名
// 头信息: X-Webhook-Signature: sha256=<签名>

// 在发送者中验证:
const crypto = require('crypto');
const signature = crypto
  .createHmac('sha256', webhookSecret)
  .update(JSON.stringify(payload))
  .digest('hex');

fetch(webhookUrl, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-Webhook-Signature': `sha256=${signature}`,
  },
  body: JSON.stringify(payload),
});

IP白名单

const hook = await webhooks.create({
  name: 'secure-signals',
  allowedIps: ['192.168.1.0/24', '10.0.0.1'],
});

发送Webhooks(外部)

# 发送信号到您的Webhook
curl -X POST https://your-domain.com/webhooks/trading-signals \
  -H "Content-Type: application/json" \
  -H "X-Webhook-Signature: sha256=<签名>" \
  -d '{"action": "BUY", "symbol": "TRUMP-YES", "size": 100}'
# Python示例
import requests
import hmac
import hashlib
import json

payload = {"action": "BUY", "symbol": "TRUMP-YES", "size": 100}
secret = "your-webhook-secret"
signature = hmac.new(
    secret.encode(),
    json.dumps(payload).encode(),
    hashlib.sha256
).hexdigest()

requests.post(
    "https://your-domain.com/webhooks/trading-signals",
    json=payload,
    headers={"X-Webhook-Signature": f"sha256={signature}"}
)

操作类型

类型 描述
notify 发送通知到渠道
execute 执行交易操作
log 记录到数据库
forward 转发到另一个Webhook
custom 自定义函数

最佳实践

  1. 始终使用签名 — 验证Webhook真实性
  2. 模式验证 — 拒绝格式错误的负载
  3. 幂等性 — 处理重复传递
  4. 日志记录 — 保持负载历史用于调试
  5. 速率限制 — 防止洪水攻击
  6. 错误处理 — 返回适当的狀態码