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

# Configuración Inicial

> Configura tu entorno de desarrollo para integrar con NotMeta

## Requisitos previos

### Cuenta de NotMeta

* Cuenta de NotMeta activa
* Acceso de administrador o desarrollador
* WhatsApp Business API configurado

### Herramientas de desarrollo

* Cliente HTTP (Postman, curl, etc.)
* Editor de código
* Navegador web
* Acceso a terminal/consola

## Obtener credenciales de API

### 1. Acceder al panel de desarrolladores

1. Inicia sesión en tu cuenta de NotMeta
2. Ve a "Configuración" > "API"
3. Haz clic en "Generar token de API"

### 2. Configurar permisos

Selecciona los permisos necesarios para tu aplicación:

* **Conversaciones**: Leer y escribir mensajes
* **Usuarios**: Gestionar equipo
* **Reportes**: Acceder a métricas
* **Webhooks**: Configurar notificaciones
* **Configuración**: Modificar ajustes

### 3. Generar token

1. Ingresa un nombre descriptivo para tu token
2. Selecciona la fecha de expiración
3. Haz clic en "Generar token"
4. **Importante**: Copia y guarda el token de forma segura

## Configuración del entorno

### Variables de entorno

Crea un archivo `.env` con tus credenciales:

```bash theme={null}
NOTMETA_API_URL=https://api.notmeta.com
NOTMETA_API_TOKEN=tu_token_aqui
NOTMETA_WEBHOOK_SECRET=tu_secret_webhook
```

### Configuración de HTTPS

Para desarrollo local, puedes usar un túnel HTTPS:

```bash theme={null}
# Usando ngrok
ngrok http 3000

# Usando localtunnel
npx localtunnel --port 3000
```

## Primeras llamadas a la API

### Verificar conexión

```bash theme={null}
curl -X GET "https://api.notmeta.com/v1/health" \
  -H "Authorization: Bearer TU_TOKEN_AQUI" \
  -H "Content-Type: application/json"
```

### Obtener información de la cuenta

```bash theme={null}
curl -X GET "https://api.notmeta.com/v1/account" \
  -H "Authorization: Bearer TU_TOKEN_AQUI" \
  -H "Content-Type: application/json"
```

## Configuración de webhooks

### 1. Crear endpoint webhook

```javascript theme={null}
const express = require('express');
const app = express();

app.post('/webhook', (req, res) => {
  const signature = req.headers['x-notmeta-signature'];
  const payload = JSON.stringify(req.body);
  
  // Verificar firma del webhook
  if (verifyWebhookSignature(payload, signature)) {
    // Procesar evento
    handleWebhookEvent(req.body);
    res.status(200).send('OK');
  } else {
    res.status(400).send('Invalid signature');
  }
});

function verifyWebhookSignature(payload, signature) {
  const crypto = require('crypto');
  const expectedSignature = crypto
    .createHmac('sha256', process.env.NOTMETA_WEBHOOK_SECRET)
    .update(payload)
    .digest('hex');
  
  return signature === `sha256=${expectedSignature}`;
}
```

### 2. Registrar webhook

```bash theme={null}
curl -X POST "https://api.notmeta.com/v1/webhooks" \
  -H "Authorization: Bearer TU_TOKEN_AQUI" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://tu-dominio.com/webhook",
    "events": ["message.received", "conversation.assigned"]
  }'
```

## SDKs oficiales

### JavaScript/Node.js

```bash theme={null}
npm install @notmeta/sdk
```

```javascript theme={null}
const NotMeta = require('@notmeta/sdk');

const client = new NotMeta({
  apiToken: process.env.NOTMETA_API_TOKEN
});

// Enviar mensaje
const message = await client.messages.send({
  to: '1234567890',
  type: 'text',
  text: 'Hola, ¿cómo puedo ayudarte?'
});
```

### Python

```bash theme={null}
pip install notmeta-sdk
```

```python theme={null}
from notmeta import NotMeta

client = NotMeta(api_token='tu_token_aqui')

# Enviar mensaje
message = client.messages.send(
    to='1234567890',
    type='text',
    text='Hola, ¿cómo puedo ayudarte?'
)
```

### PHP

```bash theme={null}
composer require notmeta/notmeta-php
```

```php theme={null}
<?php
use NotMeta\NotMeta;

$client = new NotMeta([
    'api_token' => 'tu_token_aqui'
]);

// Enviar mensaje
$message = $client->messages->send([
    'to' => '1234567890',
    'type' => 'text',
    'text' => 'Hola, ¿cómo puedo ayudarte?'
]);
?>
```

## Herramientas de desarrollo

### Postman Collection

Importa nuestra colección de Postman para probar la API:

1. Descarga la colección desde [GitHub](https://github.com/notmeta/postman)
2. Importa en Postman
3. Configura las variables de entorno:
   * `base_url`: [https://api.notmeta.com](https://api.notmeta.com)
   * `api_token`: Tu token de API

### Testing

```javascript theme={null}
// Ejemplo de test con Jest
const NotMeta = require('@notmeta/sdk');

describe('NotMeta API', () => {
  let client;
  
  beforeAll(() => {
    client = new NotMeta({
      apiToken: process.env.NOTMETA_API_TOKEN
    });
  });
  
  test('should send message', async () => {
    const response = await client.messages.send({
      to: '1234567890',
      type: 'text',
      text: 'Test message'
    });
    
    expect(response.id).toBeDefined();
  });
});
```

## Mejores prácticas

### Seguridad

* Nunca hardcodees tokens en el código
* Usa variables de entorno para credenciales
* Implementa verificación de firmas de webhooks
* Usa HTTPS en producción

### Manejo de errores

```javascript theme={null}
try {
  const response = await client.messages.send(messageData);
} catch (error) {
  if (error.status === 401) {
    // Token inválido
    console.error('Error de autenticación');
  } else if (error.status === 429) {
    // Rate limit excedido
    console.error('Demasiadas solicitudes');
  } else {
    console.error('Error inesperado:', error.message);
  }
}
```

### Rate limiting

```javascript theme={null}
// Implementar retry con backoff exponencial
async function sendWithRetry(messageData, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await client.messages.send(messageData);
    } catch (error) {
      if (error.status === 429 && i < maxRetries - 1) {
        const delay = Math.pow(2, i) * 1000;
        await new Promise(resolve => setTimeout(resolve, delay));
      } else {
        throw error;
      }
    }
  }
}
```

## Solución de problemas

### Error 401: Unauthorized

* Verifica que tu token sea válido
* Confirma que el token no haya expirado
* Revisa los permisos asignados al token

### Error 429: Too Many Requests

* Implementa backoff exponencial
* Reduce la frecuencia de las solicitudes
* Considera usar webhooks en lugar de polling

### Error 500: Internal Server Error

* Verifica el formato de tu solicitud
* Contacta soporte técnico si persiste
* Revisa el estado del servicio

## Recursos adicionales

<Card title="Autenticación" icon="key" href="/developers/authentication">
  Aprende sobre los diferentes métodos de autenticación
</Card>

<Card title="Webhooks" icon="webhook" href="/developers/webhooks">
  Configura notificaciones en tiempo real
</Card>
