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

# 创建授权用户

将现有的 Fluz 用户作为授权用户添加到调用方的账户，并分配一个或多个访问角色。此 mutation 不会创建用户——它会通过电子邮箱或手机号查找现有的 Fluz 用户，然后在调用方的账户上创建角色分配（或使用新角色重新激活先前为 `DECLINED`/`INACTIVE` 的分配）。

目标账户始终根据调用方的凭证解析——Bearer 令牌使用令牌所属的账户；Basic（API key）调用方使用应用配置的运营商账户。无法通过此端点以你不拥有的账户为目标。

🔒 受限访问

此 mutation 需要 `MANAGE_SUBUSERS` 范围。它同时支持 Bearer（用户访问令牌）和 Basic（`<API_KEY>`）认证。`OWNER` 角色无法通过此端点分配。

```graphql theme={null}
mutation AddAuthorizedUser(
  $email: String
  $phone: String
  $roles: [UACRoleType!]!
  $status: UACRoleStatusType
  $sendInvite: Boolean
) {
  addAuthorizedUser(
    email: $email
    phone: $phone
    roles: $roles
    status: $status
    sendInvite: $sendInvite
  ) {
    success
    authUserId
    roles
    status
    pendingActionId
    error {
      code
      message
    }
  }
}
```

<br />

### 参数

| Parameter  | Type              | Required | Description                                                                                                |
| :--------- | :---------------- | :------- | :--------------------------------------------------------------------------------------------------------- |
| email      | String            | No\*     | 要授权的现有 Fluz 用户的电子邮箱地址。\*`email` 与 `phone` 至少需要提供一个。                                                        |
| phone      | String            | No\*     | 要授权的现有 Fluz 用户的手机号码。\*`email` 与 `phone` 至少需要提供一个。                                                          |
| roles      | \[UACRoleType!]!  | Yes      | 要分配的一个或多个角色。允许值：`ADMIN`、`MANAGER`、`SPENDER`、`VIEWER`。不允许使用 `OWNER`。                                        |
| status     | UACRoleStatusType | No       | 角色分配的初始状态。默认为 `PENDING`。将其设置为 `ACTIVE` 可跳过待处理状态并立即激活分配（无需接受）。允许值：`PENDING`、`ACTIVE`、`INACTIVE`、`DECLINED`。 |
| sendInvite | Boolean           | No       | 是否向用户发送角色分配邀请。默认为 `true`。设置为 `false` 可在不发送邀请的情况下创建分配，使邀请成为可选项。                                             |

<br />

### 响应

#### 成功响应

```json theme={null}
{
  "data": {
    "addAuthorizedUser": {
      "success": true,
      "authUserId": "8b2c1e0a-7d4f-4a9b-9c2d-1f3e4a5b6c7d",
      "roles": ["MANAGER", "VIEWER"],
      "status": "PENDING",
      "pendingActionId": "2f7c1a3b-9e44-4d2a-8a91-c1b2d3e4f5a6",
      "error": null
    }
  }
}
```

<br />

### 响应字段

| Field             | Type                | Description                                                                      |
| :---------------- | :------------------ | :------------------------------------------------------------------------------- |
| `success`         | Boolean             | 若成功创建或重新激活角色分配则为 `true`。                                                         |
| `authUserId`      | UUID                | 授权用户 ID（UAC 角色分配 ID）。在调用 `removeAuthorizedUser` 或从 `authorizedUsers` 结果中过滤时使用此值。 |
| `roles`           | \[UACRoleType]      | 用户在此账户上被分配的角色。                                                                   |
| `status`          | UACRoleStatusType   | 角色分配的状态：`PENDING`、`ACTIVE`、`INACTIVE` 或 `DECLINED`。                              |
| `pendingActionId` | UUID                | 邀请对应的待处理操作 ID（当分配需要用户接受时返回）。                                                     |
| `error`           | AuthorizedUserError | 当 `success` 为 false 时，包含 `code` 和 `message` 的错误对象。                               |

<br />

> 注意：此 mutation 会在响应数据中返回错误，而不是作为 GraphQL errors 返回。请务必检查 `success` 字段，并在 `success` 为 false 时处理 `error` 对象。

### 示例请求

```curl theme={null}
curl -X POST https://transactional-graph.staging.fluzapp.com/api/v1/graphql \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer <your_access_token>" \
  -d '{
  "query": "mutation AddAuthorizedUser($email: String, $phone: String, $roles: [UACRoleType!]!) { addAuthorizedUser(email: $email, phone: $phone, roles: $roles) { success authUserId roles status pendingActionId error { code message } } }",
  "variables": {
    "email": "teammate@example.com",
    "roles": ["MANAGER", "VIEWER"]
  }
}'
```

```typescript theme={null}
const response = await fetch('https://transactional-graph.staging.fluzapp.com/api/v1/graphql', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${accessToken}`
  },
  body: JSON.stringify({
    query: `
      mutation AddAuthorizedUser(
        $email: String
        $phone: String
        $roles: [UACRoleType!]!
      ) {
        addAuthorizedUser(
          email: $email
          phone: $phone
          roles: $roles
        ) {
          success
          authUserId
          roles
          status
          pendingActionId
          error {
            code
            message
          }
        }
      }
    `,
    variables: {
      email: "teammate@example.com",
      roles: ["MANAGER", "VIEWER"]
    }
  })
});

const data = await response.json();

if (data.data.addAuthorizedUser.success) {
  console.log('Authorized user added:', data.data.addAuthorizedUser);
} else {
  console.error('Add authorized user failed:', data.data.addAuthorizedUser.error);
}
```

<br />

#### 跳过待处理状态并抑制邀请

若要在不发送邀请的情况下立即激活授权用户，请将 `status` 设为 `ACTIVE`，并将 `sendInvite` 设为 `false`。此时分配会以 `ACTIVE` 状态创建，不会返回 `pendingActionId`，也不会向用户发送邀请。

```curl theme={null}
curl -X POST https://transactional-graph.staging.fluzapp.com/api/v1/graphql \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer <your_access_token>" \
  -d '{
  "query": "mutation AddAuthorizedUser($email: String, $phone: String, $roles: [UACRoleType!]!, $status: UACRoleStatusType, $sendInvite: Boolean) { addAuthorizedUser(email: $email, phone: $phone, roles: $roles, status: $status, sendInvite: $sendInvite) { success authUserId roles status pendingActionId error { code message } } }",
  "variables": {
    "email": "teammate@example.com",
    "roles": ["MANAGER", "VIEWER"],
    "status": "ACTIVE",
    "sendInvite": false
  }
}'
```

### 错误代码

| Code        | Message                                                                | Description                                                                                                                                 |
| :---------- | :--------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------ |
| `ARG-0002`  | Missing required arguments                                             | 未提供 `email` 或 `phone`，或 `roles` 为空。至少需要一个标识符以及至少一个角色。                                                                                       |
| `ARG-0001`  | Invalid arguments received                                             | `roles` 中包含一个或多个不被允许的值（例如 `OWNER`），或者 `status` 不是 `PENDING`、`ACTIVE`、`INACTIVE`、`DECLINED` 之一。角色请使用 `ADMIN`、`MANAGER`、`SPENDER` 或 `VIEWER`。 |
| `AUTH-0008` | Invalid user access                                                    | 无法从访问令牌或 API key 解析调用方，或使用 Basic 认证的应用未配置运营商账户。请验证你的认证凭证。                                                                                   |
| `AUTH-0031` | The requested scopes must be granted by the user first.                | 令牌缺少管理授权用户所需的 `MANAGE_SUBUSERS` 范围。                                                                                                         |
| `AUTH-0034` | No Fluz user found with the provided email or phone number.            | 没有与提供的 `email` 或 `phone` 匹配的现有 Fluz 用户。目标用户必须已拥有 Fluz 账户。                                                                                   |
| `AUTH-0035` | This user already has an active role assignment on this account.       | 该用户已在调用方的账户上被授权。若需重新分配角色，请先使用 `removeAuthorizedUser`。                                                                                       |
| `AUTH-0037` | Unable to manage authorized user. Please try again or contact support. | 创建角色分配时发生一般性故障。请重试或联系支持。                                                                                                                    |

<br />
