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

# Buscar Afiliados

> Aprende a buscar afiliados y mostrar la información completa usando GET /stores/{storeId}/affiliates.

## 📌 Endpoint

`GET /stores/{storeId}/affiliates`

Busca y **filtra** los afiliados de la tienda. Con `statistics=true`, la respuesta incluye las **estadísticas** (ingresos netos — ya descontadas las tasas de la pasarela de pago —, ventas y clics calculados en el momento) y las **métricas** del período (`from`/`to`).

***

## ⚙️ Cómo se resuelve la comisión

En el momento de la venta, el porcentaje se resuelve por **ítem**:

1. Entre las reglas `commissionRules` del afiliado, se consideran las que **encajan** con el ítem:
   * `PRODUCT` → el ítem es el producto (`targetId`);
   * `CATEGORY` → el ítem pertenece a la categoría (`targetId`);
   * `COUPON` → el cupón aplicado al pago es (`targetId`);
   * `DEFAULT` → **siempre encaja** con cualquier ítem.
2. Vence la regla de **menor `position`** entre las que encajaron.
3. Si ninguna otra encaja, la `DEFAULT` (mayor `position`) es el porcentaje por defecto del afiliado.

> La validación de `targetId` ocurre en el **POST/PUT**: para `PRODUCT`, `CATEGORY` y `COUPON` debe existir en la tienda. Las reglas cuyo `target` se eliminó después son **ignoradas** en la resolución, sin afectar la venta.

***

## 🔐 Autenticación

* **Ruta privada**.
* Requiere el header `Authorization` con tu API key y plan activo.

```json theme={null}
{
	"Authorization": "TU_API_KEY_AQUI"
}
```

***

## 🔎 Parámetros de consulta

| Parámetro | Tipo | Obligatorio | Descripción |
| - | - | - | - |
| `id` | string | No | Busca un afiliado por ID (con `statistics=true`, la respuesta incluye `statistics` y `metrics`) |
| `name` | string | No | Busca por nombre (parcial, sin diferenciar mayúsculas) |
| `email` | string | No | Busca por correo electrónico (sin diferenciar mayúsculas; cuando se envía, debe ser un correo válido de hasta 120 caracteres, de lo contrario devuelve `400 INVALID_DATA`) |
| `code` | string | No | Busca por el código/atajo del enlace |
| `status` | string | No | `activo` o `inactivo` |
| `statistics` | boolean | No | Si es `true`, incluye `statistics` y `metrics` del afiliado |
| `from` | date | No | Fecha inicial de las métricas (`RFC3339` o `YYYY-MM-DD`; validado incluso sin `statistics=true`). Requiere `statistics=true` para devolver métricas |
| `to` | date | No | Fecha final de las métricas (`RFC3339` o `YYYY-MM-DD`; validado incluso sin `statistics=true`). Requiere `statistics=true` para devolver métricas |
| `page` | number | No | Página actual (predeterminado: `1`) |
| `limit` | number | No | Ítems por página (predeterminado: `20`, máximo: `100`) |
| `cursor` | string | No | Cursor opaco para paginación por cursor. Usa el `nextCursor` de la respuesta anterior. No puede usarse junto con `page` |

***

## 🔄 Paginación por cursor

Para listas grandes (más de \~100 ítems), prefiere la paginación por **cursor** en lugar de `page`:

1. Haz la primera llamada **sin** `cursor`.
2. Si `hasMore` es `true`, la respuesta trae el campo `nextCursor`.
3. Envía ese `nextCursor` en el parámetro `cursor` de la siguiente solicitud para buscar la página siguiente.

```bash theme={null}
curl -X GET "https://api.cabrapi.com.br/v1/stores/STORE_ID/affiliates?status=ativo&cursor=v1:TU_CURSOR_AQUI&limit=20" \
	-H "Authorization: TU_API_KEY_AQUI"
```

En modo cursor, la paginación se devuelve solo con `nextCursor`, `hasMore` y `limit`:

```json theme={null}
{
	"code": "AFFILIATES_FETCHED",
	"affiliates": [],
	"pagination": {
		"nextCursor": "v1:e2xFn...",
		"hasMore": true,
		"limit": 20
	}
}
```

* `cursor` y `page` **no pueden** usarse juntos (`400 INVALID_PAGINATION`).
* `nextCursor: null` con `hasMore: false` indican el fin de la lista (la API responde `200` con array vacío).

***

## ✅ Ejemplo de solicitud — lista con filtros

```bash theme={null}
curl -X GET "https://api.cabrapi.com.br/v1/stores/STORE_ID/affiliates?name=bianca&status=ativo&page=1&limit=20" \
	-H "Authorization: TU_API_KEY_AQUI"
```

***

## ✅ Ejemplo de solicitud — información completa de un afiliado

```bash theme={null}
curl -X GET "https://api.cabrapi.com.br/v1/stores/STORE_ID/affiliates?id=AFFILIATE_ID&statistics=true&from=2026-08-01&to=2026-08-31" \
	-H "Authorization: TU_API_KEY_AQUI"
```

***

## 📦 Respuesta exitosa (200)

```json theme={null}
{
	"code": "AFFILIATES_FETCHED",
	"affiliates": [
		{
			"id": "AFFILIATE_ID",
			"name": "Bianca Rocha",
			"email": "bianca@email.com",
			"code": "bianca-rocha",
			"image": null,
			"status": "ativo",
			"pausedAt": null,
			"metadata": {
				"note": "afiliado destacado",
				"tag": "premium"
			},
			"commissionRules": [
				{
					"type": "PRODUCT",
					"targetId": "PRODUCT_ID",
					"commission": 15,
					"position": 0
				},
				{
					"type": "CATEGORY",
					"targetId": "CATEGORY_ID",
					"commission": 12,
					"position": 1
				},
				{
					"type": "COUPON",
					"targetId": "CUPOM10",
					"commission": 20,
					"position": 2
				},
				{
					"type": "DEFAULT",
					"commission": 10,
					"position": 3
				}
			],
			"storeId": "STORE_ID",
			"createdAt": "2026-09-08T19:30:00Z",
			"updatedAt": "2026-09-08T19:30:00Z",
			"statistics": {
				"revenue": 8990.0,
				"sales": 34,
				"clicks": 1284
			},
			"metrics": {
				"commissions": {
					"totalCount": 12,
					"totalValue": 154.9,
					"graph": [
						{ "date": "2026-08-01", "total": 19.9 },
						{ "date": "2026-08-02", "total": 0 }
					]
				},
				"affiliateRevenue": {
					"totalCount": 12,
					"totalValue": 1549.0,
					"graph": [
						{ "date": "2026-08-01", "total": 199.0 }
					]
				}
			}
		}
	],
	"pagination": {
		"page": 1,
		"limit": 20,
		"total": 1,
		"totalPages": 1,
		"nextCursor": null,
		"hasMore": false
	}
}
```

> La primera llamada (sin `cursor`) ya devuelve `nextCursor` y `hasMore` en la paginación, permitiendo iniciar la paginación por cursor sin llamadas extra.

***

## ⚠️ Posibles errores

* `400 INVALID_DATA` → parámetros inválidos (`id`, `name`, `email` inválido o mayor de 120 caracteres, `code`, `status`, `from`, `to` o `storeId`)
* `400 INVALID_PAGINATION_LIMIT` → `limit` fuera del intervalo permitido (`1` a `100`)
* `400 INVALID_PAGINATION_PAGE` → `page` inválida
* `400 INVALID_PAGINATION_CURSOR` → `cursor` inválido o malformado
* `400 INVALID_PAGINATION` → `page` y `cursor` utilizados juntos
* `401 API_KEY_NOT_PROVIDED` → header `Authorization` no enviado
* `401 INVALID_API_KEY` → API key inválida
* `401 UNAUTHENTICATED` → usuario no autenticado
* `403 USER_DISABLED` → usuario deshabilitado
* `403 NO_ACTIVE_SUBSCRIPTION` → sin plan activo
* `404 STORE_NOT_FOUND` → tienda no encontrada
* `404 AFFILIATE_NOT_FOUND` → `id` informado no encontrado (aplica solo en modo offset, sin `cursor`)
* `429 RATE_LIMIT_EXCEEDED` → límite de solicitudes por minuto excedido
* `500 INTERNAL_SERVER_ERROR` → error interno
* `503 SERVICE_UNAVAILABLE` → servicio no disponible


## OpenAPI

````yaml GET /stores/{storeId}/affiliates
openapi: 3.1.0
info:
  title: caBRAPI
  version: 1.0.0
servers:
  - url: https://api.cabrapi.com.br/v1
security: []
paths:
  /stores/{storeId}/affiliates:
    get:
      tags:
        - Affiliates
      summary: List affiliates
      operationId: listAffiliates
      parameters:
        - $ref: '#/components/parameters/StoreId'
        - in: query
          name: id
          schema:
            maxLength: 50
            type: string
        - in: query
          name: name
          schema:
            maxLength: 56
            type: string
        - in: query
          name: email
          schema:
            format: email
            maxLength: 120
            type: string
        - in: query
          name: code
          schema:
            maxLength: 50
            type: string
        - in: query
          name: status
          schema:
            enum:
              - ativo
              - inativo
            type: string
        - in: query
          name: from
          schema:
            type: string
          description: Start date filter (RFC3339 or YYYY-MM-DD).
        - in: query
          name: to
          schema:
            type: string
          description: End date filter (RFC3339 or YYYY-MM-DD).
        - in: query
          name: page
          schema:
            default: 1
            minimum: 1
            type: integer
        - in: query
          name: limit
          schema:
            default: 20
            maximum: 100
            minimum: 1
            type: integer
        - description: Opaque cursor from previous page (do not combine with page).
          in: query
          name: cursor
          schema:
            type: string
        - in: query
          name: statistics
          schema:
            type: boolean
      responses:
        '200':
          content:
            application/json:
              schema:
                properties:
                  code:
                    example: AFFILIATES_FETCHED
                    type: string
                  affiliates:
                    items:
                      $ref: '#/components/schemas/Affiliate'
                    type: array
                  pagination:
                    $ref: '#/components/schemas/Pagination'
                required:
                  - code
                  - affiliates
                  - pagination
                type: object
          description: List affiliates.
        '400':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
          description: Invalid request.
        '401':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
          description: Missing or invalid API key.
        '403':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
          description: Forbidden (inactive plan or insufficient permissions).
        '404':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
          description: Resource not found.
        '429':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
          description: Rate limit exceeded.
        '500':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
          description: Internal server error.
        '503':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
          description: Service unavailable.
      security:
        - ApiKey: []
components:
  parameters:
    StoreId:
      in: path
      name: storeId
      required: true
      schema:
        type: string
        minLength: 1
        maxLength: 50
  schemas:
    Affiliate:
      description: Store affiliate (referral code, commission, and stats).
      properties:
        code:
          type: string
        commissionRules:
          items:
            properties:
              commission:
                type: number
              position:
                type: integer
              targetId:
                type: string
              type:
                enum:
                  - DEFAULT
                  - PRODUCT
                  - CATEGORY
                  - COUPON
                type: string
            required:
              - type
              - commission
              - position
            type: object
          nullable: true
          type: array
        createdAt:
          format: date-time
          type: string
        email:
          format: email
          nullable: true
          type: string
        id:
          format: uuid
          type: string
        image:
          nullable: true
          type: string
        metadata:
          nullable: true
          type: object
        name:
          type: string
        pausedAt:
          format: date-time
          nullable: true
          type: string
        status:
          enum:
            - ativo
            - inativo
          type: string
        storeId:
          format: uuid
          type: string
        updatedAt:
          format: date-time
          type: string
        statistics:
          description: Included when statistics=true.
          type: object
          properties:
            clicks:
              type: integer
            revenue:
              type: number
            sales:
              type: integer
        metrics:
          description: Included when statistics=true.
          type: object
          properties:
            commissions:
              type: object
              properties:
                totalCount:
                  type: integer
                totalValue:
                  type: number
                graph:
                  type: array
                  items:
                    type: object
                    properties:
                      date:
                        type: string
                      total:
                        type: number
                    required:
                      - date
                      - total
              required:
                - totalCount
                - totalValue
                - graph
            affiliateRevenue:
              type: object
              properties:
                totalCount:
                  type: integer
                totalValue:
                  type: number
                graph:
                  type: array
                  items:
                    type: object
                    properties:
                      date:
                        type: string
                      total:
                        type: number
                    required:
                      - date
                      - total
              required:
                - totalCount
                - totalValue
                - graph
          required:
            - commissions
            - affiliateRevenue
      required:
        - id
        - name
        - code
        - status
        - storeId
        - createdAt
        - updatedAt
      type: object
    Pagination:
      properties:
        hasMore:
          type: boolean
        limit:
          type: integer
        nextCursor:
          nullable: true
          type: string
        page:
          type: integer
        total:
          type: integer
        totalPages:
          type: integer
      type: object
    Error:
      properties:
        code:
          example: STORE_NOT_FOUND
          type: string
      required:
        - code
      type: object
  securitySchemes:
    ApiKey:
      in: header
      name: Authorization
      type: apiKey
      x-default: YOUR_API_KEY_HERE

````

This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.