# Zapier integration

There are two ways to use it:
- **A. the Tricid Zapier app** (`integrations/zapier-app/`), a Zapier Platform CLI app;
- **B. built-in recipes** with Webhooks by Zapier and Code by Zapier, which need no app.


## A. Zapier Platform app (`integrations/zapier-app`)

| Trigger / action | Tricid app key | Behaviour |
|---|---|---|
| New Image / New PDF / New Video (instant) | `new_image`, `new_pdf`, `new_video` | **REST hooks** on project webhooks. Turning the Zap on subscribes its target URL (`POST /api/rest/webhooks`, event `image.finished` etc.); turning it off unsubscribes it (`DELETE`). The trigger fires for **every** finished creative of that kind in the project. Deliveries are verified with the subscription secret (`X-Render-Signature`). `performList` loads recent jobs for the Zap editor from `GET /api/rest/{kind}s?limit=3` once the API offers it; until then Zapier shows the static sample |
| Create Image / PDF / Video | `create_image`, `create_pdf`, `create_video` | Pick a **Template** from a dropdown (paginated, title + tags). The form then shows **one field per dynamic layer property** (e.g. `TITLE › text`, `PIC › image`), with Instruct AI layer descriptions as help text, plus a *hide* switch per layer. In videos, text and image are **list** fields. Options: Output Mode (final or free preview), Passthrough, Layers (JSON) merged over the fields. Images: width/height/format/filename. PDFs: Additional Pages (JSON), DPI, image quality. Videos: audio, Additional Clips (JSON), size, fps, canvas background |
| Get Image / PDF / Video | `get_image`, `get_pdf`, `get_video` (searches) | By id; returns nothing when not found |
| Convert File to URL | `convert_file_to_url` | Downloads the file from the earlier step (**without** the API token) and uploads it to `POST /api/rest/media` as multipart. Returns a media URL for picture layers |

**Connection.** Two fields: *Base URL* and *API Token*. The test call is `GET /api/rest/me`, and the
connection is labelled with the project name. The token is sent only to the Base URL's origin.

**Time limit.** Zapier stops an action after about 30 s. Images use `create_now` and are usually returned
finished. PDFs and videos are polled for 25 s; if they are still queued, the step returns `status: queued`
with the id, and *Get …* or the instant trigger picks them up.

**Errors.** The API's `error_message` and `error_details` become the Zapier error text. 429 is mapped to
`ThrottledError`, so Zapier retries after `Retry-After`.

### Build, test, deploy
```bash
pnpm --filter zapier-tricid test        # tsc build + appTester/nock tests + schema validation
cd integrations/zapier-app
npx zapier-platform-cli validate --without-style   # offline schema validation through the real CLI
npx zapier-platform-cli login && npx zapier-platform-cli register "Tricid" && npx zapier-platform-cli push   # needs a Zapier account
```
The app is TypeScript (`src/`). It compiles to CommonJS in `lib/`, and `index.js` re-exports that, as Zapier expects.

## B. Recipes without the app

### Action: Create an image, PDF or video
Step *Webhooks by Zapier → Custom Request*:
- Method `POST`, URL `https://render.example.com/api/rest/images` (or `/pdfs`, `/videos`)
- Headers:
  - `Authorization` = `Bearer <project API token>`
  - `Content-Type` = `application/json`
- Data (raw JSON):
  ```json
  { "template_uuid": "abc123def456x", "layers": { "TITLE": { "text": "{{title}}" }, "PIC": { "image": "{{photo_url}}" } }, "create_now": true }
  ```
With `create_now: true`, images usually come back already `finished`, with `image_url`.

### Action: Get Image / PDF / Video
*Webhooks by Zapier → GET* `{{polling_url}}` with the same `Authorization` header.

### Trigger: New Image / PDF / Video
Use *Webhooks by Zapier → Catch Raw Hook*, then subscribe its URL once:
```bash
curl -X POST https://render.example.com/api/rest/webhooks -H "Authorization: Bearer <token>" -H "Content-Type: application/json" \
  -d '{"url":"<Catch Raw Hook URL>","events":["image.finished","pdf.finished","video.finished"]}'
# -> {"id":"…","secret":"whsec_…",…}
```
To verify the signature, add a *Code by Zapier* step:
```js
const crypto = require('crypto');
const h = Object.fromEntries((inputData.signature || '').split(',').map((p) => p.split('=')));
const expected = crypto.createHmac('sha256', inputData.secret).update(`${h.t}.${inputData.raw_body}`).digest('hex');
if (!h.v1 || !crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(h.v1))) throw new Error('bad signature');
return JSON.parse(inputData.raw_body);
```
