跳转到主要内容

分步设置

1

创建端点

构建 POST 端点以接收 webhooks
app.post('/webhooks/killb', async (req, res) => {
  // 处理 webhook
  res.status(200).json({ received: true });
});
2

验证签名

实现 HMAC 验证
import { createHash } from 'node:crypto';

const verifySignature = (payload, expectedSignature, secret) => {
  const signature = createHash('sha256')
    .update(`${JSON.stringify(req.body)}_${my_secret}`)
    .digest('hex');

  return signature === expectedSignature;
}
3

注册 Webhook

在 KillB 中配置
POST /api/v2/webhooks
{
  "url": "https://api.yourapp.com/webhooks/killb",
  "secret": "your-secret-key",
  "events": ["RAMP", "USER"]
}
4

测试

创建测试 ramp 并验证 webhook 接收

完整实现

import express from 'express';
import { createHash } from 'node:crypto';

const app = express();

app.use(express.json());

app.post('/webhooks/killb', async (req, res) => {
  try {
    // 1. 验证签名
    const signature = req.headers['x-signature-sha256'];
    
    const expectedSignature = createHash('sha256')
      .update(`${JSON.stringify(req.body)}_${process.env.WEBHOOK_SECRET}`)
      .digest('hex');
    
    if (signature !== expectedSignature) {
      console.error('Invalid signature');
      return res.status(401).json({ error: 'Invalid signature' });
    }
    
    // 2. 立即确认
    res.status(200).json({ received: true });
    
    // 3. 异步处理
    processWebhookAsync(req.body).catch(console.error);
    
  } catch (error) {
    console.error('Webhook error:', error);
    res.status(500).json({ error: 'Processing failed' });
  }
});

const processWebhookAsync = async (event) => {
  console.log('Processing event:', event.event);
  
  switch(event.event) {
    case 'ramp.completed':
      await handleRampCompleted(event.data);
      break;
    case 'ramp.failed':
      await handleRampFailed(event.data);
      break;
    case 'user.kyc_approved':
      await handleKYCApproved(event.data);
      break;
  }
};

app.listen(3000);

注册 Webhook

curl --request POST \
  --url https://teste-94u93qnn.uc.gateway.dev/api/v2/webhooks \
  --header 'Authorization: Bearer YOUR_ACCESS_TOKEN' \
  --header 'Content-Type: application/json' \
  --data '{
    "url": "https://api.yourapp.com/webhooks/killb",
    "secret": "your-secret-key-at-least-32-chars",
    "events": ["RAMP", "USER", "ACCOUNT"]
  }'

本地测试

使用 ngrok 进行本地测试:
# 启动本地服务器
npm start

# 通过 ngrok 暴露
ngrok http 3000

# 使用 ngrok URL
# https://abc123.ngrok.io/webhooks/killb

下一步