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

# Criar Afiliado

> Aprenda a criar um afiliado usando o endpoint POST /stores/{storeId}/affiliates.

## 📌 Endpoint

`POST /stores/{storeId}/affiliates`

Cria um novo afiliado na loja.

O `code` (slug) é usado para montar o link de divulgação:
`https://SEU_DOMINIO.com.br/l/{code}`.

***

## 🔐 Autenticação

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

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

***

## 🧾 Parâmetros de rota

| Parâmetro | Tipo | Obrigatório | Descrição |
| - | - | - | - |
| `storeId` | string | Sim | ID da loja |

***

## 📤 Body (JSON)

| Campo | Tipo | Obrigatório | Regras |
| - | - | - | - |
| `name` | string | Sim | até 56 caracteres |
| `email` | string | Sim | e-mail válido, **único por loja** (comparação sem diferenciar maiúsculas) |
| `code` | string | Sim | slug único em minúsculas `^[a-z0-9]+(?:-[a-z0-9]+)*$` (3 a 50 caracteres) |
| `image` | string | Não | URL `http`/`https` válida (até 512 caracteres) ou `null` |
| `metadata` | object | Não | dados extras/observações sobre o afiliado (máximo de 64 chaves) |
| `commissionRules` | array | Não | array não vazio com regras de comissão: `[{ type, targetId, commission, position }]`. `type` ∈ `DEFAULT`, `PRODUCT`, `CATEGORY`, `COUPON`; `targetId` é o id do produto/categoria ou o código do cupom (não se aplica ao `DEFAULT`); `commission` de 1 a 100; `position` é um inteiro `>= 0` e único por regra, definindo a prioridade — **menor `position` vence** quando várias regras casam. A regra `DEFAULT` casa com qualquer venda e funciona como o **percentual padrão** do afiliado (fica na maior `position`) |

***

## ✅ Exemplo de requisição

```bash theme={null}
curl -X POST "https://api.cabrapi.com.br/v1/stores/STORE_ID/affiliates" \
	-H "Authorization: SUA_API_KEY_AQUI" \
	-H "Content-Type: application/json" \
	-d '{
		"code": "bianca-rocha",
		"name": "Bianca Rocha",
		"email": "bianca@email.com",
		"metadata": {
			"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
			}
		]
	}'
```

***

## 📦 Resposta de sucesso (201)

```json theme={null}
{
	"code": "AFFILIATE_CREATED",
	"affiliate": {
		"id": "AFFILIATE_ID",
		"name": "Bianca Rocha",
		"email": "bianca@email.com",
		"code": "bianca-rocha",
		"image": null,
		"status": "ativo",
		"pausedAt": null,
		"metadata": {
			"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
			}
		],
		"createdAt": "2026-09-08T19:30:00Z",
		"updatedAt": "2026-09-08T19:30:00Z",
		"storeId": "STORE_ID"
	}
}
```

***

## ⚠️ Possíveis erros

* `400 INVALID_DATA` → body inválido
* `400 INVALID_DATA_NAME` → `name` ausente ou fora de 1 a 56 caracteres
* `400 INVALID_DATA_EMAIL` → `email` ausente, inválido ou maior que 120 caracteres
* `400 INVALID_DATA_CODE` → `code` ausente, fora de 3 a 50 caracteres ou fora do padrão slug
* `400 INVALID_DATA_IMAGE` → `image` inválida (URL `http`/`https` inválida ou maior que 512 caracteres)
* `400 INVALID_DATA_METADATA` → `metadata` inválido (não é objeto ou excede 64 chaves)
* `400 INVALID_DATA_RULES` → `commissionRules` inválido (não é um array)
* `400 INVALID_COMMISSION_RULES` → `commissionRules` vazio
* `400 INVALID_COMMISSION_RULE_TYPE` → `type` inválido
* `400 INVALID_COMMISSION_RULE_POSITION` → `position` inválida/duplicada
* `400 INVALID_COMMISSION_VALUE` → `commission` fora de 1 a 100
* `400 COMMISSION_RULE_DEFAULT_REQUIRED` → falta exatamente uma regra `DEFAULT`
* `400 INVALID_COMMISSION_RULE_TARGET` → `DEFAULT` com `targetId`, ou `PRODUCT`/`CATEGORY`/`COUPON` sem `targetId`
* `400 RELATION_NOT_FOUND` → `targetId` de produto/categoria/cupom inexistente na loja
* `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
* `409 AFFILIATE_ALREADY_EXISTS` → `code` já existente
* `409 AFFILIATE_EMAIL_ALREADY_EXISTS` → e-mail já cadastrado por outro afiliado na loja
* `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 POST /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:
    post:
      tags:
        - Affiliates
      summary: Create affiliate
      operationId: createAffiliate
      parameters:
        - $ref: '#/components/parameters/StoreId'
      requestBody:
        required: true
        description: Affiliate details (name, email, code, commissionRules).
        content:
          application/json:
            schema:
              type: object
              required:
                - name
                - email
                - code
              properties:
                name:
                  type: string
                  minLength: 1
                  maxLength: 56
                email:
                  format: email
                  maxLength: 120
                  type: string
                code:
                  type: string
                  minLength: 3
                  maxLength: 50
                  pattern: ^[a-z0-9]+(?:-[a-z0-9]+)*$
                image:
                  type: string
                  maxLength: 512
                  nullable: true
                metadata:
                  type: object
                  maxProperties: 64
                  nullable: true
                commissionRules:
                  type: array
                  nullable: true
                  items:
                    type: object
                    required:
                      - type
                      - commission
                      - position
                    properties:
                      type:
                        enum:
                          - DEFAULT
                          - PRODUCT
                          - CATEGORY
                          - COUPON
                        type: string
                      targetId:
                        type: string
                      commission:
                        type: number
                        minimum: 1
                        maximum: 100
                      position:
                        type: integer
                        minimum: 0
                  minItems: 1
      responses:
        '201':
          content:
            application/json:
              schema:
                properties:
                  code:
                    example: AFFILIATE_CREATED
                    type: string
                  affiliate:
                    $ref: '#/components/schemas/Affiliate'
                required:
                  - code
                  - affiliate
                type: object
          description: Create affiliate.
        '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.
        '409':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
          description: Resource already exists.
        '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
    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.