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

一次寫入多筆客戶，逐筆各自新增、更新或去重，互不影響。送出空陣列或沒有 body 會在受理前被拒絕，回傳 400 empty_batch；已受理的請求一律回傳 HTTP 200，逐筆的處理結果放在回應 body 的 items 裡（見 BatchUpsertResult / BatchItemResult），單筆失敗不會讓其他筆一起失敗。每一筆的新增/更新/去重規則與單筆端點相同：帶 id 就更新該筆；不帶 id 但 outerSysCode 命中既有客戶就改為更新（冪等去重）；兩者都沒有則新增。更新一律是部分合併，只會覆蓋你送出的欄位。

Reference: https://docs.orderupb2b.com/api-reference/customers/batch-upsert-customers

## 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 a list of object.

- `list of object`
  - `id` (long, optional, nullable) — 客戶序號。帶 id 時一律視為更新該筆客戶，不會再比對 outerSysCode；省略時改依 outerSysCode 判斷新增或更新。PUT /v1/customers/\{id} 會忽略這裡的值，一律以路徑上的 id 為準。
  - `outerSysCode` (string, optional, nullable) — ERP 端的客戶代碼，用來與既有客戶比對、去重。新增時省略視為空字串；更新時省略保留現有值。長度上限 50 字元，超過回傳 400 outer_sys_code_too_long。
  - `name` (string, optional, nullable) — 企業名稱。新增時省略視為空字串；更新時省略保留現有值。長度上限 50 字元，超過回傳 400 name_too_long。
  - `shortName` (string, optional, nullable) — 企業簡稱。新增時省略視為空字串；更新時省略保留現有值。長度上限 20 字元，超過回傳 400 short_name_too_long。
  - `cellPhone` (string, optional, nullable) — 公司電話。新增時省略視為空字串；更新時省略保留現有值。長度上限 20 字元，超過回傳 400 cell_phone_too_long。
  - `shippingAddress` (string, optional, nullable) — 收貨地址。新增時省略視為空字串；更新時省略保留現有值。長度上限 50 字元，超過回傳 400 shipping_address_too_long。
  - `internalUserId` (long, optional, nullable) — 負責業務（內部使用者）的序號，選填。新增時省略會套用貴租戶設定的預設業務；若租戶未設定預設業務，新增會失敗。更新時省略保留現有值。

## Response

### 200

OK

- `items` (list of object, optional, nullable) — 逐筆的處理結果，順序與送出的陣列相同，一筆對一筆。
  - `index` (integer, optional) — 這一筆在原始批次陣列中的索引位置（從 0 起算），用來比對是哪一筆。
  - `status` (string, optional, nullable) — 這一筆的結果。created=新增、updated=更新、failed=失敗（原因見 errors）。
  - `id` (long, optional, nullable) — 新增或更新成功時，這一筆資料的 id；失敗時為 null。
  - `errors` (list of string, optional, nullable) — 失敗時的錯誤訊息，可能不只一則；成功時為空陣列。

## 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
{
  "items": [
    {
      "index": 1,
      "status": "string",
      "id": 1,
      "errors": [
        "string"
      ]
    }
  ]
}
```

**SDK Code**

```python
import requests

url = "https://api.example.com/v1/customers/batch"

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

	payload := strings.NewReader("[\n  {}\n]")

	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/customers/batch")

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 = "[\n  {}\n]"

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/customers/batch")
  .header("X-Signature", "<apiKey>")
  .header("Content-Type", "application/json")
  .body("[\n  {}\n]")
  .asString();
```

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

$client = new \GuzzleHttp\Client();

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

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

```csharp
using RestSharp;

var client = new RestClient("https://api.example.com/v1/customers/batch");
var request = new RestRequest(Method.POST);
request.AddHeader("X-Signature", "<apiKey>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "[\n  {}\n]", 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/customers/batch")! 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()
```