
## Aggregate payments

`POST /v1/payments/aggregate`

Counts payments and computes numeric aggregations (`sum`, `avg`, `min`, `max`) over the `sum` field. Supports filtering and grouping by `paySystemId`, `orderId`, `currency`, `paid`, `responsibleId`.

## Standard fields

| Field | Purpose |
|------|------------|
| `sum` | The only numeric field — suitable for `sum` / `avg` / `min` / `max` (the field name and the function name coincide, but they are different things) |
| `paySystemId`, `orderId`, `responsibleId` | Identifiers — used in `groupBy` (by payment system, order, responsible) |
| `currency` | Categorical — used in `groupBy` (by currency) |
| `paid` | Boolean — used in `groupBy` (paid / unpaid) |

The full list of aggregatable fields is given in the table above.

## Request fields (body)

| Parameter | Type | Req. | Description |
|----------|-----|:-----:|---------|
| `aggregate` | array | no | Array of aggregations: `[{ "field": "sum", "function": "sum" }]`. Functions: `count`, `sum`, `avg`, `min`, `max`. For `count`, the field is `"*"`. Without the parameter — only `count` (a single request to Bitrix24, records are not fetched) |
| `filter` | object | no | Filtering — the same fields as in [`GET /v1/payments`](./list.md). [Filtering syntax](/docs/filtering) |
| `groupBy` | string \| string[] | no | A field or an array of fields to group by (maximum 5) |
| `groupOrderBy` | array | no | Group sorting: `[{ "field": "sum:sum", "direction": "desc" }]` |
| `groupLimit` | number | no | Limit on the number of groups returned (1-1000) |

## Examples

### curl — personal key

```bash
curl -X POST "https://vibecode.bitrix24.com/v1/payments/aggregate" \
  -H "X-Api-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "aggregate": [{ "field": "sum", "function": "sum" }],
    "groupBy": "paySystemId"
  }'
```

### curl — OAuth application

```bash
curl -X POST "https://vibecode.bitrix24.com/v1/payments/aggregate" \
  -H "X-Api-Key: YOUR_APP_KEY" \
  -H "Authorization: Bearer USER_SESSION_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "aggregate": [{ "field": "sum", "function": "sum" }],
    "groupBy": "paySystemId"
  }'
```

### JavaScript — personal key

```javascript
const res = await fetch('https://vibecode.bitrix24.com/v1/payments/aggregate', {
  method: 'POST',
  headers: {
    'X-Api-Key': 'YOUR_API_KEY',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    aggregate: [{ field: 'sum', function: 'sum' }],
    groupBy: 'paySystemId',
  }),
})

const { success, data } = await res.json()
console.log(data.groups)
```

### JavaScript — OAuth application

```javascript
const res = await fetch('https://vibecode.bitrix24.com/v1/payments/aggregate', {
  method: 'POST',
  headers: {
    'X-Api-Key': 'YOUR_APP_KEY',
    'Authorization': 'Bearer USER_SESSION_TOKEN',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    aggregate: [{ field: 'sum', function: 'sum' }],
    groupBy: 'paySystemId',
  }),
})

const { success, data } = await res.json()
```

## Other scenarios

Count records — `count` with field `"*"`, the fastest request without fetching records. Without the `aggregate` array the result is the same:

```json
{ "aggregate": [{ "field": "*", "function": "count" }] }
```

Sum of all received payments:

```json
{
  "aggregate": [{ "field": "sum", "function": "sum" }],
  "filter": { "paid": true }
}
```

Top 3 payment systems by amount, sorted:

```json
{
  "aggregate": [{ "field": "sum", "function": "sum" }],
  "groupBy": "paySystemId",
  "groupOrderBy": [{ "field": "sum:sum", "direction": "desc" }],
  "groupLimit": 3
}
```

## Response fields

| Field | Type | Description |
|------|-----|---------|
| `success` | boolean | Always `true` on success |
| `data.count` | number | Total number of payments matching the filter |
| `data.aggregates` | object | Aggregation results: `{ "sum": { "sum": ..., "avg": ... } }` |
| `data.groups` | array | Groups (only when `groupBy` is set) |
| `data.meta.totalRecords` | number | Total number of records |
| `data.meta.recordsProcessed` | number | Number of records processed (up to 5000) |
| `data.meta.truncated` | boolean | `true` if there are more than 5000 records |
| `data.meta.groupTotal` | number | Number of groups before `groupLimit` |
| `data.meta.groupsTruncated` | boolean | Whether the group list was truncated by `groupLimit` |

## Response example

```json
{
  "success": true,
  "data": {
    "count": 99,
    "aggregates": {
      "sum": { "sum": 8475.87 }
    },
    "groups": [
      {
        "paySystemId": 11,
        "count": 87,
        "aggregates": { "sum": { "sum": 5870.5 } }
      },
      {
        "paySystemId": 6,
        "count": 8,
        "aggregates": { "sum": { "sum": 2025.37 } }
      },
      {
        "paySystemId": 25,
        "count": 4,
        "aggregates": { "sum": { "sum": 580 } }
      }
    ],
    "meta": {
      "totalRecords": 99,
      "recordsProcessed": 99,
      "truncated": false,
      "groupTotal": 3,
      "groupsTruncated": false
    }
  }
}
```

Without `groupBy`, the `data.groups` field is absent from the response.

## Error response example

400 — a `groupBy` field is outside the list of aggregatable fields:

```json
{
  "success": false,
  "error": {
    "code": "INVALID_PARAMS",
    "message": "groupBy field 'foo' is not aggregatable on this entity. Available: sum, currency, paid, paySystemId, orderId, responsibleId."
  }
}
```

## Errors

| HTTP | Code | Description |
|------|-----|---------|
| 400 | `INVALID_PARAMS` | Unknown aggregation function |
| 400 | `INVALID_PARAMS` | Non-existent numeric field in `aggregate[].field` — message `Field 'foo' not found. Available numeric fields: …` |
| 400 | `INVALID_PARAMS` | A `groupBy` field outside the aggregatable list — message `groupBy field 'foo' is not aggregatable on this entity. Available: …` |
| 400 | `INVALID_PARAMS` | More than 5 fields passed in `groupBy` |
| 400 | `INVALID_PARAMS` | Reserved keywords in `groupBy`: `count`, `aggregates`, `meta`, `groups` |
| 403 | `SCOPE_DENIED` | The API key does not have the `sale` scope |
| 401 | `TOKEN_MISSING` | The API key has no configured tokens |

Full list of common API errors — [Errors](/docs/errors).

## Known specifics

**`count` vs numeric functions.** `count` is computed with a single request to Bitrix24 — records are not fetched and the response is fast at any volume. `sum` / `avg` / `min` / `max` fetch records page by page (maximum 5000) and compute on the Vibecode side. With more than 5000 records, `meta.truncated` will be `true`.

**Grouping by `currency` matters on multi-currency Bitrix24 accounts.** The total of all payments in `data.aggregates.sum.sum` without `groupBy: "currency"` mixes different currencies — it only becomes meaningful when split out.

## See also

- [Payment fields](./fields.md)
- [List payments](./list.md)
- [Search payments](./search.md)
- [Filtering syntax](/docs/filtering)
- [Limits and optimization](/docs/optimization)
