> ## Documentation Index
> Fetch the complete documentation index at: https://docs.unibee.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Export data with an API key

> Create asynchronous export tasks, poll their status, and download CSV or XLSX files with a UniBee merchant API key.

## Overview

Use the merchant Task APIs when an export may contain more records than a normal list response. UniBee creates the export asynchronously, processes all result pages internally, and exposes the finished file through an authenticated download URL.

The workflow uses these endpoints:

| Step | Method and endpoint                      | Purpose                                                      |
| ---- | ---------------------------------------- | ------------------------------------------------------------ |
| 1    | `POST /merchant/task/export_column_list` | Optional. Discover the columns available for an export type. |
| 2    | `POST /merchant/task/new_export`         | Create an asynchronous export task.                          |
| 3    | `GET` or `POST /merchant/task/list`      | Poll the task until it succeeds or fails.                    |
| 4    | `GET /export/{taskId}`                   | Download the completed file from the task's `downloadUrl`.   |

All four requests must use the same merchant API key.

## Authorization and hosts

Send the merchant API key as a Bearer token:

```http theme={null}
Authorization: Bearer YOUR_API_KEY
```

| Environment | Base URL                         |
| ----------- | -------------------------------- |
| Production  | `https://api.unibee.dev`         |
| Sandbox     | `https://api-sandbox.unibee.top` |

API-key export tasks are isolated from Admin Portal member tasks. An API key can list and download only API-created tasks for its merchant; it cannot access a member's export tasks or another merchant's data.

## Complete export workflow

### 1. Get available columns (optional)

Call this endpoint when you want to let users choose columns or need the exact accepted values for `exportColumns`:

```bash theme={null}
curl -X POST "https://api.unibee.dev/merchant/task/export_column_list" \
  -H "Authorization: Bearer $UNIBEE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "task": "SubscriptionExport"
  }'
```

The response includes:

* `columns`: values accepted by `exportColumns`.
* `columnHeaders`: default display header for each column.
* `columnComments`: additional column descriptions when available.
* `groupColumns`: columns grouped by subject.

Omit `exportColumns` when creating a task to export every available column.

### 2. Create an export task

```bash theme={null}
curl -X POST "https://api.unibee.dev/merchant/task/new_export" \
  -H "Authorization: Bearer $UNIBEE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "task": "SubscriptionExport",
    "payload": {
      "status": [2],
      "currency": "USD",
      "createTimeStart": 1767225600,
      "createTimeEnd": 1769904000,
      "timeZone": "Asia/Shanghai"
    },
    "exportColumns": [
      "subscriptionId",
      "email",
      "status",
      "planName",
      "createTime"
    ],
    "format": "csv"
  }'
```

| Field           | Type      | Required | Description                                                                          |
| --------------- | --------- | -------- | ------------------------------------------------------------------------------------ |
| `task`          | string    | Yes      | Export type. Use one of the nine public task names listed below.                     |
| `payload`       | object    | No       | Filters for the selected export. Use `{}` or omit it to export all matching records. |
| `exportColumns` | string\[] | No       | Columns returned by `export_column_list`. Omit to export all columns.                |
| `format`        | string    | No       | `xlsx` or `csv`. Defaults to `xlsx`.                                                 |

Do not put `page` or `count` in `payload`. The export service reads all pages internally.

<Note>
  `new_export` confirms that the task was accepted but does not return a task ID. Poll `task/list` and identify the newly created item by its `taskName`, `payload`, and `createTime`. If the same API key creates identical exports concurrently, serialize those requests or compare the task IDs returned before and after creation.
</Note>

### 3. Poll task status

```bash theme={null}
curl -X GET "https://api.unibee.dev/merchant/task/list?page=0&count=20" \
  -H "Authorization: Bearer $UNIBEE_API_KEY"
```

Each item in `data.downloads` contains the task details.

| Field           | Description                                                |
| --------------- | ---------------------------------------------------------- |
| `id`            | Task ID.                                                   |
| `taskName`      | Export type, such as `SubscriptionExport`.                 |
| `payload`       | Stored export payload as a JSON string.                    |
| `status`        | `0` pending, `1` processing, `2` success, or `3` failure.  |
| `downloadUrl`   | Authenticated download URL. Use only when `status` is `2`. |
| `failureReason` | Failure detail when `status` is `3`.                       |
| `successCount`  | Number of exported records processed so far.               |
| `format`        | `xlsx` or `csv`.                                           |
| `createTime`    | Task creation time as Unix seconds.                        |

Poll with a reasonable interval, such as 2–5 seconds, and stop when the task reaches status `2` or `3`. Use exponential backoff for long-running exports.

### 4. Download the file

The `downloadUrl` is protected. Send the same API key in the download request:

```bash theme={null}
curl -L "https://api.unibee.dev/export/12345" \
  -H "Authorization: Bearer $UNIBEE_API_KEY" \
  --output unibee-export.csv
```

Do not treat `downloadUrl` as a public or presigned URL. A request without the authorization header is denied.

## How `payload` works

`payload` is a JSON object, not a JSON-encoded string. Its fields correspond to filters consumed by the selected export task.

These export-only fields are available for all task types:

| Field                  | Type    | Description                                                                                                                                                      |
| ---------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `timeZone`             | string  | IANA time zone used to display timestamps in the exported file, for example `UTC`, `America/New_York`, or `Asia/Shanghai`. Defaults to `UTC`.                    |
| `legacyTimeZoneOffset` | boolean | Compatibility option. When `true`, subtracts the `timeZone` offset from timestamp filters before querying. New integrations should omit it or set it to `false`. |

Timestamp filters are Unix timestamps in seconds. By default, UniBee uses them exactly as supplied; `timeZone` changes exported timestamp display and does not change the filter range.

Amount filters such as `amountStart` and `amountEnd` use the currency's smallest unit, for example `1000` means USD 10.00.

For filters using `planTagFilter`, pass:

```json theme={null}
{
  "planTagFilter": {
    "tagIds": [101, 102],
    "mode": "any"
  }
}
```

`mode` can be `any` or `all` and defaults to `any`. When `planIds` and `planTagFilter` are both present, they are combined with union/OR semantics.

## Available export tasks and filters

Only the fields listed for each task below are consumed by that export implementation. Unknown payload fields are ignored.

| Task name            | Exported data                       | Related list endpoint                   |
| -------------------- | ----------------------------------- | --------------------------------------- |
| `SubscriptionExport` | Subscriptions                       | `/merchant/subscription/list`           |
| `InvoiceExport`      | Invoices                            | `/merchant/invoice/list`                |
| `UserExport`         | Users                               | `/merchant/user/list`                   |
| `TransactionExport`  | Payment and refund timeline records | `/merchant/payment/timeline/list`       |
| `DiscountExport`     | Discount codes                      | `/merchant/discount/list`               |
| `UserDiscountExport` | Discount usage records              | `/merchant/discount/user_discount_list` |
| `PlanExport`         | Plans                               | `/merchant/plan/list`                   |
| `MetricEventExport`  | Billable metric events              | `/merchant/metric/event_list`           |
| `UserChurnExport`    | Churn episodes                      | `/merchant/user_churn/list`             |

### `SubscriptionExport`

Exports subscriptions. Its filters correspond to `GET|POST /merchant/subscription/list`.

| Filter            | Type       | Description                                                                                                                                        |
| ----------------- | ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| `userId`          | integer    | Exact UniBee user ID.                                                                                                                              |
| `externalUserId`  | string     | Exact external user ID.                                                                                                                            |
| `searchKey`       | string     | Search subscription ID or email.                                                                                                                   |
| `email`           | string     | Filter by the subscription user's email.                                                                                                           |
| `status`          | integer\[] | `1` pending, `2` active, `3` pending-inactive (deprecated), `4` cancelled, `5` expired, `6` suspended, `7` incomplete, `8` processing, `9` failed. |
| `currency`        | string     | Currency code, for example `USD`.                                                                                                                  |
| `planIds`         | integer\[] | Include subscriptions using any listed plan ID.                                                                                                    |
| `planTagFilter`   | object     | Filter by plan tags using `tagIds` and `mode`. Combined with `planIds` using OR.                                                                   |
| `productIds`      | integer\[] | Include subscriptions using any listed product ID. Ignored when `planIds` is supplied.                                                             |
| `amountStart`     | integer    | Minimum subscription amount in the smallest currency unit.                                                                                         |
| `amountEnd`       | integer    | Maximum subscription amount in the smallest currency unit.                                                                                         |
| `sortField`       | string     | `gmt_create` or `gmt_modify`; default `gmt_modify`.                                                                                                |
| `sortType`        | string     | `asc` or `desc`; default `desc`.                                                                                                                   |
| `createTimeStart` | integer    | Inclusive creation-time lower bound, Unix seconds.                                                                                                 |
| `createTimeEnd`   | integer    | Creation-time upper bound, Unix seconds.                                                                                                           |

Example—active USD subscriptions:

```json theme={null}
{
  "status": [2],
  "currency": "USD"
}
```

### `InvoiceExport`

Exports invoices. Its filters correspond to `GET|POST /merchant/invoice/list`.

| Filter            | Type       | Description                                                                                      |
| ----------------- | ---------- | ------------------------------------------------------------------------------------------------ |
| `userId`          | integer    | Exact UniBee user ID.                                                                            |
| `gatewayIds`      | integer\[] | Include invoices for any listed gateway ID.                                                      |
| `planIds`         | integer\[] | Include invoices containing any listed plan ID.                                                  |
| `planTagFilter`   | object     | Filter by plan tags. Combined with `planIds` using OR.                                           |
| `hasDiscountCode` | boolean    | `true` for invoices with a discount code; `false` for invoices without one.                      |
| `discountCode`    | string     | Exact discount code, case-insensitive.                                                           |
| `firstName`       | string     | Filter by invoice user first name.                                                               |
| `lastName`        | string     | Filter by invoice user last name.                                                                |
| `currency`        | string     | Currency code.                                                                                   |
| `status`          | integer\[] | `1` pending, `2` processing, `3` paid, `4` failed, `5` cancelled, `6` reversed.                  |
| `searchKey`       | string     | Search invoice name, email, or product name.                                                     |
| `deleteInclude`   | boolean    | Include deleted records.                                                                         |
| `type`            | integer    | `0` payment invoice or `1` refund invoice.                                                       |
| `sendEmail`       | string     | Filter by the invoice email value.                                                               |
| `sortField`       | string     | `invoice_id`, `gmt_create`, `gmt_modify`, `period_end`, or `total_amount`; default `gmt_modify`. |
| `sortType`        | string     | `asc` or `desc`; default `desc`.                                                                 |
| `amountStart`     | integer    | Minimum invoice amount in the smallest currency unit.                                            |
| `amountEnd`       | integer    | Maximum invoice amount in the smallest currency unit.                                            |
| `createTimeStart` | integer    | Creation-time lower bound, Unix seconds.                                                         |
| `createTimeEnd`   | integer    | Creation-time upper bound, Unix seconds.                                                         |
| `reportTimeStart` | integer    | Report-time lower bound, Unix seconds.                                                           |
| `reportTimeEnd`   | integer    | Report-time upper bound, Unix seconds.                                                           |

Example—paid invoices created during January 2026:

```json theme={null}
{
  "status": [3],
  "createTimeStart": 1767225600,
  "createTimeEnd": 1769904000
}
```

### `UserExport`

Exports users. Its filters correspond to `GET|POST /merchant/user/list`.

| Filter            | Type       | Description                                                                                                                                                               |
| ----------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `userId`          | integer    | Exact UniBee user ID.                                                                                                                                                     |
| `externalUserId`  | string     | Exact external user ID.                                                                                                                                                   |
| `email`           | string     | Filter by email.                                                                                                                                                          |
| `firstName`       | string     | Filter by first name.                                                                                                                                                     |
| `lastName`        | string     | Filter by last name.                                                                                                                                                      |
| `searchKey`       | string     | Search first name, last name, email, phone, address, or external user ID.                                                                                                 |
| `subscriptionId`  | string     | Exact subscription ID.                                                                                                                                                    |
| `status`          | integer\[] | User status: `0` active or `2` suspended.                                                                                                                                 |
| `subStatus`       | integer\[] | Subscription status: `1` pending, `2` active, `3` pending-inactive (deprecated), `4` cancelled, `5` expired, `6` suspended, `7` incomplete, `8` processing, `9` failed.   |
| `planIds`         | integer\[] | Include users associated with any listed plan ID.                                                                                                                         |
| `gatewayIds`      | integer\[] | Include users associated with any listed gateway ID.                                                                                                                      |
| `deleteInclude`   | boolean    | Include deleted users.                                                                                                                                                    |
| `sortField`       | string     | `user_id`, `gmt_create`, `email`, `user_name`, `subscription_name`, `subscription_status`, `payment_method`, `recurring_amount`, or `billing_type`; default `gmt_create`. |
| `sortType`        | string     | `asc` or `desc`; default `desc`.                                                                                                                                          |
| `createTimeStart` | integer    | Creation-time lower bound, Unix seconds.                                                                                                                                  |
| `createTimeEnd`   | integer    | Creation-time upper bound, Unix seconds.                                                                                                                                  |

### `TransactionExport`

Exports payment and refund timeline records. Its filters correspond to `GET|POST /merchant/payment/timeline/list`.

| Filter            | Type       | Description                                                                                      |
| ----------------- | ---------- | ------------------------------------------------------------------------------------------------ |
| `userId`          | integer    | Exact UniBee user ID.                                                                            |
| `searchKey`       | string     | Search subscription ID, invoice ID, payment ID, or user ID.                                      |
| `currency`        | string     | Currency code.                                                                                   |
| `amountStart`     | integer    | Minimum transaction amount in the smallest currency unit.                                        |
| `amountEnd`       | integer    | Maximum transaction amount in the smallest currency unit.                                        |
| `status`          | integer\[] | `0` pending, `1` success, `2` failure, `3` cancelled.                                            |
| `timelineTypes`   | integer\[] | `0` payment or `1` refund.                                                                       |
| `gatewayIds`      | integer\[] | Include transactions for any listed gateway ID.                                                  |
| `planIds`         | integer\[] | Include timelines whose invoice contains any listed plan ID.                                     |
| `planTagFilter`   | object     | Filter by invoice plan tags. Combined with `planIds` using OR.                                   |
| `hasDiscountCode` | boolean    | Filter by whether the related invoice has a discount code.                                       |
| `discountCode`    | string     | Exact related-invoice discount code, case-insensitive.                                           |
| `sortField`       | string     | `invoice_id`, `gmt_create`, `gmt_modify`, `period_end`, or `total_amount`; default `gmt_modify`. |
| `sortType`        | string     | `asc` or `desc`; default `desc`.                                                                 |
| `createTimeStart` | integer    | Creation-time lower bound, Unix seconds.                                                         |
| `createTimeEnd`   | integer    | Creation-time upper bound, Unix seconds.                                                         |

### `DiscountExport`

Exports discount codes. Its filters correspond to `GET /merchant/discount/list`.

| Filter            | Type       | Description                                                            |
| ----------------- | ---------- | ---------------------------------------------------------------------- |
| `discountType`    | integer\[] | `1` percentage or `2` fixed amount.                                    |
| `billingType`     | integer\[] | `1` one-time or `2` recurring.                                         |
| `status`          | integer\[] | `1` editable, `2` active, `3` deactivated, `4` expired, `10` archived. |
| `code`            | string     | Exact discount code.                                                   |
| `searchKey`       | string     | Search discount code or name.                                          |
| `currency`        | string     | Currency code.                                                         |
| `sortField`       | string     | `gmt_create` or `gmt_modify`; default `gmt_modify`.                    |
| `sortType`        | string     | `asc` or `desc`; default `desc`.                                       |
| `createTimeStart` | integer    | Creation-time lower bound, Unix seconds.                               |
| `createTimeEnd`   | integer    | Creation-time upper bound, Unix seconds.                               |

### `UserDiscountExport`

Exports usage records for one discount code. Its filters correspond to `GET /merchant/discount/user_discount_list`.

| Filter            | Type       | Required | Description                                                                           |
| ----------------- | ---------- | -------- | ------------------------------------------------------------------------------------- |
| `id`              | integer    | Yes      | UniBee discount ID. The export returns no rows when this field is missing or invalid. |
| `userIds`         | integer\[] | No       | Include records for any listed user ID.                                               |
| `email`           | string     | No       | Filter by user email.                                                                 |
| `planIds`         | integer\[] | No       | Include records for any listed plan ID.                                               |
| `subscriptionIds` | string\[]  | No       | Include records for any listed subscription ID.                                       |
| `status`          | integer\[] | No       | `1` used or `2` rolled back.                                                          |
| `childCode`       | string     | No       | Fuzzy-search a child code; available when `id` is a batch-template ID.                |
| `sortField`       | string     | No       | `gmt_create` or `gmt_modify`; default `gmt_modify`.                                   |
| `sortType`        | string     | No       | `asc` or `desc`; default `desc`.                                                      |
| `createTimeStart` | integer    | No       | Creation-time lower bound, Unix seconds.                                              |
| `createTimeEnd`   | integer    | No       | Creation-time upper bound, Unix seconds.                                              |

Example:

```json theme={null}
{
  "id": 1001,
  "status": [1]
}
```

### `PlanExport`

Exports plans. Its filters correspond to `GET|POST /merchant/plan/list`.

| Filter          | Type       | Description                                                                  |
| --------------- | ---------- | ---------------------------------------------------------------------------- |
| `planIds`       | integer\[] | Include any listed plan ID.                                                  |
| `planTagFilter` | object     | Filter by plan tags. Combined with `planIds` using OR.                       |
| `productIds`    | integer\[] | Include plans belonging to any listed product ID.                            |
| `type`          | integer\[] | `1` main plan, `2` recurring add-on, `3` one-time plan.                      |
| `status`        | integer\[] | `1` editing, `2` active, `3` inactive, `4` soft-archived, `5` hard-archived. |
| `publishStatus` | integer    | `1` unpublished or `2` published.                                            |
| `searchKey`     | string     | Search plan name or description.                                             |
| `currency`      | string     | Currency code.                                                               |
| `sortField`     | string     | `plan_name`, `gmt_create`, or `gmt_modify`; default `gmt_create`.            |
| `sortType`      | string     | `asc` or `desc`; default `desc`.                                             |

### `MetricEventExport`

Exports billable metric events. Its filters correspond to `GET|POST /merchant/metric/event_list`.

| Filter            | Type       | Description                                                                                                                 |
| ----------------- | ---------- | --------------------------------------------------------------------------------------------------------------------------- |
| `userIds`         | integer\[] | Include events for any listed user ID.                                                                                      |
| `metricIds`       | integer\[] | Include events for any listed metric ID.                                                                                    |
| `subscriptionIds` | string\[]  | Include events for any listed subscription ID.                                                                              |
| `invoiceId`       | string     | List events for the invoice period. When supplied, its subscription period overrides `createTimeStart` and `createTimeEnd`. |
| `sortField`       | string     | `user_id` or `gmt_create`; default `gmt_create`.                                                                            |
| `sortType`        | string     | `asc` or `desc`; default `desc`.                                                                                            |
| `createTimeStart` | integer    | Creation-time lower bound, Unix seconds.                                                                                    |
| `createTimeEnd`   | integer    | Creation-time upper bound, Unix seconds.                                                                                    |

### `UserChurnExport`

Exports churn episodes. Its filters correspond to `GET|POST /merchant/user_churn/list`.

| Filter           | Type       | Description                                                                      |
| ---------------- | ---------- | -------------------------------------------------------------------------------- |
| `view`           | string     | `pending`, `current`, `reactivated`, or `all`; default `all`.                    |
| `churnTimeStart` | integer    | Inclusive churn-time lower bound, Unix seconds.                                  |
| `churnTimeEnd`   | integer    | Exclusive churn-time upper bound, Unix seconds; the range is `[start, end)`.     |
| `churnType`      | string     | `Cancelled` or `Expired`.                                                        |
| `reasonCategory` | string     | Normalized churn reason category.                                                |
| `productIds`     | integer\[] | Include churn records for any listed product ID.                                 |
| `planIds`        | integer\[] | Include churn records for any listed plan ID.                                    |
| `userId`         | integer    | Exact UniBee user ID.                                                            |
| `email`          | string     | Filter by email.                                                                 |
| `externalUserId` | string     | Filter by external user ID.                                                      |
| `searchKey`      | string     | Search email, external user ID, subscription ID, or user ID.                     |
| `countryCode`    | string     | Filter by country code.                                                          |
| `currency`       | string     | Filter by currency code.                                                         |
| `sortField`      | string     | `churn_time`, `confirm_time`, `reactivated_time`, or `id`; default `churn_time`. |
| `sortType`       | string     | `asc` or `desc`; default `desc`.                                                 |

## Error handling

| Condition                           | Behavior                                                                                     |
| ----------------------------------- | -------------------------------------------------------------------------------------------- |
| Missing or invalid API key          | Merchant API endpoints return HTTP `401`. The download endpoint denies the request.          |
| Invalid `task`                      | `new_export` returns a validation error such as `Task not found`.                            |
| Invalid `format`                    | The request fails unless the value is `xlsx` or `csv`.                                       |
| Task status `3`                     | Read `failureReason`; create a new task after correcting the request or after a retry delay. |
| Download before status `2`          | The download endpoint returns HTTP `400`.                                                    |
| API key belongs to another merchant | The download endpoint returns `Not Your Task`.                                               |

For JSON API errors, check both the HTTP status and the response envelope's `code` and `message`. Log `requestId` when contacting UniBee support.
