跳转到主要内容

概述

探索我们的演示应用程序和代码示例集合,以加速您与 KillB API 的集成。

示例应用程序

On-Ramp 演示

on-ramp 流程的完整实现(COP/MXN → USDC)。

功能

  • 用户创建和 KYC
  • 实时报价显示
  • PSE/SPEI 支付集成
  • 交易状态跟踪
  • Webhook 处理

代码示例

import { useState } from 'react';

function OnRampWidget() {
  const [quote, setQuote] = useState(null);
  const [amount, setAmount] = useState('');

  const getQuote = async () => {
    const response = await fetch('/api/v2/quotations', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${accessToken}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        fromCurrency: 'COP',
        toCurrency: 'USDC',
        amount: parseFloat(amount),
        amountIsToCurrency: false,
        cashInMethod: 'PSE',
        cashOutMethod: 'POLYGON'
      })
    });
    
    const data = await response.json();
    setQuote(data);
  };

  const createRamp = async () => {
    const response = await fetch('/api/v2/ramps', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${accessToken}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        quotationId: quote.id,
        userId: currentUser.id,
        accountId: walletAccount.id
      })
    });
    
    const ramp = await response.json();
    // Redirect to PSE payment URL
    window.location.href = ramp.paymentInfo[0].url;
  };

  return (
    <div>
      <input
        type="number"
        value={amount}
        onChange={(e) => setAmount(e.target.value)}
        placeholder="Amount in COP"
      />
      <button onClick={getQuote}>Get Quote</button>
      
      {quote && (
        <div>
          <p>You will receive: {quote.toAmount} USDC</p>
          <p>Rate: {quote.rate}</p>
          <button onClick={createRamp}>Continue to Payment</button>
        </div>
      )}
    </div>
  );
}

查看完整演示

在 GitHub 上查看完整的 on-ramp 演示应用程序

Off-Ramp 演示

将加密货币转换回本地法币。

功能

  • 钱包余额检查
  • 报价计算
  • 银行账户验证
  • 交易监控
  • 收据生成

代码示例

export default function OffRampPage() {
  const createOffRamp = async (formData) => {
    // Step 1: Get quote
    const quoteRes = await fetch('/api/v2/quotations', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        fromCurrency: 'USDC',
        toCurrency: 'COP',
        amount: formData.amount,
        amountIsToCurrency: false,
        cashInMethod: 'POLYGON',
        cashOutMethod: 'PSE'
      })
    });
    const quote = await quoteRes.json();

    // Step 2: Create ramp
    const rampRes = await fetch('/api/v2/ramps', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        quotationId: quote.id,
        userId: formData.userId,
        accountId: formData.bankAccountId
      })
    });
    const ramp = await rampRes.json();

    // Step 3: Show payment instructions
    return ramp;
  };

  return (
    <form onSubmit={(e) => {
      e.preventDefault();
      createOffRamp(formData);
    }}>
      {/* Form fields */}
    </form>
  );
}

储蓄演示

实现托管储蓄账户界面。

代码示例

// Create savings account
const createSavingsAccount = async (userId) => {
  const response = await fetch('/api/v2/savings', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      userId: userId,
      acceptedTermsAndConditions: true
    })
  });
  
  return await response.json();
};

// Get balance
const getBalance = async (savingsAccountId) => {
  const response = await fetch(
    `/api/v2/savings/${savingsAccountId}/balance`,
    {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    }
  );
  
  return await response.json();
};

// Get deposit instructions
const getDepositInstructions = async (savingsAccountId, type) => {
  const response = await fetch(
    `/api/v2/savings/${savingsAccountId}/deposit-instructions/${type}`,
    {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    }
  );
  
  return await response.json();
};

Webhook 监听器演示

处理来自 KillB 的实时 webhook 事件。

代码示例

const express = require('express');
const crypto = require('crypto');

const app = express();
app.use(express.json());

app.post('/webhooks/killb', (req, res) => {
  // Verify webhook signature
  const signature = req.headers['x-signature-sha256'];
  const payload = JSON.stringify(req.body);
  
  const expectedSignature = crypto
    .createHmac('sha256', process.env.WEBHOOK_SECRET)
    .update(payload)
    .digest('hex');
  
  if (signature !== expectedSignature) {
    return res.status(401).json({ error: 'Invalid signature' });
  }
  
  // Process webhook event
  const { event, data } = req.body;
  
  switch(event) {
    case 'ramp.completed':
      handleRampCompleted(data);
      break;
    case 'ramp.failed':
      handleRampFailed(data);
      break;
    case 'user.kyc_updated':
      handleKYCUpdate(data);
      break;
  }
  
  res.status(200).json({ received: true });
});

app.listen(3000);

了解更多

阅读完整的 webhook 安全指南

代码片段

用户管理

const createUser = async (userData) => {
  const response = await fetch('/api/v2/users', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      type: 'PERSON',
      externalId: userData.externalId,
      data: {
        firstName: userData.firstName,
        lastName: userData.lastName,
        email: userData.email,
        phone: userData.phone,
        dateOfBirth: userData.dateOfBirth,
        address: userData.address,
        document: userData.document
      }
    })
  });
  
  return await response.json();
};

账户创建

const createWalletAccount = async (userId, walletAddress) => {
  const response = await fetch('/api/v2/accounts', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      type: 'WALLET',
      userId: userId,
      externalId: `wallet-${userId}`,
      data: {
        firstName: 'John',
        lastName: 'Doe',
        email: '[email protected]',
        phone: '+573001234567',
        currency: 'USDC',
        network: 'POLYGON',
        address: walletAddress,
        countryCode: 'CO',
        document: {
          type: 'PASSPORT',
          number: 'AB123456',
          issuedCountryCode: 'CO'
        }
      }
    })
  });
  
  return await response.json();
};

Ramp 创建

const executeRamp = async (userId, accountId, amount, direction) => {
  try {
    // 1. Create quotation
    const quote = await fetch('/api/v2/quotations', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        fromCurrency: direction === 'ON' ? 'COP' : 'USDC',
        toCurrency: direction === 'ON' ? 'USDC' : 'COP',
        amount: amount,
        amountIsToCurrency: false,
        cashInMethod: direction === 'ON' ? 'PSE' : 'POLYGON',
        cashOutMethod: direction === 'ON' ? 'POLYGON' : 'PSE'
      })
    }).then(r => r.json());

    console.log('Quote:', quote);

    // 2. Create ramp
    const ramp = await fetch('/api/v2/ramps', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        quotationId: quote.id,
        userId: userId,
        accountId: accountId
      })
    }).then(r => r.json());

    console.log('Ramp:', ramp);
    
    return ramp;
  } catch (error) {
    console.error('Ramp creation failed:', error);
    throw error;
  }
};

在沙盒中测试

使用这些辅助函数来测试您的集成:

模拟现金入账

curl --request POST \
  --url https://teste-94u93qnn.uc.gateway.dev/api/v2/faker/cash-in \
  --header 'Authorization: Bearer YOUR_ACCESS_TOKEN' \
  --header 'Content-Type: application/json' \
  --data '{
    "rampId": "ramp-id-here"
  }'

模拟现金出账完成

curl --request POST \
  --url https://teste-94u93qnn.uc.gateway.dev/api/v2/faker/cash-out \
  --header 'Authorization: Bearer YOUR_ACCESS_TOKEN' \
  --header 'Content-Type: application/json' \
  --data '{
    "rampId": "ramp-id-here"
  }'
Faker 端点仅在沙盒环境中工作,用于测试目的。

集成清单

1

设置身份验证

实现登录和令牌刷新逻辑
2

创建用户管理

构建用户创建和 KYC 提交流程
3

实现账户创建

添加银行账户和钱包管理
4

构建报价 UI

向用户显示实时价格
5

处理 Ramp 流程

创建和监控 ramp 交易
6

设置 Webhooks

接收实时状态更新
7

添加错误处理

实现适当的错误处理和重试逻辑
8

彻底测试

使用沙盒环境进行端到端测试

其他资源

有演示应用要分享吗?通过 [email protected] 联系我们以展示它!