> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://developers.omicx.one/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://developers.omicx.one/_mcp/server.

# Tìm kiếm khách hàng

POST https://api.omicx.one/customers/search
Content-Type: application/json

Body rỗng trả về trang 1 của toàn bộ khách hàng trong phạm vi dữ liệu của agent. **Scope yêu cầu:** `customer:read`. Kết quả chỉ giới hạn trong phạm vi xem của agent gắn với key.

Reference: https://developers.omicx.one/customers/info/search-customers

## Request

### Headers

- `X-Api-Key` (string, required)

### Body (application/json)

This endpoint expects a CustomerSearchRequest.

- `filter` (map from string to any, optional) — Tương ứng `CustomerFilter` của web app — ví dụ `keyword`, `lifecycleStages[]`, `statuses[]`, `createdFrom`/`createdTo` (epoch millis), `assignedAgentId`, `tagIds[]`, `groupIds[]`, `conditions[]` (`{field, operator, value|values}`) trong đó `field` là **fieldCode** của thuộc tính (hoặc `phone`/ `email`), không bao giờ là slot lưu trữ thô. Lọc theo thuộc tính mức **Che dữ liệu**/**Bảo mật** cần agent có quyền tương ứng, nếu không sẽ trả `403`.
- `sort` (list of CustomerSearchRequestSortItems, optional)
- `pagination` (CustomerSearchRequestPagination, optional)

## Response

### 200

Một trang kết quả khách hàng.

- `items` (list of CustomerResponse, optional)
- `page` (integer, optional)
- `size` (integer, optional)
- `totalItems` (long, optional)
- `totalPages` (integer, optional)

## Errors

### 400 Bad Request Error

Envelope tìm kiếm không hợp lệ.

- `error` (ErrorResponseError, optional)

### 401 Unauthorized Error

`API_KEY_REQUIRED` hoặc `API_KEY_INVALID`.

- `error` (ErrorResponseError, optional)

### 403 Forbidden Error

`INSUFFICIENT_SCOPE` (key thiếu scope) · `API_KEY_PRINCIPAL_REQUIRED` (legacy key chưa gắn agent — tạo key mới) · `API_KEY_PRINCIPAL_NOT_ELIGIBLE` (agent của key đã bị vô hiệu hoá, rời tenant, hoặc không còn thuộc tenant) · `FEATURE_ACCESS_DENIED` (quyền hiện tại của agent không cho phép thao tác này trên Khách hàng) · `CUSTOMER_ACCESS_DENIED` (ngoài phạm vi dữ liệu của agent).

- `error` (ErrorResponseError, optional)

### 422 Unprocessable Entity Error

`CUSTOMER_ATTRIBUTE_UNKNOWN` — filter theo fieldCode không tồn tại (hoặc slot lưu trữ thô), hoặc dùng toán tử/giá trị không được hỗ trợ.

- `error` (ErrorResponseError, optional)

### 429 Too Many Requests Error

`RATE_LIMIT_EXCEEDED`.

- `error` (ErrorResponseError, optional)

### 502 Bad Gateway Error

`CUSTOMER_SERVICE_UNAVAILABLE` — customer-service timeout/lỗi 5xx, kèm `Retry-After: 5`. Platform không tự động thử lại.

- `error` (ErrorResponseError, optional)

### 503 Service Unavailable Error

`AGENT_SERVICE_UNAVAILABLE` / `PERMISSION_SNAPSHOT_UNAVAILABLE` / `SCOPE_RESOLUTION_FAILED` — không xác thực được quyền hạn, hệ thống từ chối theo hướng an toàn (fail closed).

- `error` (ErrorResponseError, optional)

## Types

### CustomerSearchRequestSortItems

- `field` (string, optional) — Cột cố định (`createdAt`, `fullName`...) hoặc fieldCode của thuộc tính.
- `direction` (enum, optional)
  - Allowed values: `ASC`, `DESC`

### CustomerSearchRequestPagination

- `page` (integer, optional, default: 1)
- `size` (integer, optional, default: 20) — Giá trị lớn hơn 100 sẽ bị giới hạn về 100.

### CustomerResponse

Dữ liệu khách hàng theo góc nhìn đối tác (từ `GET /customers` và các item trong `POST /customers/search`). Giá trị mức **Che dữ liệu** bị che, thuộc tính mức **Bảo mật** bị lược bỏ khỏi response, trừ khi agent gắn với key hiện đang có quyền xem dữ liệu bảo mật tương ứng; đọc được giá trị đầy đủ sẽ được ghi audit log. `customerId` là định danh **duy nhất** trên public API — không có id nội bộ, `tenantId`, cờ xoá, kênh ghi (`*Via`), `description`, hay `lastAiSummary*` nào được trả về.

- `customerId` (string, optional)
- `lifecycleStages` (string, optional)
- `status` (string, optional)
- `fullName` (string, optional)
- `phone` (string, optional) — Có thể đã bị che.
- `email` (string, optional) — Có thể đã bị che.
- `gender` (string, optional)
- `dateOfBirth` (long, optional) — Epoch millis.
- `customerSource` (string, optional)
- `avatarUrl` (string, optional)
- `refId` (string, optional)
- `attributes` (map from string to any, optional) — Khoá theo fieldCode.
- `aiAttributes` (map from string to any, optional) — Câu trả lời của Agent Bot (AI Insight), có ở cả `GET /customers` và search. Khoá theo `id` của card trong [Danh sách tiêu chí AI Insights](/customer-config/attributes/get-customer-ai-insight-config) — là mã kỹ năng (card `SYSTEM`) hoặc id của card (card `CUSTOM` không có mã). Chỉ trả về card đang được cấu hình; card chưa có câu trả lời sẽ không xuất hiện. Giá trị theo `valueType`: `TEXT`/`SINGLE_SELECT` → chuỗi, `STRING_LIST` → mảng chuỗi, `RATING` → số, `BOOLEAN` → boolean.
- `socialIds` (map from string to string, optional) — Chỉ có ở `GET /customers`, không có khi search.
- `assignedAgentId` (string, optional)
- `relatedAgentIds` (list of string, optional)
- `relatedCustomerUids` (list of string, optional)
- `tagIds` (list of string, optional)
- `groupIds` (list of string, optional)
- `workflowStates` (list of CustomerResponseWorkflowStatesItems, optional) — Các quy trình chăm sóc đang gắn với khách hàng.
- `createdBy` (string, optional) — id của agent tạo khách hàng — `public-service` khi tạo qua API này.
- `createdAt` (long, optional)
- `lastModifiedBy` (string, optional) — id của agent sửa khách hàng gần nhất.
- `lastModifiedAt` (long, optional)
- `lastLifecycleStageTime` (long, optional) — Thời điểm chuyển sang giai đoạn hành trình hiện tại.
- `lastInteractionAt` (long, optional, nullable)

### ErrorResponseError

- `code` (string, optional) — Nhóm lỗi (dạng máy đọc được), ổn định theo từng HTTP status.
- `subCode` (string, optional, nullable) — Mã cụ thể, ổn định — dùng để phân nhánh xử lý / dịch i18n. Hãy xử lý logic dựa trên `subCode`, không dựa vào chuỗi `message`.
- `message` (string, optional) — Mô tả cho con người đọc (dùng để debug), không nên dịch trực tiếp.
- `timestamp` (long, optional) — Epoch millis.
- `path` (string, optional) — Đường dẫn request đầy đủ.
- `traceId` (string, optional, nullable) — Mã tương quan request, có khi lỗi đi qua bộ xử lý lỗi chung.
- `details` (list of ErrorResponseErrorDetailsItems, optional, nullable) — Chỉ xuất hiện khi `code` là `VALIDATION_ERROR` — danh sách lỗi theo từng trường.

### CustomerResponseWorkflowStatesItems

- `workflowId` (string, optional)
- `statusId` (string, optional)
- `joinedAt` (long, optional)
- `statusChangedAt` (long, optional)

### ErrorResponseErrorDetailsItems

- `field` (string, optional)
- `message` (string, optional)
- `rejectedValue` (any, optional, nullable)

## Examples

**Request**

```json
{
  "filter": {
    "keyword": "Nguyễn",
    "lifecycleStages": [
      "qualifiedLead"
    ]
  },
  "sort": [
    {
      "field": "createdAt",
      "direction": "DESC"
    }
  ],
  "pagination": {
    "page": 1,
    "size": 20
  }
}
```

**Response**

```json
{
  "items": [
    {
      "customerId": "string",
      "lifecycleStages": "string",
      "status": "string",
      "fullName": "string",
      "phone": "string",
      "email": "string",
      "gender": "string",
      "dateOfBirth": 1,
      "customerSource": "string",
      "avatarUrl": "string",
      "refId": "string",
      "attributes": {
        "cap_bac": "VIP",
        "diem_tich_luy": 120
      },
      "aiAttributes": {
        "customer_sentiment": "Tích cực",
        "nhu_cau": "Quan tâm gói Premium"
      },
      "socialIds": {
        "zalo": "0912345678"
      },
      "assignedAgentId": "string",
      "relatedAgentIds": [
        "string"
      ],
      "relatedCustomerUids": [
        "string"
      ],
      "tagIds": [
        "string"
      ],
      "groupIds": [
        "string"
      ],
      "workflowStates": [
        {
          "workflowId": "string",
          "statusId": "string",
          "joinedAt": 1,
          "statusChangedAt": 1
        }
      ],
      "createdBy": "string",
      "createdAt": 1,
      "lastModifiedBy": "string",
      "lastModifiedAt": 1,
      "lastLifecycleStageTime": 1,
      "lastInteractionAt": 1
    }
  ],
  "page": 1,
  "size": 1,
  "totalItems": 1,
  "totalPages": 1
}
```

**SDK Code**

```python Tìm khách hàng theo từ khoá và giai đoạn
import requests

url = "https://api.omicx.one/customers/search"

payload = {
    "filter": {
        "keyword": "Nguyễn",
        "lifecycleStages": ["qualifiedLead"]
    },
    "sort": [
        {
            "field": "createdAt",
            "direction": "DESC"
        }
    ],
    "pagination": {
        "page": 1,
        "size": 20
    }
}
headers = {
    "X-Api-Key": "omx_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript Tìm khách hàng theo từ khoá và giai đoạn
const url = 'https://api.omicx.one/customers/search';
const options = {
  method: 'POST',
  headers: {
    'X-Api-Key': 'omx_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
    'Content-Type': 'application/json'
  },
  body: '{"filter":{"keyword":"Nguyễn","lifecycleStages":["qualifiedLead"]},"sort":[{"field":"createdAt","direction":"DESC"}],"pagination":{"page":1,"size":20}}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go Tìm khách hàng theo từ khoá và giai đoạn
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://api.omicx.one/customers/search"

	payload := strings.NewReader("{\n  \"filter\": {\n    \"keyword\": \"Nguyễn\",\n    \"lifecycleStages\": [\n      \"qualifiedLead\"\n    ]\n  },\n  \"sort\": [\n    {\n      \"field\": \"createdAt\",\n      \"direction\": \"DESC\"\n    }\n  ],\n  \"pagination\": {\n    \"page\": 1,\n    \"size\": 20\n  }\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("X-Api-Key", "omx_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
	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 Tìm khách hàng theo từ khoá và giai đoạn
require 'uri'
require 'net/http'

url = URI("https://api.omicx.one/customers/search")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["X-Api-Key"] = 'omx_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"filter\": {\n    \"keyword\": \"Nguyễn\",\n    \"lifecycleStages\": [\n      \"qualifiedLead\"\n    ]\n  },\n  \"sort\": [\n    {\n      \"field\": \"createdAt\",\n      \"direction\": \"DESC\"\n    }\n  ],\n  \"pagination\": {\n    \"page\": 1,\n    \"size\": 20\n  }\n}"

response = http.request(request)
puts response.read_body
```

```java Tìm khách hàng theo từ khoá và giai đoạn
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.omicx.one/customers/search")
  .header("X-Api-Key", "omx_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
  .header("Content-Type", "application/json")
  .body("{\n  \"filter\": {\n    \"keyword\": \"Nguyễn\",\n    \"lifecycleStages\": [\n      \"qualifiedLead\"\n    ]\n  },\n  \"sort\": [\n    {\n      \"field\": \"createdAt\",\n      \"direction\": \"DESC\"\n    }\n  ],\n  \"pagination\": {\n    \"page\": 1,\n    \"size\": 20\n  }\n}")
  .asString();
```

```php Tìm khách hàng theo từ khoá và giai đoạn
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.omicx.one/customers/search', [
  'body' => '{
  "filter": {
    "keyword": "Nguyễn",
    "lifecycleStages": [
      "qualifiedLead"
    ]
  },
  "sort": [
    {
      "field": "createdAt",
      "direction": "DESC"
    }
  ],
  "pagination": {
    "page": 1,
    "size": 20
  }
}',
  'headers' => [
    'Content-Type' => 'application/json',
    'X-Api-Key' => 'omx_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
  ],
]);

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

```csharp Tìm khách hàng theo từ khoá và giai đoạn
using RestSharp;

var client = new RestClient("https://api.omicx.one/customers/search");
var request = new RestRequest(Method.POST);
request.AddHeader("X-Api-Key", "omx_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"filter\": {\n    \"keyword\": \"Nguyễn\",\n    \"lifecycleStages\": [\n      \"qualifiedLead\"\n    ]\n  },\n  \"sort\": [\n    {\n      \"field\": \"createdAt\",\n      \"direction\": \"DESC\"\n    }\n  ],\n  \"pagination\": {\n    \"page\": 1,\n    \"size\": 20\n  }\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift Tìm khách hàng theo từ khoá và giai đoạn
import Foundation

let headers = [
  "X-Api-Key": "omx_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  "Content-Type": "application/json"
]
let parameters = [
  "filter": [
    "keyword": "Nguyễn",
    "lifecycleStages": ["qualifiedLead"]
  ],
  "sort": [
    [
      "field": "createdAt",
      "direction": "DESC"
    ]
  ],
  "pagination": [
    "page": 1,
    "size": 20
  ]
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.omicx.one/customers/search")! 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()
```