> 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/company-groups/{id}
Content-Type: application/json

⚠️ **調整子客戶清單會立即改變資料可見範圍**：新加入的客戶，總部的 Boss 角色使用者隨即看得到它的資料；被移出的客戶，其所屬群組歸零，總部的人隨即看不到。

依 id 更新客戶總部，成功回傳 200 與群組的 id。更新是部分合併，只能改 `name` 與子客戶清單：

  - `name`：省略保留現有名稱；有給時規則同新增（去掉前後空白後 1 至 50 字元）
  - `subCompanyIds` 與 `subCompanyCodes` 都省略：子客戶清單不動
  - 兩者任一有給（包含空陣列）：兩者的聯集會**取代**整份子客戶清單。只給 `subCompanyIds: []` 代表移除所有子客戶，群組只剩總部


**總部客戶不能更換。** 請求帶了 `parentCompanyId` 或 `parentCompanyCode` 會被忽略；要換總部請刪除群組後重建。

成員的指定方式與新增相同（`id` 或 `outerSysCode`，代碼為大小寫敏感的完全比對）。群組不存在或屬於其他租戶時回傳 404 not_found；成員規則不符時整筆拒絕、不寫入任何資料，錯誤字串見「錯誤碼」。同一租戶的群組寫入請一次送一筆，也不要與該租戶的客戶寫入（`POST`／`PUT /v1/companies`、批次）同時進行。

Reference: https://docs.orderupb2b.com/api-規格/company-groups/update-company-group

## 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 not_found。

### Body (application/json)

This endpoint expects a CompanyGroupUpdateRequest.

- `name` (string, optional, nullable) — 群組名稱。省略保留現有名稱；有給時規則同新增，去掉前後空白後 1 至 50 字元，空白回傳 400 name_required，超過回傳 400 name_too_long。
- `subCompanyIds` (list of long, optional, nullable) — 子客戶的序號清單。`subCompanyIds` 與 `subCompanyCodes` 都省略時，子客戶清單不動；任一有給（包含空陣列）時，兩者的聯集會取代整份子客戶清單。被移出的客戶其所屬群組歸零，總部的 Boss 角色使用者隨即看不到它們的資料。
- `subCompanyCodes` (list of string, optional, nullable) — 子客戶的 ERP 端代碼清單，大小寫敏感的完全比對，取代規則同 `subCompanyIds`。對不到客戶回傳 400 company_not_found；對到兩家以上回傳 400 company_code_ambiguous。

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

### 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/company-groups/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/company-groups/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/company-groups/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/company-groups/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/company-groups/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/company-groups/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/company-groups/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/company-groups/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()
```