> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.orderupb2b.com/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.orderupb2b.com/_mcp/server.

# 建立客戶帳號

POST https://api.example.com/v1/companies/{id}/users
Content-Type: application/json

在指定的客戶底下建立一個前台登入帳號。`account`、`name`、`password`、`roleId` 為必填，未帶時分別回傳 400 account_required／name_required／password_required／role_id_required；`email`、`phone` 選填，`status` 省略時為 Active。

`account` 須為 3–50 個英文字母、數字或連字號（-），或是有效的電子郵件格式，否則回傳 400 invalid_account_format。帳號在**整個租戶內**不得重複（不分大小寫），不只是同一家客戶——前台登入只看租戶與帳號，所以另一家客戶已經用過的帳號一樣會回傳 400 account_already_used。`roleId` 必須是呼叫端所屬租戶的角色（見 GET /v1/company-user-roles），否則回傳 400 invalid_role_id。

與在後台建立帳號相同，新帳號會自動產生一組 8 位數字的邀請碼；若貴租戶設定新帳號首次登入不必變更密碼，這裡建立的帳號也比照辦理。這支端點一律視為新增，沒有去重更新：重送同一份資料會因帳號重複而被拒絕。

客戶不存在或屬於其他租戶時回傳 404 company_not_found。

Reference: https://docs.orderupb2b.com/api-規格/company-users/create-company-user

## Authentication

- `X-Signature` header (required) — 每個 /v1 請求都必須帶 `X-Client-Id`、`X-Timestamp`、`X-Nonce` 與 `X-Signature` 四個標頭。`X-Signature` 是以 client secret 對 canonical string 做 HMAC-SHA256 後的 Base64。 canonical string 的組成、可複製的簽章範例與 401 排查步驟，請參閱[「驗證與簽章」](/authentication)。

## Request

### Path parameters

- `id` (long, required) — 要建立帳號的客戶序號。查無此客戶或屬於其他租戶時，一律回傳 404 company_not_found。

### Body (application/json)

This endpoint expects a CompanyUserCreateRequest.

- `account` (string, optional, nullable) — 登入帳號，必填。3–50 個英文字母、數字或連字號（-），或有效的電子郵件格式，否則回傳 invalid_account_format；長度上限 50 字元，超過回傳 account_too_long。在整個租戶內不得重複（不分大小寫），重複回傳 account_already_used。建立後不能修改。
- `name` (string, optional, nullable) — 姓名，必填。長度上限 30 字元，超過回傳 name_too_long。
- `password` (string, optional, nullable) — 登入密碼，必填。以雜湊儲存，任何查詢都不會回傳。
- `email` (string, optional, nullable) — 電子郵件，選填。長度上限 100 字元，超過回傳 email_too_long。
- `phone` (string, optional, nullable) — 手機號碼，選填。長度上限 100 字元，超過回傳 phone_too_long。
- `roleId` (long, optional) — 角色序號，必填，必須是呼叫端所屬租戶的角色，透過 GET /v1/company-user-roles 取得。省略回傳 role_id_required；不存在或屬於其他租戶回傳 invalid_role_id。
- `status` (string, optional, nullable) — 帳號狀態，Active 或 Inactive（大小寫不敏感），省略時為 Active。其他值回傳 invalid_status。

## Response

### 201

Created

- `id` (long, optional) — 新增或更新成功後，該筆資料的 id。

## Errors

### 400 Bad Request Error

Bad Request

- `error` (string, optional, nullable) — 錯誤代碼，固定為 snake_case 字串，依代碼判斷失敗原因。

### 401 Unauthorized Error

Unauthorized

- `error` (string, optional, nullable) — 錯誤代碼，固定為 snake_case 字串，依代碼判斷失敗原因。

### 403 Forbidden Error

Forbidden

- `error` (string, optional, nullable) — 錯誤代碼，固定為 snake_case 字串，依代碼判斷失敗原因。

### 404 Not Found Error

Not Found

- `error` (string, optional, nullable) — 錯誤代碼，固定為 snake_case 字串，依代碼判斷失敗原因。

### 500 Internal Server Error

Internal Server Error

- `code` (string, optional, nullable) — 錯誤代碼字串。
- `message` (string, optional, nullable) — 對應的錯誤說明文字。

## Examples

**Request**

```json
{}
```

**Response**

```json
{
  "id": 1
}
```

**SDK Code**

```python
import requests

url = "https://api.example.com/v1/companies/1/users"

payload = {}
headers = {
    "X-Signature": "<apiKey>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript
const url = 'https://api.example.com/v1/companies/1/users';
const options = {
  method: 'POST',
  headers: {'X-Signature': '<apiKey>', 'Content-Type': 'application/json'},
  body: '{}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://api.example.com/v1/companies/1/users"

	payload := strings.NewReader("{}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("X-Signature", "<apiKey>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby
require 'uri'
require 'net/http'

url = URI("https://api.example.com/v1/companies/1/users")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["X-Signature"] = '<apiKey>'
request["Content-Type"] = 'application/json'
request.body = "{}"

response = http.request(request)
puts response.read_body
```

```java
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.example.com/v1/companies/1/users")
  .header("X-Signature", "<apiKey>")
  .header("Content-Type", "application/json")
  .body("{}")
  .asString();
```

```php
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.example.com/v1/companies/1/users', [
  'body' => '{}',
  'headers' => [
    'Content-Type' => 'application/json',
    'X-Signature' => '<apiKey>',
  ],
]);

echo $response->getBody();
```

```csharp
using RestSharp;

var client = new RestClient("https://api.example.com/v1/companies/1/users");
var request = new RestRequest(Method.POST);
request.AddHeader("X-Signature", "<apiKey>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let headers = [
  "X-Signature": "<apiKey>",
  "Content-Type": "application/json"
]
let parameters = [] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.example.com/v1/companies/1/users")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```