# Criar modelos com imagem, documento e botões

`POST /v1/templates/media`

**Monte o modelo pelo seu sistema, mostre a prévia ao seu cliente e envie para aprovação.** Quatro chamadas, e nenhuma envia mensagem:

1. **`POST /v1/templates/media`** — o arquivo de **amostra** que a Meta revisa (PDF, JPG/PNG ou MP4; multipart com `file`, ou JSON com `file` em base64). Devolve `{ handle, type, format, mimeType, bytes }`. Não é o arquivo que se envia: esse vai em cada envio, por `link` ou `mediaId`. Não guardamos o arquivo.
2. **`POST /v1/templates/validate`** — a mesma checagem de criar, **sem enviar nada à Meta**: `ok`, e em `errors[]` todos os problemas juntos, cada um com seu `field` (`header.handle`, `buttons[1].url`…) e a mensagem no seu idioma.
3. **`POST /v1/templates`** — `header: { "format": "IMAGE", "handle": "…" }` (também `VIDEO`, `DOCUMENT` e `LOCATION`) e `buttons`: `QUICK_REPLY` (`text`), `URL` (`text`, `url` e, se terminar em `{{1}}`, `example` com o final de exemplo), `PHONE_NUMBER` (`text`, `phoneNumber` com código do país) e `COPY_CODE` (`example`). Nasce `PENDING`; **`template.status_changed`** avisa (com `previousStatus`).
4. **`POST /v1/templates/preview?format=html`** — uma página autocontida com o balão do WhatsApp (sem scripts nem recursos externos) para mostrar ao seu cliente num `<iframe sandbox>`. Sem `format`, a mesma visão em JSON.

**Os limites da Meta, checados antes da Meta:** até 10 botões, 2 de URL, 1 de telefone, 1 de copiar código; o texto de um botão até 25 caracteres; as respostas rápidas juntas (no início ou no fim). Se a conta da Meta tiver `141006` (forma de pagamento) ou `141010` (verificação do negócio), o modelo é criado igual e a resposta traz um `warning`: a Meta pode aprová-lo, mas você não vai conseguir enviá-lo até resolver.

## Exemplos

### cURL

```bash
# 1) The sample file Meta reviews (PDF, JPG/PNG or MP4) → its handle
HANDLE=$(curl -s -X POST https://api.waiaconnect.com/v1/templates/media   -H "Authorization: Bearer wc_live_YOUR_API_KEY"   -F file=@foto.png | jq -r .handle)

# 2) Validate: every error at once, nothing sent to Meta
BODY='{"connectionId":"conn_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX","name":"envio_factura","language":"es","category":"UTILITY","header":{"format":"IMAGE","handle":"HANDLE"},"body":{"text":"Hola {{1}}, tu factura *{{2}}* está lista.","examples":["María","A-1042"]},"footer":{"text":"Tu negocio"},"buttons":[{"type":"QUICK_REPLY","text":"Recibido"},{"type":"URL","text":"Ver factura","url":"https://your-site.example/f/{{1}}","example":"A-1042"},{"type":"PHONE_NUMBER","text":"Llamar","phoneNumber":"+5493511234567"}]}'
BODY=${BODY/HANDLE/$HANDLE}
curl -s -X POST https://api.waiaconnect.com/v1/templates/validate -H "Authorization: Bearer wc_live_YOUR_API_KEY"   -H "Content-Type: application/json" -d "$BODY"
# → { "ok": true, "errors": [], "warnings": [], "components": [...] }

# 3) Create it (born PENDING; template.status_changed tells you when Meta decides)
curl -s -X POST https://api.waiaconnect.com/v1/templates -H "Authorization: Bearer wc_live_YOUR_API_KEY"   -H "Content-Type: application/json" -d "$BODY"

# 4) The WhatsApp-style preview for your customer (self-contained HTML)
curl -s -X POST "https://api.waiaconnect.com/v1/templates/preview?format=html" -H "Authorization: Bearer wc_live_YOUR_API_KEY"   -H "Content-Type: application/json" -d "$BODY" > preview.html
```

### Node.js

```javascript
import { readFile } from "node:fs/promises";
const H = { Authorization: "Bearer wc_live_YOUR_API_KEY" };
const J = { ...H, "Content-Type": "application/json" };

// 1) The sample file Meta reviews (PDF, JPG/PNG or MP4) → its handle
const form = new FormData();
form.append("file", new Blob([await readFile("foto.png")]), "foto.png");
const { handle } = await (await fetch("https://api.waiaconnect.com/v1/templates/media", { method: "POST", headers: H, body: form })).json();

const def = {
  "connectionId": "conn_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "name": "envio_factura",
  "language": "es",
  "category": "UTILITY",
  "header": {
    "format": "IMAGE",
    "handle": handle
  },
  "body": {
    "text": "Hola {{1}}, tu factura *{{2}}* está lista.",
    "examples": [
      "María",
      "A-1042"
    ]
  },
  "footer": {
    "text": "Tu negocio"
  },
  "buttons": [
    {
      "type": "QUICK_REPLY",
      "text": "Recibido"
    },
    {
      "type": "URL",
      "text": "Ver factura",
      "url": "https://your-site.example/f/{{1}}",
      "example": "A-1042"
    },
    {
      "type": "PHONE_NUMBER",
      "text": "Llamar",
      "phoneNumber": "+5493511234567"
    }
  ]
};

// 2) Validate: every error at once, nothing sent to Meta
const v = await (await fetch("https://api.waiaconnect.com/v1/templates/validate", { method: "POST", headers: J, body: JSON.stringify(def) })).json();
if (!v.ok) throw new Error(v.errors.map(e => `${e.field}: ${e.message}`).join("\n"));

// 3) Create it (PENDING until Meta decides → template.status_changed)
const created = await (await fetch("https://api.waiaconnect.com/v1/templates", { method: "POST", headers: J, body: JSON.stringify(def) })).json();

// 4) The WhatsApp-style preview (self-contained HTML, show it in an <iframe sandbox>)
const html = await (await fetch("https://api.waiaconnect.com/v1/templates/preview?format=html", { method: "POST", headers: J, body: JSON.stringify(def) })).text();
console.log(created.template.status, created.warning?.message ?? "");
```

### PHP

```php
<?php
$key = "wc_live_YOUR_API_KEY";
function call($method, $url, $key, $body, $json = true) {
  $ch = curl_init($url);
  curl_setopt_array($ch, [
    CURLOPT_CUSTOMREQUEST => $method,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => array_merge(["Authorization: Bearer $key"], $json ? ["Content-Type: application/json"] : []),
    CURLOPT_POSTFIELDS => $json ? json_encode($body) : $body,
  ]);
  return curl_exec($ch);
}
// 1) The sample file Meta reviews (PDF, JPG/PNG or MP4) → its handle
$handle = json_decode(call("POST", "https://api.waiaconnect.com/v1/templates/media", $key, ["file" => new CURLFile("foto.png")], false), true)["handle"];

$def = ["connectionId" => "conn_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX","name" => "envio_factura","language" => "es","category" => "UTILITY","header" => ["format" => "IMAGE","handle" => $handle],"body" => ["text" => "Hola {{1}}, tu factura *{{2}}* está lista.","examples" => ["María","A-1042"]],"footer" => ["text" => "Tu negocio"],"buttons" => [["type" => "QUICK_REPLY","text" => "Recibido"],["type" => "URL","text" => "Ver factura","url" => "https://your-site.example/f/{{1}}","example" => "A-1042"],["type" => "PHONE_NUMBER","text" => "Llamar","phoneNumber" => "+5493511234567"]]];

// 2) Validate (nothing sent to Meta) · 3) create · 4) the HTML preview
$v = json_decode(call("POST", "https://api.waiaconnect.com/v1/templates/validate", $key, $def), true);
if (!$v["ok"]) { print_r($v["errors"]); exit; }
echo call("POST", "https://api.waiaconnect.com/v1/templates", $key, $def);
file_put_contents("preview.html", call("POST", "https://api.waiaconnect.com/v1/templates/preview?format=html", $key, $def));
```

### Python

```python
import requests
H = {"Authorization": "Bearer wc_live_YOUR_API_KEY"}

# 1) The sample file Meta reviews (PDF, JPG/PNG or MP4) -> its handle
handle = requests.post("https://api.waiaconnect.com/v1/templates/media", headers=H, files={"file": open("foto.png", "rb")}).json()["handle"]

definition = {"connectionId":"conn_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX","name":"envio_factura","language":"es","category":"UTILITY","header":{"format":"IMAGE","handle":handle},"body":{"text":"Hola {{1}}, tu factura *{{2}}* está lista.","examples":["María","A-1042"]},"footer":{"text":"Tu negocio"},"buttons":[{"type":"QUICK_REPLY","text":"Recibido"},{"type":"URL","text":"Ver factura","url":"https://your-site.example/f/{{1}}","example":"A-1042"},{"type":"PHONE_NUMBER","text":"Llamar","phoneNumber":"+5493511234567"}]}

# 2) Validate: every error at once, nothing sent to Meta
v = requests.post("https://api.waiaconnect.com/v1/templates/validate", headers=H, json=definition).json()
if not v["ok"]:
    raise SystemExit("\n".join(f"{e['field']}: {e['message']}" for e in v["errors"]))

# 3) Create it (PENDING until Meta decides -> template.status_changed)
created = requests.post("https://api.waiaconnect.com/v1/templates", headers=H, json=definition).json()

# 4) The WhatsApp-style preview (self-contained HTML)
open("preview.html", "w").write(requests.post("https://api.waiaconnect.com/v1/templates/preview", params={"format": "html"}, headers=H, json=definition).text)
```

## Notas

- Para mudá-lo depois: `PATCH /v1/templates/:id` (aprovado, rejeitado ou pausado; o aprovado 1 vez a cada 24 h e com a mesma categoria).
- Com 4 botões ou mais, o WhatsApp mostra 2 e «Ver todas as opções»: a prévia desenha igual.
