# 4send — Exemplos de código

Base URL: `https://api.4send.me/v1` · Auth: `Authorization: Bearer <api_key>`

## Enviar um WhatsApp

### cURL
```bash
curl -X POST https://api.4send.me/v1/messages \
  -H "Authorization: Bearer $FOURSEND_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $(uuidgen)" \
  -d '{
    "channel": "whatsapp",
    "to": { "phone": "+5551999999999" },
    "whatsapp": { "body": "Olá {{nome}}! Seu pedido saiu 🚚" },
    "variables": { "nome": "João" }
  }'
```

### Node.js
```javascript
import { randomUUID } from 'node:crypto';

const API = 'https://api.4send.me/v1';
const KEY = process.env.FOURSEND_API_KEY;

async function sendWhatsapp(phone, body, variables = {}) {
  const res = await fetch(`${API}/messages`, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${KEY}`,
      'Content-Type': 'application/json',
      'Idempotency-Key': randomUUID(),
    },
    body: JSON.stringify({ channel: 'whatsapp', to: { phone }, whatsapp: { body }, variables }),
  });
  if (!res.ok) throw new Error((await res.json()).error?.message || res.statusText);
  return res.json(); // { id: "msg_...", status: "queued", ... }
}

// status depois:
async function getMessage(id) {
  const res = await fetch(`${API}/messages/${id}`, { headers: { Authorization: `Bearer ${KEY}` } });
  return res.json();
}
```

### Python
```python
import os, uuid, requests

API = "https://api.4send.me/v1"
KEY = os.environ["FOURSEND_API_KEY"]

def send_whatsapp(phone, body, variables=None):
    r = requests.post(
        f"{API}/messages",
        headers={
            "Authorization": f"Bearer {KEY}",
            "Idempotency-Key": str(uuid.uuid4()),
        },
        json={"channel": "whatsapp", "to": {"phone": phone},
              "whatsapp": {"body": body}, "variables": variables or {}},
    )
    r.raise_for_status()
    return r.json()
```

## Enviar um e-mail
```bash
curl -X POST https://api.4send.me/v1/messages \
  -H "Authorization: Bearer $FOURSEND_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "channel": "email",
    "to": { "email": "joao@exemplo.com" },
    "email": { "subject": "Seu pedido saiu", "html": "<h1>Olá, {{nome}}!</h1>" },
    "variables": { "nome": "João" }
  }'
```

## Criar contato e colocar num fluxo
```bash
# 1) cria/atualiza o contato
curl -X POST https://api.4send.me/v1/contacts \
  -H "Authorization: Bearer $FOURSEND_API_KEY" -H "Content-Type: application/json" \
  -d '{ "phone": "+5551999999999", "name": "João", "fields": { "plano": "gold" } }'

# 2) descobre os fluxos ativos
curl https://api.4send.me/v1/flows -H "Authorization: Bearer $FOURSEND_API_KEY"

# 3) matricula o contato no fluxo
curl -X POST https://api.4send.me/v1/flows/flow_663f.../enroll \
  -H "Authorization: Bearer $FOURSEND_API_KEY" -H "Content-Type: application/json" \
  -d '{ "to": { "phone": "+5551999999999" }, "variables": { "nome": "João" } }'
```

## Dica de fluxo típico (CRM → 4send)
Evento no seu sistema (ex.: pedido criado) → chame `POST /messages` (aviso na hora)
ou `POST /flows/{id}/enroll` (jornada). Assine os webhooks pra saber quando foi
entregue/lido. Use `4s_test_` enquanto desenvolve.
