# Create templates with an image, document and buttons

`POST /v1/templates/media`

**Build the template from your system, show your customer the preview and send it to review.** Four calls, none of them sends a message:

1. **`POST /v1/templates/media`** — the **sample** file Meta reviews (PDF, JPG/PNG or MP4; multipart with `file`, or JSON with `file` in base64). Returns `{ handle, type, format, mimeType, bytes }`. It isn't the file you send: that one goes with every send, by `link` or `mediaId`. We don't keep the file.
2. **`POST /v1/templates/validate`** — the same check as create, **nothing sent to Meta**: `ok`, and in `errors[]` every problem at once, each with its `field` (`header.handle`, `buttons[1].url`…) and the message in your language.
3. **`POST /v1/templates`** — `header: { "format": "IMAGE", "handle": "…" }` (also `VIDEO`, `DOCUMENT` and `LOCATION`) and `buttons`: `QUICK_REPLY` (`text`), `URL` (`text`, `url`, and if it ends in `{{1}}`, `example` with a sample ending), `PHONE_NUMBER` (`text`, `phoneNumber` with country code) and `COPY_CODE` (`example`). Born `PENDING`; **`template.status_changed`** tells you (with `previousStatus`).
4. **`POST /v1/templates/preview?format=html`** — a self-contained page with the WhatsApp bubble (no scripts, no outside resources) to show your customer in an `<iframe sandbox>`. Without `format`, the same view as JSON.

**Meta's limits, checked before Meta:** up to 10 buttons, 2 URL, 1 phone, 1 copy-code; button text up to 25 characters; quick replies grouped (first or last). If the Meta account has `141006` (payment method) or `141010` (business verification), the template is still created and the answer carries a `warning`: Meta may approve it, but you won't be able to send it until that's fixed.

## Examples

### 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)
```

## Notes

- To change it later: `PATCH /v1/templates/:id` (approved, rejected or paused; an approved one once every 24 h and with the same category).
- With 4 buttons or more, WhatsApp shows 2 and "See all options": the preview draws it the same way.
