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

# Autenticación

> Cómo autenticarte con la API de Whaapy

# Autenticación

La API de Whaapy usa **API Keys** para autenticación. Cada request debe incluir tu API Key en el header `Authorization`.

## Formato del Header

```http theme={null}
Authorization: Bearer wha_TU_API_KEY
Content-Type: application/json
```

## Obtener tu API Key

<Steps>
  <Step title="Inicia sesión">
    Ve a [app.whaapy.com](https://app.whaapy.com) e inicia sesión
  </Step>

  <Step title="Navega a Configuración">
    Click en **Configuración** en el menú lateral
  </Step>

  <Step title="API Keys">
    Selecciona la pestaña **API Keys**
  </Step>

  <Step title="Genera una nueva key">
    Click en **Generar Nueva Key** y copia el valor
  </Step>
</Steps>

## Formato de API Key

Las API Keys de Whaapy tienen el formato:

```
wha_XXXXXXXXXXXXXXXXXXXXXXXXXXXXX
```

<Warning>
  **Mantén tu API Key segura**

  * Nunca compartas tu API Key públicamente
  * No la incluyas en código del lado del cliente (frontend, apps móviles)
  * Usa variables de entorno para almacenarla
  * Rota tu key periódicamente
</Warning>

## Scopes y Permisos

Cada API Key puede tener diferentes scopes que limitan qué acciones puede realizar:

| Scope                | Permisos                   |
| -------------------- | -------------------------- |
| `messages:write`     | Enviar mensajes            |
| `messages:read`      | Leer historial de mensajes |
| `conversations:read` | Listar conversaciones      |
| `contacts:read`      | Leer contactos             |
| `contacts:write`     | Crear/actualizar contactos |

<Tip>
  Usa el principio de **mínimo privilegio**: solo otorga los scopes que tu aplicación necesita.
</Tip>

## Ejemplo de Request Autenticado

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST https://api.whaapy.com/messages/v1 \
    -H "Authorization: Bearer wha_SUfMm4ZpqYlyvTdtxGU4UjeeNeNYR94T" \
    -H "Content-Type: application/json" \
    -d '{"to": "+5215512345678", "content": "Hola!"}'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('https://api.whaapy.com/messages/v1', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer wha_TU_API_KEY',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      to: '+5215512345678',
      content: 'Hola!'
    })
  });
  ```

  ```python Python theme={null}
  import requests

  response = requests.post(
      'https://api.whaapy.com/messages/v1',
      headers={
          'Authorization': 'Bearer wha_TU_API_KEY',
          'Content-Type': 'application/json'
      },
      json={
          'to': '+5215512345678',
          'content': 'Hola!'
      }
  )
  ```

  ```php PHP theme={null}
  $ch = curl_init('https://api.whaapy.com/messages/v1');
  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_HTTPHEADER, [
      'Authorization: Bearer wha_TU_API_KEY',
      'Content-Type: application/json'
  ]);
  curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
      'to' => '+5215512345678',
      'content' => 'Hola!'
  ]));
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  $response = curl_exec($ch);
  ```
</CodeGroup>

## Errores de Autenticación

### 401 Unauthorized

```json theme={null}
{
  "error": "unauthorized",
  "message": "API Key inválida o faltante"
}
```

**Causas comunes:**

* API Key no incluida en el header
* Formato incorrecto (falta `Bearer `)
* API Key revocada o expirada

### 403 Forbidden

```json theme={null}
{
  "error": "forbidden",
  "message": "Sin permisos para este scope"
}
```

**Causas comunes:**

* La API Key no tiene el scope requerido
* Intentando acceder a recursos de otra cuenta

## Variables de Entorno

Recomendamos almacenar tu API Key en variables de entorno:

```bash .env theme={null}
WHAAPY_API_KEY=wha_TU_API_KEY
```

```javascript Node.js theme={null}
const apiKey = process.env.WHAAPY_API_KEY;
```

```python Python theme={null}
import os
api_key = os.environ.get('WHAAPY_API_KEY')
```

## Rotar API Key

Si sospechas que tu API Key fue comprometida:

1. Ve a **Configuración** → **API Keys**
2. Click en **Revocar** junto a la key comprometida
3. Genera una nueva key
4. Actualiza tu aplicación con la nueva key

<Note>
  Revocar una key es instantáneo. Cualquier request con la key revocada fallará inmediatamente.
</Note>
