> ## Documentation Index
> Fetch the complete documentation index at: https://docs.killb.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 演示应用和示例

> 示例实现和集成示例

## 概述

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

## 示例应用程序

<CardGroup cols={2}>
  <Card title="On-Ramp 演示" icon="arrow-up" href="#on-ramp-demo">
    从法币到加密货币的完整 on-ramp 流程
  </Card>

  <Card title="Off-Ramp 演示" icon="arrow-down" href="#off-ramp-demo">
    将加密货币转换回本地法币
  </Card>

  <Card title="储蓄仪表板" icon="chart-line" href="#savings-demo">
    托管储蓄账户界面
  </Card>

  <Card title="Webhook 监听器" icon="bell" href="#webhook-demo">
    处理实时事件通知
  </Card>
</CardGroup>

## On-Ramp 演示

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

### 功能

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

### 代码示例

<CodeGroup>
  ```javascript React theme={null}
  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>
    );
  }
  ```

  ```python Flask theme={null}
  from flask import Flask, request, jsonify
  import requests

  app = Flask(__name__)

  @app.route('/create-onramp', methods=['POST'])
  def create_onramp():
      data = request.json
      
      # Get quotation
      quote_response = requests.post(
          'https://sandbox.killb.app/api/v2/quotations',
          headers={
              'Authorization': f'Bearer {access_token}',
              'Content-Type': 'application/json'
          },
          json={
              'fromCurrency': 'COP',
              'toCurrency': 'USDC',
              'amount': data['amount'],
              'amountIsToCurrency': False,
              'cashInMethod': 'PSE',
              'cashOutMethod': 'POLYGON'
          }
      )
      quote = quote_response.json()
      
      # Create ramp
      ramp_response = requests.post(
          'https://sandbox.killb.app/api/v2/ramps',
          headers={
              'Authorization': f'Bearer {access_token}',
              'Content-Type': 'application/json'
          },
          json={
              'quotationId': quote['id'],
              'userId': data['userId'],
              'accountId': data['accountId']
          }
      )
      ramp = ramp_response.json()
      
      return jsonify({
          'rampId': ramp['id'],
          'paymentUrl': ramp['paymentInfo'][0]['url'],
          'status': ramp['status']
      })

  if __name__ == '__main__':
      app.run(debug=True)
  ```
</CodeGroup>

<Card title="查看完整演示" icon="github" href="https://github.com/Kill-B/onramp-demo">
  在 GitHub 上查看完整的 on-ramp 演示应用程序
</Card>

## Off-Ramp 演示

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

### 功能

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

### 代码示例

<CodeGroup>
  ```javascript Next.js theme={null}
  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>
    );
  }
  ```

  ```python Django theme={null}
  from django.http import JsonResponse
  from django.views.decorators.http import require_http_methods
  import requests

  @require_http_methods(["POST"])
  def create_offramp(request):
      data = json.loads(request.body)
      base_url = 'https://sandbox.killb.app'
      token = request.headers.get('Authorization')
      
      # Create quotation
      quote_response = requests.post(
          f'{base_url}/api/v2/quotations',
          headers={'Authorization': token},
          json={
              'fromCurrency': 'USDC',
              'toCurrency': 'COP',
              'amount': data['amount'],
              'amountIsToCurrency': False,
              'cashInMethod': 'POLYGON',
              'cashOutMethod': 'PSE'
          }
      )
      quote = quote_response.json()
      
      # Create ramp
      ramp_response = requests.post(
          f'{base_url}/api/v2/ramps',
          headers={'Authorization': token},
          json={
              'quotationId': quote['id'],
              'userId': data['userId'],
              'accountId': data['bankAccountId']
          }
      )
      ramp = ramp_response.json()
      
      return JsonResponse(ramp)
  ```
</CodeGroup>

## 储蓄演示

实现托管储蓄账户界面。

### 代码示例

```javascript theme={null}
// 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 事件。

### 代码示例

<CodeGroup>
  ```javascript Express.js theme={null}
  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);
  ```

  ```python FastAPI theme={null}
  from fastapi import FastAPI, Header, HTTPException, Request
  import hmac
  import hashlib

  app = FastAPI()

  @app.post("/webhooks/killb")
  async def webhook_handler(
      request: Request,
      x_webhook_signature: str = Header(None)
  ):
      # Get raw body
      body = await request.body()
      
      # Verify signature
      expected_signature = hmac.new(
          WEBHOOK_SECRET.encode(),
          body,
          hashlib.sha256
      ).hexdigest()
      
      if x_webhook_signature != expected_signature:
          raise HTTPException(status_code=401, detail="Invalid signature")
      
      # Process event
      data = await request.json()
      event = data.get('event')
      
      if event == 'ramp.completed':
          handle_ramp_completed(data['data'])
      elif event == 'ramp.failed':
          handle_ramp_failed(data['data'])
      elif event == 'user.kyc_updated':
          handle_kyc_update(data['data'])
      
      return {"received": True}
  ```
</CodeGroup>

<Card title="了解更多" icon="webhook" href="/zh/guides/webhooks/security">
  阅读完整的 webhook 安全指南
</Card>

## 代码片段

### 用户管理

<CodeGroup>
  ```javascript Create User theme={null}
  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();
  };
  ```

  ```python Create User theme={null}
  def create_user(user_data, access_token):
      response = requests.post(
          'https://sandbox.killb.app/api/v2/users',
          headers={
              'Authorization': f'Bearer {access_token}',
              'Content-Type': 'application/json'
          },
          json={
              'type': 'PERSON',
              'externalId': user_data['external_id'],
              'data': {
                  'firstName': user_data['first_name'],
                  'lastName': user_data['last_name'],
                  'email': user_data['email'],
                  'phone': user_data['phone'],
                  'dateOfBirth': user_data['date_of_birth'],
                  'address': user_data['address'],
                  'document': user_data['document']
              }
          }
      )
      return response.json()
  ```
</CodeGroup>

### 账户创建

<CodeGroup>
  ```javascript Create Wallet Account theme={null}
  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: 'john@example.com',
          phone: '+573001234567',
          currency: 'USDC',
          network: 'POLYGON',
          address: walletAddress,
          countryCode: 'CO',
          document: {
            type: 'PASSPORT',
            number: 'AB123456',
            issuedCountryCode: 'CO'
          }
        }
      })
    });
    
    return await response.json();
  };
  ```

  ```python Create Bank Account theme={null}
  def create_bank_account(user_id, bank_details, access_token):
      response = requests.post(
          'https://sandbox.killb.app/api/v2/accounts',
          headers={
              'Authorization': f'Bearer {access_token}',
              'Content-Type': 'application/json'
          },
          json={
              'type': 'PSE',
              'userId': user_id,
              'externalId': f'bank-{user_id}',
              'data': {
                  'firstName': bank_details['first_name'],
                  'lastName': bank_details['last_name'],
                  'email': bank_details['email'],
                  'phone': bank_details['phone'],
                  'accountNumber': bank_details['account_number'],
                  'bankCode': bank_details['bank_code'],
                  'type': 'savings',
                  'countryCode': 'CO',
                  'document': bank_details['document']
              }
          }
      )
      return response.json()
  ```
</CodeGroup>

### Ramp 创建

<CodeGroup>
  ```javascript Complete Ramp Flow theme={null}
  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;
    }
  };
  ```

  ```python Complete Ramp Flow theme={null}
  def execute_ramp(user_id, account_id, amount, direction, access_token):
      base_url = 'https://sandbox.killb.app'
      headers = {
          'Authorization': f'Bearer {access_token}',
          'Content-Type': 'application/json'
      }
      
      # 1. Create quotation
      quote_payload = {
          'fromCurrency': 'COP' if direction == 'ON' else 'USDC',
          'toCurrency': 'USDC' if direction == 'ON' else 'COP',
          'amount': amount,
          'amountIsToCurrency': False,
          'cashInMethod': 'PSE' if direction == 'ON' else 'POLYGON',
          'cashOutMethod': 'POLYGON' if direction == 'ON' else 'PSE'
      }
      
      quote_response = requests.post(
          f'{base_url}/api/v2/quotations',
          headers=headers,
          json=quote_payload
      )
      quote = quote_response.json()
      print(f'Quote created: {quote}')
      
      # 2. Create ramp
      ramp_payload = {
          'quotationId': quote['id'],
          'userId': user_id,
          'accountId': account_id
      }
      
      ramp_response = requests.post(
          f'{base_url}/api/v2/ramps',
          headers=headers,
          json=ramp_payload
      )
      ramp = ramp_response.json()
      print(f'Ramp created: {ramp}')
      
      return ramp
  ```
</CodeGroup>

## 在沙盒中测试

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

### 模拟现金入账

```bash theme={null}
curl --request POST \
  --url https://sandbox.killb.app/api/v2/faker/cash-in \
  --header 'Authorization: Bearer YOUR_ACCESS_TOKEN' \
  --header 'Content-Type: application/json' \
  --data '{
    "rampId": "ramp-id-here"
  }'
```

### 模拟现金出账完成

```bash theme={null}
curl --request POST \
  --url https://sandbox.killb.app/api/v2/faker/cash-out \
  --header 'Authorization: Bearer YOUR_ACCESS_TOKEN' \
  --header 'Content-Type: application/json' \
  --data '{
    "rampId": "ramp-id-here"
  }'
```

<Warning>
  Faker 端点仅在**沙盒环境**中工作，用于测试目的。
</Warning>

## 集成清单

<Steps>
  <Step title="设置身份验证">
    实现登录和令牌刷新逻辑
  </Step>

  <Step title="创建用户管理">
    构建用户创建和 KYC 提交流程
  </Step>

  <Step title="实现账户创建">
    添加银行账户和钱包管理
  </Step>

  <Step title="构建报价 UI">
    向用户显示实时价格
  </Step>

  <Step title="处理 Ramp 流程">
    创建和监控 ramp 交易
  </Step>

  <Step title="设置 Webhooks">
    接收实时状态更新
  </Step>

  <Step title="添加错误处理">
    实现适当的错误处理和重试逻辑
  </Step>

  <Step title="彻底测试">
    使用沙盒环境进行端到端测试
  </Step>
</Steps>

## 其他资源

<CardGroup cols={2}>
  <Card title="API 参考" icon="book" href="/api-reference/introduction">
    完整的 API 文档
  </Card>

  <Card title="Webhooks 指南" icon="bell" href="/zh/guides/webhooks/overview">
    设置实时通知
  </Card>

  <Card title="错误处理" icon="triangle-exclamation" href="/zh/resources/error-handling">
    错误管理的最佳实践
  </Card>

  <Card title="最佳实践" icon="star" href="/zh/resources/best-practices">
    生产就绪集成的提示
  </Card>
</CardGroup>

<Info>
  有演示应用要分享吗？通过 [developers@killb.com](mailto:developers@killb.com) 联系我们以展示它！
</Info>
