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

# 创建用户

> 创建和管理用户的分步指南

## 概览

在用户执行 ramp 交易之前，必须在 KillB 中注册并提供适当的 KYC 信息。本指南涵盖创建个人（PERSON）和企业（COMPANY）用户。

<Info>
  用户只有在入驻状态为 `ACTIVE` 时才能进行操作。如果用户是 `PENDING`，请将其引导到 `complianceUrl` 完成验证。如果是 `REJECTED`，则需要重新提交更正后的信息。
</Info>

## 先决条件

* 来自 `/api/v2/auth/login` 的有效访问令牌
* 要提交的用户信息
* 政府身份证详情

## 创建个人用户

### 基本示例

```bash theme={null}
POST /api/v2/users
```

<CodeGroup>
  ```json 请求 theme={null}
  {
    "type": "PERSON",
    "externalId": "user-12345",
    "data": {
      "firstName": "Juan",
      "lastName": "García",
      "email": "juan.garcia@example.com",
      "phone": "+573001234567",
      "dateOfBirth": "1990-05-15",
      "address": {
        "street1": "Calle 123 #45-67",
        "city": "Bogotá",
        "state": "Cundinamarca",
        "zipCode": "110111",
        "countryCode": "CO"
      },
      "document": {
        "type": "NUIP",
        "number": "1234567890",
        "issuedCountryCode": "CO"
      }
    }
  }
  ```

  ```json 响应 theme={null}
  {
    "id": "4d23aa52-1b40-4584-a8ea-58aba6099c5c",
    "status": "ACTIVE",
    "customerId": "8ffce092-b97a-48bd-9efa-24c66ac7fe13",
    "type": "PERSON",
    "complianceUrl": "https://kyc.killb.com/verify/user-id",
    "externalId": "user-12345",
    "active": true,
    "createdAt": "2024-01-15T10:30:00.000Z",
    "updatedAt": "2024-01-15T10:30:00.000Z"
  }
  ```
</CodeGroup>

### 必需字段

| 字段            | 类型     | 描述               | 示例                                            |
| ------------- | ------ | ---------------- | --------------------------------------------- |
| `firstName`   | string | 名字               | "Juan"                                        |
| `lastName`    | string | 姓氏               | "García"                                      |
| `email`       | string | 电子邮件地址           | "[juan@example.com](mailto:juan@example.com)" |
| `phone`       | string | 带国家代码的电话         | "+573001234567"                               |
| `dateOfBirth` | string | YYYY-MM-DD 格式的日期 | "1990-05-15"                                  |
| `address`     | object | 物理地址             | 见下文                                           |
| `document`    | object | 政府身份证            | 见下文                                           |

### 地址对象

```json theme={null}
{
  "street1": "Calle 123 #45-67",
  "street2": "Apt 301",
  "city": "Bogotá",
  "state": "Cundinamarca",
  "zipCode": "110111",
  "countryCode": "CO"
}
```

<Tip>
  `street2` 是可选的。用于公寓号码、建筑物名称等。
</Tip>

### 文档对象

为用户所在国家选择适当的文档类型：

<Tabs>
  <Tab title="哥伦比亚">
    ```json theme={null}
    {
      "type": "NUIP",
      "number": "1234567890",
      "issuedCountryCode": "CO"
    }
    ```

    **支持的类型：**

    * `NUIP` - Número Único de Identificación Personal
    * `PASSPORT` - 护照
    * `DRIVER_LICENSE` - 驾照
  </Tab>

  <Tab title="墨西哥">
    ```json theme={null}
    {
      "type": "RFC",
      "number": "GACJ900515ABC",
      "issuedCountryCode": "MX"
    }
    ```

    **INE/IFE 特定：**

    ```json theme={null}
    {
      "type": "INE",
      "number": "1234567890123",
      "issuedCountryCode": "MX",
      "expeditionDate": "2020-01-15",
      "cic": "123",
      "identificadorCiudadano": "ABC123"
    }
    ```

    **支持的类型：**

    * `RFC` - 税号
    * `CURP` - 人口登记
    * `INE` - 选举身份证（需要额外字段）
    * `IFE` - 旧选举身份证
    * `PASSPORT`
  </Tab>

  <Tab title="美国">
    ```json theme={null}
    {
      "type": "SSN",
      "number": "123-45-6789",
      "issuedCountryCode": "US"
    }
    ```

    **支持的类型：**

    * `SSN` - 社会保障号
    * `PASSPORT` - 护照
    * `DRIVER_LICENSE` - 驾照
  </Tab>

  <Tab title="其他国家">
    ```json theme={null}
    {
      "type": "PASSPORT",
      "number": "AB1234567",
      "issuedCountryCode": "BR",
      "expeditionDate": "2020-01-15"
    }
    ```

    **支持的类型：**

    * `PASSPORT` - 国际护照
    * `DNI` - 国民身份证
    * `DUI` - 唯一身份证件
    * `CPF` - 巴西税号
  </Tab>
</Tabs>

## 创建企业用户

对于商业实体：

```json theme={null}
{
  "type": "COMPANY",
  "externalId": "company-456",
  "data": {
    "companyName": "Acme Technologies SAS",
    "tradeName": "Acme Tech",
    "registeredNumber": "900123456",
    "legalStructure": "LLC",
    "establishedOn": "2015-03-20",
    "phone": "+573001234567",
    "email": "business@acmetech.com",
    "address": {
      "street1": "Carrera 7 #123-45",
      "city": "Bogotá",
      "state": "Cundinamarca",
      "zipCode": "110111",
      "countryCode": "CO"
    },
    "document": {
      "type": "NIT",
      "number": "900123456-1",
      "issuedCountryCode": "CO"
    },
    "mainOwnerUser": "owner-user-id",
    "ownerUsers": ["owner-1-id", "owner-2-id"]
  }
}
```

### 企业特定字段

| 字段                 | 必需 | 描述                      |
| ------------------ | -- | ----------------------- |
| `companyName`      | ✅  | 法定注册名称                  |
| `tradeName`        | ❌  | 经营名称                    |
| `registeredNumber` | ❌  | 商业注册号码                  |
| `legalStructure`   | ❌  | LLC, C\_CORP, S\_CORP 等 |
| `establishedOn`    | ❌  | 公司成立日期                  |
| `mainOwnerUser`    | ❌  | 主要所有者用户 ID              |
| `ownerUsers`       | ❌  | 所有者用户 ID 数组             |
| `naics`            | ❌  | 行业分类代码                  |

<Note>
  公司所有者必须首先创建为 PERSON 用户，然后在公司资料中引用。
</Note>

## 可选增强字段

### 投资资料

为更高的 KYC 级别提供：

```json theme={null}
{
  "investmentProfile": {
    "primarySourceOfFunds": "EMPLOYMENT",
    "primarySourceOfFundsDescription": "软件工程薪资",
    "totalAssets": "TEN_TO_100K",
    "usdValueOfFiat": "TEN_TO_100K",
    "monthlyDeposits": "UPTO_5",
    "monthlyWithdrawals": "UPTO_5",
    "monthlyInvestmentDeposit": "ONE_TO_100K",
    "monthlyInvestmentWithdrawal": "UPTO_1K"
  }
}
```

**资金来源选项：**

* `EMPLOYMENT` - 薪资/工资
* `SAVINGS` - 个人储蓄
* `INVESTMENT` - 投资回报
* `COMPANY` - 商业收入
* `REAL_ESTATE` - 房地产收入
* `OTHER` - 其他来源

### KYC 资料

反洗钱信息：

```json theme={null}
{
  "kycProfile": {
    "fundsSendReceiveJurisdictions": ["CO", "US", "MX"],
    "engageInActivities": ["NONE"]
  }
}
```

## 完整代码示例

<CodeGroup>
  ```javascript Node.js theme={null}
  const createUser = async (userData) => {
    const response = await fetch('https://sandbox.killb.app/api/v2/users', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${accessToken}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        type: 'PERSON',
        externalId: userData.id,
        data: {
          firstName: userData.firstName,
          lastName: userData.lastName,
          email: userData.email,
          phone: userData.phone,
          dateOfBirth: userData.dateOfBirth,
          address: {
            street1: userData.address.street,
            city: userData.address.city,
            state: userData.address.state,
            zipCode: userData.address.zipCode,
            countryCode: userData.address.country
          },
          document: {
            type: userData.document.type,
            number: userData.document.number,
            issuedCountryCode: userData.document.country
          }
        }
      })
    });
    
    if (!response.ok) {
      const error = await response.json();
      throw new Error(`用户创建失败: ${error.message}`);
    }
    
    const user = await response.json();
    
    // 在数据库中存储用户 ID
    await db.users.update(userData.id, {
      killbUserId: user.id,
      kycStatus: user.status
    });
    
    return user;
  };
  ```

  ```python Python theme={null}
  def create_user(user_data, access_token):
      """在 KillB 中创建具有 KYC 信息的用户"""
      
      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['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': {
                      'street1': user_data['address']['street'],
                      'city': user_data['address']['city'],
                      'state': user_data['address']['state'],
                      'zipCode': user_data['address']['zip_code'],
                      'countryCode': user_data['address']['country']
                  },
                  'document': {
                      'type': user_data['document']['type'],
                      'number': user_data['document']['number'],
                      'issuedCountryCode': user_data['document']['country']
                  }
              }
          }
      )
      
      if response.status_code != 201:
          raise Exception(f"用户创建失败: {response.json()}")
      
      user = response.json()
      
      # 存储在数据库中
      db.users.update(
          user_data['id'],
          killb_user_id=user['id'],
          kyc_status=user['status']
      )
      
      return user
  ```
</CodeGroup>

## 验证

提交前验证数据：

```javascript theme={null}
const validateUserData = (data) => {
  const errors = [];
  
  // 电子邮件格式
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(data.email)) {
    errors.push('电子邮件格式无效');
  }
  
  // 电话格式（E.164）
  if (!/^\+[1-9]\d{10,14}$/.test(data.phone)) {
    errors.push('电话必须采用格式: +[国家代码][号码]');
  }
  
  // 出生日期（18 岁以上）
  const dob = new Date(data.dateOfBirth);
  const age = (Date.now() - dob.getTime()) / (365.25 * 24 * 60 * 60 * 1000);
  if (age < 18) {
    errors.push('用户必须年满 18 岁');
  }
  
  // 文档号码格式
  if (data.document.type === 'NUIP' && !/^\d{10}$/.test(data.document.number)) {
    errors.push('NUIP 必须是 10 位数字');
  }
  
  return errors;
};
```

## 错误处理

常见的用户创建错误：

| 错误代码        | 描述      | 解决方案                |
| ----------- | ------- | ------------------- |
| `USER.0001` | 用户已存在   | 使用现有用户 ID           |
| `USER.0002` | 无效文档    | 检查文档格式              |
| `USER.0003` | 电子邮件已注册 | 使用不同的电子邮件           |
| `USER.0004` | 无效电话格式  | 使用 E.164 格式（+57...） |
| `USER.0005` | 未成年用户   | 用户必须年满 18 岁         |

## 创建后的下一步

<Steps>
  <Step title="存储用户 ID">
    在数据库中保存返回的 `id`，映射到您的 `externalId`
  </Step>

  <Step title="检查 KYC 状态">
    监控 `status` 字段
  </Step>

  <Step title="开始/继续验证">
    如果 `status` 是 `PENDING`，将用户重定向到 `complianceUrl` 以提交所需的信息和文档
  </Step>

  <Step title="创建账户">
    为此用户添加银行账户或钱包
  </Step>
</Steps>

<CardGroup cols={2}>
  <Card title="上传文档" icon="upload" href="/zh/guides/users/upload-documents">
    提交身份证图像和证明文档
  </Card>

  <Card title="管理用户" icon="users-gear" href="/zh/guides/users/manage-users">
    查询、更新和删除用户
  </Card>

  <Card title="API 参考" icon="code" href="/api-reference/endpoint/users-create">
    完整的用户 API 文档
  </Card>
</CardGroup>
