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

# Actualizar Afiliado

> Aprende a actualizar un afiliado usando el endpoint PUT /stores/{storeId}/affiliates/{affiliateId}.

## 📌 Endpoint

`PUT /stores/{storeId}/affiliates/{affiliateId}`

Actualiza los datos de un afiliado (nombre, correo electrónico, código, imagen, estado, metadata y reglas de comisión).

Todos los campos son opcionales — solo los enviados son modificados.

***

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

| Parámetro | Tipo | Obligatorio | Descripción |
| - | - | - | - |
| `storeId` | string | Sí | ID de la tienda |
| `affiliateId` | string | Sí | ID del afiliado |

***

## 📤 Body (JSON)

| Campo | Tipo | Obligatorio | Reglas |
| - | - | - | - |
| `name` | string | No | hasta 56 caracteres |
| `email` | string | No | correo válido, **único por tienda** (no puede repetir el de otro afiliado; comparación sin diferenciar mayúsculas) |
| `code` | string | No | slug único en minúsculas `^[a-z0-9]+(?:-[a-z0-9]+)*$` (3 a 50 caracteres) |
| `image` | string | No | URL `http`/`https` válida (hasta 512 caracteres); enviar `null` o `""` elimina la imagen |
| `status` | string | No | `activo` o `inativo` |
| `metadata` | object | No | datos adicionales/observaciones sobre el afiliado (máximo de 64 claves) |
| `commissionRules` | array | No | array no vacío con reglas de comisión: `[{ type, targetId, commission, position }]`. `type` ∈ `DEFAULT`, `PRODUCT`, `CATEGORY`, `COUPON`; `targetId` es el id del producto/categoría o el código del cupón (no aplica al `DEFAULT`); `commission` de 1 a 100; `position` es un entero `>= 0` y único por regla, definiendo la prioridad — **menor `position` vence** cuando varias reglas encajan. La regla `DEFAULT` encaja con cualquier venta y funciona como el **porcentaje por defecto** del afiliado (queda en la mayor `position`) |

***

## ✅ Ejemplo de solicitud

```bash theme={null}
curl -X PUT "https://api.cabrapi.com.br/v1/stores/STORE_ID/affiliates/AFFILIATE_ID" \
	-H "Authorization: TU_API_KEY_AQUI" \
	-H "Content-Type: application/json" \
	-d '{
		"name": "Bianca Rocha",
		"status": "ativo",
		"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
			}
		]
	}'
```

***

## 📦 Respuesta exitosa (200)

```json theme={null}
{
	"code": "AFFILIATE_UPDATED",
	"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
			}
		],
		"storeId": "STORE_ID",
		"createdAt": "2026-09-08T19:30:00Z",
		"updatedAt": "2026-09-08T19:30:00Z"
	}
}
```

***

## ⚠️ Posibles errores

* `400 INVALID_DATA` → body inválido
* `400 INVALID_DATA_NAME` → `name` fuera de 1 a 56 caracteres
* `400 INVALID_DATA_EMAIL` → `email` inválido o mayor de 120 caracteres
* `400 INVALID_DATA_IMAGE` → `image` inválida (URL `http`/`https` inválida o mayor de 512 caracteres)
* `400 INVALID_DATA_CODE` → `code` fuera de 3 a 50 caracteres o fuera del patrón slug
* `400 INVALID_DATA_STATUS` → `status` inválido (debe ser `ativo` o `inativo`)
* `400 INVALID_DATA_METADATA` → `metadata` inválido (no es un objeto o excede 64 claves)
* `400 INVALID_DATA_RULES` → `commissionRules` inválido (no es un array)
* `400 INVALID_COMMISSION_RULES` → `commissionRules` vacío
* `400 INVALID_COMMISSION_RULE_TYPE` → `type` inválido
* `400 INVALID_COMMISSION_RULE_POSITION` → `position` inválida/duplicada
* `400 INVALID_COMMISSION_VALUE` → `commission` fuera de 1 a 100
* `400 COMMISSION_RULE_DEFAULT_REQUIRED` → falta exactamente una regla `DEFAULT`
* `400 INVALID_COMMISSION_RULE_TARGET` → `DEFAULT` con `targetId`, o `PRODUCT`/`CATEGORY`/`COUPON` sin `targetId`
* `400 RELATION_NOT_FOUND` → `targetId` de producto/categoría/cupón inexistente en la tienda
* `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` → afiliado no encontrado
* `409 AFFILIATE_ALREADY_EXISTS` → `code` ya usado por otro afiliado
* `409 AFFILIATE_EMAIL_ALREADY_EXISTS` → correo ya registrado por otro afiliado en la tienda
* `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 PUT /stores/{storeId}/affiliates/{affiliateId}
openapi: 3.1.0
info:
  title: caBRAPI
  version: 1.0.0
servers:
  - url: https://api.cabrapi.com.br/v1
security: []
paths:
  /stores/{storeId}/affiliates/{affiliateId}:
    put:
      tags:
        - Affiliates
      summary: Update affiliate
      operationId: updateAffiliate
      parameters:
        - $ref: '#/components/parameters/StoreId'
        - $ref: '#/components/parameters/AffiliateId'
      requestBody:
        required: true
        description: Affiliate fields to update.
        content:
          application/json:
            schema:
              type: object
              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
                status:
                  enum:
                    - ativo
                    - inativo
                  type: string
                metadata:
                  type: object
                  maxProperties: 64
                  nullable: true
                commissionRules:
                  type: array
                  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
              minProperties: 1
      responses:
        '200':
          content:
            application/json:
              schema:
                properties:
                  code:
                    example: AFFILIATE_UPDATED
                    type: string
                  affiliate:
                    $ref: '#/components/schemas/Affiliate'
                required:
                  - code
                  - affiliate
                type: object
          description: Update 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
    AffiliateId:
      in: path
      name: affiliateId
      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.