> ## 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.

# 管理用户

> 查询、更新和删除用户资料

## 查询用户

### 获取所有用户

```bash theme={null}
GET /api/v2/users?type=PERSON
```

**过滤参数：**

* `type` - PERSON 或 COMPANY
* `id` - 特定用户 ID
* `externalId` - 您系统的用户 ID
* `firstName`, `lastName` - 姓名搜索
* `email` - 电子邮件搜索
* `customerId` - 按客户过滤
* `limit`, `page` - 分页

**示例：**

```bash theme={null}
curl --request GET \
  --url 'https://sandbox.killb.app/api/v2/users?type=PERSON&limit=10&page=1' \
  --header 'Authorization: Bearer YOUR_ACCESS_TOKEN'
```

**响应：**

```json theme={null}
{
  "users": [
    {
      "id": "user-1",
      "type": "PERSON",
      "status": "ACTIVE",
      "accessLevel": "L2",
      "data": { /* 用户数据 */ }
    }
  ],
  "totalPage": 5
}
```

### 按 ID 获取用户

```bash theme={null}
GET /api/v2/users/{userId}
```

```javascript theme={null}
const getUser = async (userId) => {
  const response = await fetch(
    `https://sandbox.killb.app/api/v2/users/${userId}`,
    {
      headers: {
        'Authorization': `Bearer ${accessToken}`
      }
    }
  );
  
  return await response.json();
};
```

### 按外部 ID 查找

```bash theme={null}
GET /api/v2/users?externalId=user-12345
```

<Tip>
  使用 `externalId` 通过您的内部用户 ID 快速查找用户，而无需到处存储 KillB 的用户 ID。
</Tip>

## 更新用户

```bash theme={null}
PATCH /api/v2/users/{userId}
```

创建后更新用户信息：

<CodeGroup>
  ```json 更新个人 theme={null}
  {
    "type": "PERSON",
    "data": {
      "email": "newemail@example.com",
      "phone": "+573009876543",
      "address": {
        "street1": "New Street 456",
        "city": "Medellín",
        "state": "Antioquia",
        "zipCode": "050001",
        "countryCode": "CO"
      }
    }
  }
  ```

  ```javascript Node.js theme={null}
  const updateUser = async (userId, updates) => {
    const response = await fetch(
      `https://sandbox.killb.app/api/v2/users/${userId}`,
      {
        method: 'PATCH',
        headers: {
          'Authorization': `Bearer ${accessToken}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(updates)
      }
    );
    
    return await response.json();
  };

  // 更新电子邮件和电话
  await updateUser(userId, {
    type: 'PERSON',
    data: {
      email: 'newemail@example.com',
      phone: '+573009876543'
    }
  });
  ```

  ```python Python theme={null}
  def update_user(user_id, updates, access_token):
      response = requests.patch(
          f'https://sandbox.killb.app/api/v2/users/{user_id}',
          headers={
              'Authorization': f'Bearer {access_token}',
              'Content-Type': 'application/json'
          },
          json=updates
      )
      return response.json()
  ```
</CodeGroup>

**可更新字段：**

* 电子邮件
* 电话号码
* 地址
* 就业信息
* 投资资料
* KYC 资料

<Warning>
  更改某些字段（如文档号码）可能会触发重新验证，并暂时将状态设置为 PENDING。
</Warning>

## 删除用户

```bash theme={null}
DELETE /api/v2/users/{userId}
```

```javascript theme={null}
const deleteUser = async (userId) => {
  const response = await fetch(
    `https://sandbox.killb.app/api/v2/users/${userId}`,
    {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${accessToken}`
      }
    }
  );
  
  if (response.ok) {
    console.log('用户已成功删除');
  }
};
```

<Warning>
  用户删除是**软删除**。用户数据为合规目的而保留，但标记为不活动。具有待处理 ramps 的用户无法删除。
</Warning>

## 用户状态管理

监控和处理不同的用户状态：

```javascript theme={null}
const handleUserStatus = (user) => {
  switch(user.status) {
    case 'ACTIVE':
      // 用户可以交易
      return { canTransact: true, message: '准备交易' };
      
    case 'PENDING':
      // KYC 审核中
      return {
        canTransact: false,
        message: 'KYC 验证进行中',
        action: `在 ${user.complianceUrl} 完成验证`
      };
      
    case 'REJECTED':
      // KYC 被拒绝
      return {
        canTransact: false,
        message: '验证失败',
        reason: user.note,
        action: '请重新提交文档'
      };
      
    default:
      return { canTransact: false };
  }
};
```

## 批量操作

### 获取多个用户

```javascript theme={null}
const getUsersByExternalIds = async (externalIds) => {
  const users = await Promise.all(
    externalIds.map(externalId =>
      fetch(`/api/v2/users?externalId=${externalId}`, {
        headers: { 'Authorization': `Bearer ${token}` }
      }).then(r => r.json())
    )
  );
  
  return users.flat(2); // 展平嵌套数组
};
```

### 批量用户创建

```javascript theme={null}
const createMultipleUsers = async (usersData) => {
  const results = {
    successful: [],
    failed: []
  };
  
  for (const userData of usersData) {
    try {
      const user = await createUser(userData);
      results.successful.push(user);
    } catch (error) {
      results.failed.push({
        externalId: userData.externalId,
        error: error.message
      });
    }
  }
  
  return results;
};
```

## 同步用户数据

保持您的系统和 KillB 之间的用户数据同步：

```javascript theme={null}
const syncUser = async (localUserId) => {
  // 从数据库获取用户
  const localUser = await db.users.findById(localUserId);
  
  if (!localUser.killbUserId) {
    // 在 KillB 中创建
    const killbUser = await createUser(localUser);
    await db.users.update(localUserId, {
      killbUserId: killbUser.id
    });
    return killbUser;
  }
  
  // 从 KillB 获取当前状态
  const killbUser = await getUser(localUser.killbUserId);
  
  // 更新本地数据库
  await db.users.update(localUserId, {
    kycStatus: killbUser.status,
    kycLevel: killbUser.accessLevel
  });
  
  return killbUser;
};
```

## Webhook 集成

使用 webhooks 保持更新：

```javascript theme={null}
app.post('/webhooks/killb', (req, res) => {
  const { event, data } = req.body;
  
  if (event === 'user.updated') {
    // 更新本地数据库
    db.users.updateByKillbId(data.id, {
      kycStatus: data.status,
      kycLevel: data.accessLevel,
      updatedAt: new Date()
    });
  }
  
  res.status(200).json({ received: true });
});
```

## 最佳实践

<AccordionGroup>
  <Accordion title="使用外部 ID" icon="link">
    创建用户时始终提供 `externalId`：

    ```javascript theme={null}
    {
      "externalId": yourSystemUserId,
      "data": { /* 用户信息 */ }
    }
    ```

    这允许轻松查找，而无需到处存储 KillB ID。
  </Accordion>

  <Accordion title="缓存用户数据" icon="database">
    在本地存储频繁访问的数据：

    ```javascript theme={null}
    const getUserWithCache = async (userId) => {
      const cached = await cache.get(`user:${userId}`);
      if (cached) return cached;
      
      const user = await getUser(userId);
      await cache.set(`user:${userId}`, user, 3600); // 1 小时
      return user;
    };
    ```
  </Accordion>

  <Accordion title="优雅处理更新" icon="rotate">
    并非所有字段都可以更新。处理错误：

    ```javascript theme={null}
    try {
      await updateUser(userId, updates);
    } catch (error) {
      if (error.code === 'USER.0006') {
        // 字段不可更新
        console.log('无法更新此字段');
      }
    }
    ```
  </Accordion>
</AccordionGroup>

## 下一步

<CardGroup cols={2}>
  <Card title="创建账户" icon="wallet" href="/zh/guides/accounts/overview">
    为用户添加银行账户和钱包
  </Card>

  <Card title="开始交易" icon="arrow-right-arrow-left" href="/zh/guides/ramps/overview">
    开始处理 ramp 交易
  </Card>
</CardGroup>
