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

⚠️ **新增群組後，總部客戶的 Boss 角色使用者就看得到所有成員（子客戶）的資料。** 請確認成員清單無誤再送出。

建立一個客戶總部，成功回傳 201 與新群組的 id。總部客戶本身也會成為這個群組的成員。

`name` 必填，去掉前後空白後 1 至 50 字元。總部以 `parentCompanyId` 或 `parentCompanyCode`（客戶的 `outerSysCode`）指定，至少要給一個，兩者都給時以 `parentCompanyId` 為準。子客戶以 `subCompanyIds` 和／或 `subCompanyCodes` 指定，兩者取聯集；重複的值、小於等於 0 的 id、與總部相同的 id 與空白的代碼會被略過。

代碼是大小寫敏感的完全比對，範圍限呼叫端所屬租戶的有效客戶：對不到任何客戶回傳 400 company_not_found，對到兩家以上回傳 400 company_code_ambiguous，OrderUp 絕不會替你挑一家。為避免被用來探測其他租戶的客戶序號，錯誤不會指出是哪一個 id 或代碼有問題。

任何一項規則不符就整筆拒絕、不寫入任何資料。依序檢查：名稱必填（name_required）且不超過 50 字元（name_too_long）；總部必須指定（parent_company_required）；總部與子客戶必須是有效客戶（company_not_found、company_code_ambiguous）；總部不可已是另一個群組的總部（parent_already_headquarters）；總部與子客戶都不可已屬於另一個群組（company_already_in_group）；子客戶不可是另一個群組的總部（sub_company_is_headquarters）。

同一租戶的群組寫入請一次送一筆。資料庫只保證「同一個總部只能有一個群組」，兩個同時送出的請求可能把同一家子客戶分別加進兩個群組。也不要與該租戶的客戶寫入（`POST`／`PUT /v1/companies`、批次）同時進行。

Reference: https://docs.orderupb2b.com/api-規格/company-groups/create-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

### Body (application/json)

This endpoint expects a CompanyGroupCreateRequest.

- `name` (string, optional, nullable) — 群組名稱，必填。去掉前後空白後必須有內容，上限 50 字元；空白回傳 400 name_required，超過回傳 400 name_too_long。
- `parentCompanyId` (long, optional, nullable) — 總部客戶的序號。與 `parentCompanyCode` 都給時以這個為準。兩者都沒給回傳 400 parent_company_required。
- `parentCompanyCode` (string, optional, nullable) — 總部客戶的 ERP 端代碼（`outerSysCode`），大小寫敏感的完全比對。`parentCompanyId` 有值時忽略這個欄位。對不到客戶回傳 400 company_not_found；對到兩家以上回傳 400 company_code_ambiguous，不會替你挑一家。
- `subCompanyIds` (list of long, optional, nullable) — 子客戶的序號清單，選填。與 `subCompanyCodes` 取聯集；重複的值、小於等於 0 的值與總部自己的序號會被略過。每個 id 都必須是呼叫端所屬租戶的有效客戶，否則回傳 400 company_not_found。
- `subCompanyCodes` (list of string, optional, nullable) — 子客戶的 ERP 端代碼清單，選填。與 `subCompanyIds` 取聯集；空白的代碼會被略過，其餘做大小寫敏感的完全比對。對不到客戶回傳 400 company_not_found；對到兩家以上回傳 400 company_code_ambiguous。

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

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

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/company-groups';
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/company-groups"

	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/company-groups")

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/company-groups")
  .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/company-groups', [
  '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");
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/company-groups")! 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()
```