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

批次覆蓋多筆規格的在庫數，一次寫入多筆，逐筆結果互不影響。quantity 是絕對的在庫數，不是增減量——每一筆送出的都是「更新後庫存應該是多少」，不是要加減的差量；把差量當成這個欄位送出，會直接把在庫數蓋成錯誤的值，這是使用這支端點最容易出錯、也最需要注意的地方。送出空陣列或沒有 body 會在受理前被拒絕，回傳 400 empty_batch；已受理的請求一律回傳 HTTP 200，逐筆的處理結果放在回應 body 的 items 裡（見 SkuStockBatchResult / SkuStockBatchItemResult），單筆失敗不會讓其他筆一起失敗。逐筆狀態是小寫的 ok 或 failed，與規格主檔批次端點（POST /v1/skus/batch）的 created／updated／failed 不同，兩者不可混用；failed 時 error 帶失敗原因。

Reference: https://docs.orderupb2b.com/api-reference/sku-stock/batch-update-sku-stock

## 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`
  - `skuId` (long, optional) — 要設定庫存的規格序號，必須是既有規格；不存在或屬於其他租戶時，這一筆會在逐筆結果中回報 failed，不影響其他筆。
  - `quantity` (double, optional) — 更新後的絕對在庫數，不是增減量。這是這支端點最容易出錯的地方：送出的必須是「應該是多少」，不能是「要加或減多少」，把差量當成這個欄位送出會直接把在庫數蓋成錯誤的值。

## Response

### 200

OK

- `items` (list of object, optional, nullable) — 逐筆的處理結果，順序與送出的陣列相同，一筆對一筆。
  - `skuId` (long, optional) — 這一筆對應的規格序號。
  - `status` (string, optional, nullable) — 這一筆的結果，只有兩種小寫值：ok（成功）或 failed（失敗，原因見 error）。這裡沒有 created／updated 的區分，因為庫存的寫入永遠是覆蓋，不是新增。
  - `error` (string, optional, nullable) — 失敗時的錯誤說明；成功時為 null 或空字串。

## 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": [
    {
      "skuId": 1,
      "status": "string",
      "error": "string"
    }
  ]
}
```

**SDK Code**

```python
import requests

url = "https://api.example.com/v1/skus/stock/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/skus/stock/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/skus/stock/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/skus/stock/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/skus/stock/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/skus/stock/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/skus/stock/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/skus/stock/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()
```