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

建立單一組合商品，一次建立商品、規格與配方三張表。productCategoryId 為必填，規則與「商品」家族相同：必須是可指派的（子）分類，省略回傳 400 product_category_id_required，帶了但分類不存在、不可指派或屬於其他租戶一律回傳 400 invalid_product_category_id。components 為必填、至少 1 筆，省略或空陣列回傳 400 bundle_components_required。配方裡每個元件用 componentSkuId 或 componentSkuOuterSysCode 擇一指名，兩者都有值時以 componentSkuId 為準，兩者都沒給回傳 400 component_identifier_required；用代碼指名且對到超過 1 筆規格（outerSysCode 沒有唯一索引）回傳 400 component_sku_code_ambiguous，絕不會替你挑一筆。元件必須存在、屬於同一租戶，且必須是一般規格（不允許巢狀組合品）——找不到或跨租戶一律回傳 400 component_not_found，不區分兩者以避免洩漏元件序號屬於別的租戶，是組合品型別回傳 400 component_cannot_be_a_bundle。元件不可重複，回傳 400 component_duplicated；每組用量（quantity）必須為正數，超出可表示範圍或四捨五入到小數 4 位後不大於 0 都視為不合法，回傳 400 invalid_component_quantity。price、sellPrice 若有帶值必須介於 0 到 9999999.99，超出回傳 400 invalid_price；quantityPrecision 若有帶值必須介於 0 到 4，超出回傳 400 invalid_quantity_precision。outerSysCode 已對應到既有組合商品時改為更新該筆（冪等去重）；若對應到的是一筆一般商品，回傳 400 product_type_conflict，且絕不會改為新增——請改用商品專屬端點，或換一個代碼。status 不是可寫欄位：透過本端點建立的組合商品一律為 Active，之後的狀態變更只能由後台維護。三張表的寫入在單一交易內完成，中途任何一步失敗都會整筆回滾，不會留下配方對不上的半成品組合商品。

Reference: https://docs.orderupb2b.com/api-reference/bundles/create-bundle

## 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 排查步驟，請參閱「驗證與簽章」。

## Request

### Body (application/json)

This endpoint expects an object.

- `id` (long, optional, nullable) — 組合商品序號（商品序號）。帶 id 時一律視為更新該筆，不會再比對 outerSysCode；省略時改依 outerSysCode 判斷新增或更新。PUT /v1/bundles/\{id} 會忽略這裡的值，一律以路徑上的 id 為準。
- `outerSysCode` (string, optional, nullable) — ERP 端的組合商品代碼，用來與既有組合商品比對、去重。新增時省略視為空字串；更新時省略保留現有值。長度上限 50 字元，超過回傳 400 outer_sys_code_too_long。
- `name` (string, optional, nullable) — 組合商品名稱。新增時省略視為空字串；更新時省略保留現有值。長度上限 100 字元，超過回傳 400 name_too_long。
- `productCategoryId` (long, optional, nullable) — 商品分類序號，必須是可指派的（子）分類 id。新增時必填，省略回傳 400 product_category_id_required；帶了但分類不存在、不可指派或屬於其他租戶，回傳 400 invalid_product_category_id。更新時省略會保留目前的分類；若有帶值，會依相同規則重新驗證。
- `unit` (string, optional, nullable) — 商品單位。新增時省略視為空字串；更新時省略保留現有值。長度上限 50 字元，超過回傳 400 unit_too_long。
- `spec` (string, optional, nullable) — 規格內容。新增時省略視為空字串；更新時省略保留現有值。長度上限 100 字元，超過回傳 400 spec_too_long。
- `barcode` (string, optional, nullable) — 條碼。新增時省略視為空字串；更新時省略保留現有值。長度上限 50 字元，超過回傳 400 barcode_too_long。
- `warehouse` (string, optional, nullable) — 倉別。新增時省略視為空字串；更新時省略保留現有值。長度上限 50 字元，超過回傳 400 warehouse_too_long。
- `price` (double, optional, nullable) — 牌價。新增時省略視為 0；更新時省略保留現有值。必須介於 0 到 9999999.99，超出範圍回傳 400 invalid_price。
- `sellPrice` (double, optional, nullable) — 對外售價。範圍與省略規則同 price，超出範圍同樣回傳 400 invalid_price。
- `quantityPrecision` (integer, optional, nullable) — 數量精度（0 為整數，1 至 4 為小數位數）。新增時省略視為 0；更新時省略保留現有值。必須介於 0 到 4，超出範圍回傳 400 invalid_quantity_precision。
- `components` (list of object, optional, nullable) — 配方，至少 1 筆；建立時必填，省略或空陣列一律回傳 400 bundle_components_required（建立永遠會送出自己的配方陣列，省略在效果上等同空陣列）。更新時省略（null）即配方維持不變；帶值（包含空陣列）即配方整份替換，替換規則見更新端點的說明，替換整個失敗時完全不套用、原配方保留。
  - `componentSkuId` (long, optional, nullable) — 元件規格序號。與 componentSkuOuterSysCode 擇一必填，兩者都有值時以這個欄位為準，因為它精確、不需要反查。
  - `componentSkuOuterSysCode` (string, optional, nullable) — 元件規格的 ERP 代碼，componentSkuId 省略時才會用到，精確比對，不分大小寫、去除前後空白。對到超過 1 筆規格時整筆失敗並帶 component_sku_code_ambiguous，絕不會替你挑一筆；兩個識別欄位都沒給時失敗並帶 component_identifier_required。
  - `quantity` (double, optional) — 每組用量，必須為正數。超出可表示的範圍，或四捨五入到小數 4 位後不大於 0，都視為不合法，回傳 400 invalid_component_quantity。
  - `sort` (integer, optional) — 排序，數字越小越前面。

## Response

### 200

OK

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

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

### Example 1

**Request**

```json
{}
```

**Response**

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

**SDK Code**

```python
import requests

url = "https://api.example.com/v1/bundles"

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

	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/bundles")

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/bundles")
  .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/bundles', [
  'body' => '{}',
  'headers' => [
    'Content-Type' => 'application/json',
    'X-Signature' => '<apiKey>',
  ],
]);

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

```csharp
using RestSharp;

var client = new RestClient("https://api.example.com/v1/bundles");
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/bundles")! 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()
```

### Example 2

**Request**

```json
{}
```

**Response**

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

**SDK Code**

```python
import requests

url = "https://api.example.com/v1/bundles"

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

	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/bundles")

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/bundles")
  .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/bundles', [
  'body' => '{}',
  'headers' => [
    'Content-Type' => 'application/json',
    'X-Signature' => '<apiKey>',
  ],
]);

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

```csharp
using RestSharp;

var client = new RestClient("https://api.example.com/v1/bundles");
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/bundles")! 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()
```