> ## 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

> Aprenda a buscar afiliados e exibir as informações completas usando GET /stores/{storeId}/affiliates.

## 📌 Endpoint

`GET /stores/{storeId}/affiliates`

Busca e **filtra** os afiliados da loja. Com `statistics=true` a resposta inclui as **estatísticas** (receita líquida — já descontadas as taxas da gateway —, vendas e cliques calculados na hora) e as **métricas** do período (`from`/`to`).

***

## ⚙️ Como a comissão é resolvida

Na hora da venda, a porcentagem é resolvida por **item**:

1. Entre as regras `commissionRules` do afiliado, são consideradas as que **casam** com o item:
   * `PRODUCT` → o item é do produto (`targetId`);
   * `CATEGORY` → o item pertence à categoria (`targetId`);
   * `COUPON` → o cupom aplicado no pagamento é o (`targetId`);
   * `DEFAULT` → **sempre casa** com qualquer item.
2. Vence a regra de **menor `position`** entre as que casaram.
3. Se nenhuma outra casar, a `DEFAULT` (maior `position`) é o percentual padrão do afiliado.

> A validação do `targetId` acontece no **POST/PUT**: para `PRODUCT`, `CATEGORY` e `COUPON` ele precisa existir na loja. Regras cujo `target` foi removido depois são **ignoradas** na resolução, sem afetar a venda.

***

## 🔐 Autenticação

* **Rota privada**.
* Requer header `Authorization` com sua API key e plano ativo.

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

***

## 🔎 Query params

| Parâmetro | Tipo | Obrigatório | Descrição |
| - | - | - | - |
| `id` | string | Não | Busca um afiliado pelo ID (com `statistics=true`, a resposta inclui `statistics` e `metrics`) |
| `name` | string | Não | Busca por nome (parcial, sem diferenciar maiúsculas) |
| `email` | string | Não | Busca por e-mail (sem diferenciar maiúsculas; quando enviado, deve ser um e-mail válido com até 120 caracteres, caso contrário retorna `400 INVALID_DATA`) |
| `code` | string | Não | Busca pelo código/atalho do link |
| `status` | string | Não | `ativo` ou `inativo` |
| `statistics` | boolean | Não | Se `true`, inclui `statistics` e `metrics` do afiliado |
| `from` | date | Não | Data inicial das métricas (`RFC3339` ou `YYYY-MM-DD`; validado mesmo sem `statistics=true`). Requer `statistics=true` para retornar métricas |
| `to` | date | Não | Data final das métricas (`RFC3339` ou `YYYY-MM-DD`; validado mesmo sem `statistics=true`). Requer `statistics=true` para retornar métricas |
| `page` | number | Não | Página atual (padrão: `1`) |
| `limit` | number | Não | Itens por página (padrão: `20`, máximo: `100`) |
| `cursor` | string | Não | Cursor opaco para paginação por cursor. Use o `nextCursor` da resposta anterior. Não pode ser usado junto com `page` |

***

## 🔄 Paginação por cursor

Para listas grandes (mais de \~100 itens), prefira paginação por **cursor** no lugar de `page`:

1. Faça a primeira chamada **sem** `cursor`.
2. Se `hasMore` for `true`, a resposta traz o campo `nextCursor`.
3. Envie esse `nextCursor` no parâmetro `cursor` da próxima requisição para buscar a página seguinte.

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

No modo cursor, a paginação é retornada apenas com `nextCursor`, `hasMore` e `limit`:

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

* `cursor` e `page` **não podem** ser usados juntos (`400 INVALID_PAGINATION`).
* `nextCursor: null` com `hasMore: false` indicam o fim da lista (a API responde `200` com array vazio).

***

## ✅ Exemplo de requisição — lista com 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: SUA_API_KEY_AQUI"
```

***

## ✅ Exemplo de requisição — informações completas de um 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: SUA_API_KEY_AQUI"
```

***

## 📦 Resposta de sucesso (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 top",
				"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
	}
}
```

> A primeira chamada (sem `cursor`) já retorna `nextCursor` e `hasMore` na paginação, permitindo iniciar a paginação por cursor sem chamadas extras.

***

## ⚠️ Possíveis erros

* `400 INVALID_DATA` → parâmetros inválidos (`id`, `name`, `email` inválido ou maior que 120 caracteres, `code`, `status`, `from`, `to` ou `storeId`)
* `400 INVALID_PAGINATION_LIMIT` → `limit` fora do intervalo permitido (`1` a `100`)
* `400 INVALID_PAGINATION_PAGE` → `page` inválida
* `400 INVALID_PAGINATION_CURSOR` → `cursor` inválido ou malformado
* `400 INVALID_PAGINATION` → `page` e `cursor` utilizados juntos
* `401 API_KEY_NOT_PROVIDED` → header `Authorization` não enviado
* `401 INVALID_API_KEY` → API key inválida
* `401 UNAUTHENTICATED` → usuário não autenticado
* `403 USER_DISABLED` → usuário desativado
* `403 NO_ACTIVE_SUBSCRIPTION` → sem plano ativo
* `404 STORE_NOT_FOUND` → loja não encontrada
* `404 AFFILIATE_NOT_FOUND` → `id` informado não encontrado (aplica-se apenas ao modo offset, sem `cursor`)
* `429 RATE_LIMIT_EXCEEDED` → limite de requisições por minuto excedido
* `500 INTERNAL_SERVER_ERROR` → erro interno
* `503 SERVICE_UNAVAILABLE` → serviço indisponível


## 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.