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

# 更新客戶帳號

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

依 id 更新客戶帳號，部分合併——只送有異動的欄位，省略的欄位維持原值。省略 `password` 表示不改密碼；`email`、`phone` 帶空字串會清空。帳號（account）建立後不能修改。`status` 只接受 Active 或 Inactive，其他值回傳 400 invalid_status；帶入 `roleId` 時必須是呼叫端所屬租戶的角色，否則回傳 400 invalid_role_id。客戶找不到時回傳 404 company_not_found，帳號找不到（含屬於另一家客戶）時回傳 404 not_found。

改派角色會讓這個帳號在前台的登入階段立即失效，並**清空他的購物車**，與在後台改派角色相同；把 `status` 設為 Inactive 也會立即讓他登出。

⚠️ **每一家客戶至少要保留一個生效中的 Boss 帳號。** 前台有一整批功能只開放給 Boss 角色（例如管理同公司的帳號、查看全公司的訂單），後台為客戶代客下單也需要客戶有 Boss。若這個帳號是客戶目前唯一生效中的 Boss，把他改成其他角色、或把狀態設為 Inactive，會被拒絕並回傳 409 last_active_boss——請先把另一個帳號改為 Boss。本來就沒有生效中 Boss 的客戶不受這條限制。

Reference: https://docs.orderupb2b.com/api-規格/company-users/update-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。
- `userId` (long, required) — 要更新的客戶帳號序號。不存在、屬於其他租戶，或不屬於網址上的客戶時，一律回傳 404 not_found。

### Body (application/json)

This endpoint expects a CompanyUserUpdateRequest.

- `name` (string, optional, nullable) — 姓名。省略或只有空白時維持原值；長度上限 30 字元，超過回傳 name_too_long。
- `email` (string, optional, nullable) — 電子郵件。省略維持原值，帶空字串會清空；長度上限 100 字元，超過回傳 email_too_long。
- `phone` (string, optional, nullable) — 手機號碼。省略維持原值，帶空字串會清空；長度上限 100 字元，超過回傳 phone_too_long。
- `password` (string, optional, nullable) — 新密碼。省略或只有空白時不改密碼。
- `roleId` (long, optional, nullable) — 改派的角色序號，必須是呼叫端所屬租戶的角色，否則回傳 invalid_role_id。省略維持原角色。改派會讓這個帳號在前台立即登出並清空購物車；若他是客戶唯一生效中的 Boss，改成其他角色會回傳 409 last_active_boss。
- `status` (string, optional, nullable) — 帳號狀態，Active 或 Inactive（大小寫不敏感），其他值回傳 invalid_status。省略維持原狀態；設為 Inactive 會立即讓他在前台登出，若他是客戶唯一生效中的 Boss 則回傳 409 last_active_boss。

## Response

### 200

OK

- `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 字串，依代碼判斷失敗原因。

### 409 Conflict Error

Conflict

- `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/1"

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

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

print(response.json())
```

```javascript
const url = 'https://api.example.com/v1/companies/1/users/1';
const options = {
  method: 'PUT',
  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/1"

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

	req, _ := http.NewRequest("PUT", 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/1")

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

request = Net::HTTP::Put.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.put("https://api.example.com/v1/companies/1/users/1")
  .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('PUT', 'https://api.example.com/v1/companies/1/users/1', [
  '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/1");
var request = new RestRequest(Method.PUT);
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/1")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "PUT"
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()
```