# Code samples

Everything below works with the REST API, URL API and
signed URL API examples, then PHP, Python and Ruby.

Placeholders:

| Placeholder | Meaning |
|---|---|
| `https://render.example.com` | Your Tricid server (local dev: `http://localhost:4000`) |
| `$TOKEN` / `<token>` | Project API token. Studio → project → API tokens. Shown once. |
| `abc123def456x` | Template uuid. Studio → template → Integrate, or `GET /api/rest/templates`. |
| `TITLE`, `PIC` | Dynamic layer names, as returned in `layers[]` of the template object |
| `<url-signing-key>` | The project URL-signing secret. Studio → project → URL signing. Server-side only. |
| `<webhook-secret>` | The project webhook secret. Studio → project settings. |

## 1. REST API (cURL)

### Create an image, then poll it
```bash
curl -s https://render.example.com/api/rest/images \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: order-1234" \
  -d '{
    "template_uuid": "abc123def456x",
    "layers": {
      "TITLE": { "text": "Meet Singh" },
      "PIC":   { "image": "https://example.com/photo.jpg" }
    },
    "modifications": { "width": 1080, "image_format": "png" },
    "webhook_success": "https://example.com/hooks/render",
    "passthrough": "order-1234"
  }'
# -> {"id":42,"status":"queued","image_url":null,"polling_url":"https://render.example.com/api/rest/images/42",...}

curl -s https://render.example.com/api/rest/images/42 -H "Authorization: Bearer $TOKEN"
# -> {"id":42,"status":"finished","image_url":"https://render.example.com/files/...","error_code":null,...}
```
`Idempotency-Key` is optional (a Tricid extension). When you repeat a request with the same key,
you get the same job back instead of a second render. Use it whenever you retry.
Add `"create_now": true` to render immediately (limit: 10 at the same time). The reply is then usually already `finished`.

### PDF (one page per template, merged in order)
```bash
curl -s https://render.example.com/api/rest/pdfs \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d '{
    "pages": [
      { "template_uuid": "abc123def456x", "layers": { "TITLE": { "text": "Page 1" } } },
      { "template_uuid": "abc123def456x", "layers": { "TITLE": { "text": "Page 2" } } }
    ],
    "modifications": { "filename": "certificate.pdf", "dpi": 300 }
  }'
```

### Video (clips; text and image may be arrays)
```bash
curl -s https://render.example.com/api/rest/videos \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d '{
    "clips": [
      {
        "template_uuid": "abc123def456x",
        "layers": { "TITLE": { "text": ["First", "Second", "Third"] }, "PIC": { "video": "https://example.com/clip.mp4" } },
        "audio": "https://example.com/track.mp3",
        "audio_duration": "auto"
      }
    ],
    "modifications": { "fps": 25, "canvas_background": "blur" }
  }'
```

### Upload media, list templates
```bash
curl -s https://render.example.com/api/rest/media -H "Authorization: Bearer $TOKEN" \
  -F "file=@photo.jpg" -F "file2=@logo.png"
# -> {"media":[{"file_key":"file","file_id":"https://render.example.com/files/media/..."},...]}

curl -s "https://render.example.com/api/rest/templates?tag=social&order_by=title-asc" -H "Authorization: Bearer $TOKEN"
```

## 2. URL API (images only)

```text
https://render.example.com/u/abc123def456x?TITLE[text]=Hello%20friend%21&PIC[image]=https%3A%2F%2Fexample.com%2Fphoto.jpg
```
On the first request the image is rendered and cached. Later requests with the same parameters are served from the cache.

### Signed URL
The signature is the lowercase hex `HMAC-SHA256(key, query_string)`. It is appended as the **last** parameter,
`&s=`. Only the query is signed, not the path. You may add `bw_expires=<unix seconds>` before signing (a
Tricid extension) so that the URL stops working at that time.

```text
query     = TITLE[text]=Hello
signature = hex(hmac_sha256("<url-signing-key>", "TITLE[text]=Hello"))
url       = https://render.example.com/u/abc123def456x?TITLE[text]=Hello&s=<signature>
```
Never sign in the browser. The key must stay on your server.

## 3. PHP

```php
<?php
$base  = 'https://render.example.com';
$token = getenv('TRICID_TOKEN');

function br_request(string $method, string $url, ?array $body, string $token): array {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_CUSTOMREQUEST  => $method,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER     => ['Authorization: Bearer ' . $token, 'Content-Type: application/json', 'Accept: application/json'],
        CURLOPT_POSTFIELDS     => $body === null ? null : json_encode($body),
    ]);
    $res = curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    $json = json_decode($res, true);
    if ($status >= 400) throw new RuntimeException("HTTP $status {$json['error_code']}: {$json['error_message']}");
    return $json;
}

// Create, then poll until finished
$image = br_request('POST', "$base/api/rest/images", [
    'template_uuid' => 'abc123def456x',
    'layers' => ['TITLE' => ['text' => 'Meet Singh'], 'PIC' => ['image' => 'https://example.com/photo.jpg']],
], $token);
while ($image['status'] === 'queued') {
    sleep(2);
    $image = br_request('GET', $image['polling_url'], null, $token);
}
if ($image['status'] === 'error') throw new RuntimeException("{$image['error_code']}: {$image['error_message']}");
echo $image['image_url'], PHP_EOL;

// Signed URL API link
$query     = 'TITLE[text]=' . rawurlencode('Hello friend!');
$signature = hash_hmac('sha256', $query, getenv('TRICID_URL_SIGNING_KEY'));
echo "$base/u/abc123def456x?$query&s=$signature", PHP_EOL;

// Verify a webhook (raw body!)
function br_verify_webhook(string $rawBody, string $header, string $secret, int $tolerance = 300): bool {
    parse_str(str_replace(',', '&', $header), $p);          // t=..., v1=...
    if (empty($p['t']) || empty($p['v1'])) return false;
    $expected = hash_hmac('sha256', $p['t'] . '.' . $rawBody, $secret);
    return hash_equals($expected, $p['v1']) && abs(time() - (int)$p['t']) <= $tolerance;
}
// $ok = br_verify_webhook(file_get_contents('php://input'), $_SERVER['HTTP_X_RENDER_SIGNATURE'] ?? '', getenv('TRICID_WEBHOOK_SECRET'));
```

## 4. Python (standard library only)

```python
import hashlib, hmac, json, os, time, urllib.parse, urllib.request

BASE = "https://render.example.com"
TOKEN = os.environ["TRICID_TOKEN"]

def br(method, url, body=None):
    req = urllib.request.Request(
        url if url.startswith("http") else f"{BASE}/api/rest{url}",
        method=method,
        data=None if body is None else json.dumps(body).encode(),
        headers={"Authorization": f"Bearer {TOKEN}", "Content-Type": "application/json", "Accept": "application/json"},
    )
    try:
        with urllib.request.urlopen(req) as r:
            raw = r.read()
            return json.loads(raw) if raw else None
    except urllib.error.HTTPError as e:
        err = json.loads(e.read() or b"{}")
        raise RuntimeError(f"HTTP {e.code} {err.get('error_code')}: {err.get('error_message')}") from None

def create_and_wait(kind, body, timeout=120):
    job = br("POST", f"/{kind}", body)
    delay, start = 0.5, time.time()
    while job["status"] == "queued":
        if time.time() - start > timeout:
            raise TimeoutError(f"job {job['id']} still queued")
        time.sleep(delay)
        delay = min(5, delay * 1.5)
        job = br("GET", job["polling_url"])
    if job["status"] == "error":
        raise RuntimeError(f"{job['error_code']}: {job['error_message']} {job['error_details']}")
    return job

image = create_and_wait("images", {
    "template_uuid": "abc123def456x",
    "layers": {"TITLE": {"text": "Meet Singh"}, "PIC": {"image": "https://example.com/photo.jpg"}},
})
print(image["image_url"])

def signed_url(template_uuid, layers, key, expires_at=None):
    parts = [f"{urllib.parse.quote(l, safe='')}[{urllib.parse.quote(p, safe='')}]={urllib.parse.quote(str(v), safe='')}"
             for l, props in layers.items() for p, v in props.items()]
    if expires_at is not None:
        parts.append(f"bw_expires={int(expires_at)}")
    query = "&".join(parts)
    sig = hmac.new(key.encode(), query.encode(), hashlib.sha256).hexdigest()
    return f"{BASE}/u/{template_uuid}?{query}&s={sig}"

def verify_webhook(raw_body: bytes, header: str, secret: str, tolerance=300) -> bool:
    fields = dict(p.split("=", 1) for p in header.split(",") if "=" in p)
    t, v1 = fields.get("t"), fields.get("v1")
    if not t or not v1:
        return False
    expected = hmac.new(secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, v1) and abs(time.time() - int(t)) <= tolerance
```

## 5. Ruby (standard library only)

```ruby
require "net/http"
require "json"
require "openssl"
require "erb"

BASE  = "https://render.example.com"
TOKEN = ENV.fetch("TRICID_TOKEN")

def br(method, url, body = nil)
  uri = URI(url.start_with?("http") ? url : "#{BASE}/api/rest#{url}")
  req = Net::HTTP.const_get(method.capitalize).new(uri)
  req["Authorization"] = "Bearer #{TOKEN}"
  req["Content-Type"] = "application/json"
  req.body = body.to_json if body
  res = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https") { |h| h.request(req) }
  json = res.body.to_s.empty? ? nil : JSON.parse(res.body)
  raise "HTTP #{res.code} #{json && json['error_code']}: #{json && json['error_message']}" if res.code.to_i >= 400
  json
end

image = br("POST", "/images", {
  template_uuid: "abc123def456x",
  layers: { "TITLE" => { text: "Meet Singh" }, "PIC" => { image: "https://example.com/photo.jpg" } }
})
delay = 0.5
while image["status"] == "queued"
  sleep delay
  delay = [delay * 1.5, 5].min
  image = br("GET", image["polling_url"])
end
raise "#{image['error_code']}: #{image['error_message']}" if image["status"] == "error"
puts image["image_url"]

# Signed URL API link
query = "TITLE[text]=#{ERB::Util.url_encode('Hello friend!')}"
sig   = OpenSSL::HMAC.hexdigest("SHA256", ENV.fetch("TRICID_URL_SIGNING_KEY"), query)
puts "#{BASE}/u/abc123def456x?#{query}&s=#{sig}"

# Verify a webhook (raw body)
def verify_webhook(raw_body, header, secret, tolerance = 300)
  f = header.to_s.split(",").map { |p| p.split("=", 2) }.to_h
  return false unless f["t"] && f["v1"]
  expected = OpenSSL::HMAC.hexdigest("SHA256", secret, "#{f['t']}.#{raw_body}")
  OpenSSL.secure_compare(expected, f["v1"]) && (Time.now.to_i - f["t"].to_i).abs <= tolerance
end
```

## 6. JavaScript / TypeScript (`tricid` SDK)

```ts
import { Tricid, buildUrlApiUrl, verifyWebhookSignature } from 'tricid';

const br = new Tricid({ token: process.env.TRICID_TOKEN!, baseUrl: 'https://render.example.com' });
const image = await br.images.createAndWait({
  template_uuid: 'abc123def456x',
  layers: { TITLE: { text: 'Meet Singh' }, PIC: { image: 'https://example.com/photo.jpg' } },
});
console.log(image.image_url);

const link = buildUrlApiUrl({ baseUrl: 'https://render.example.com', templateUuid: 'abc123def456x', layers: { TITLE: { text: 'Hello' } }, signingKey: process.env.TRICID_URL_SIGNING_KEY });

// Express: app.post('/hooks/render', express.raw({ type: 'application/json' }), (req, res) => {
//   verifyWebhookSignature(req.body, req.get('x-render-signature'), process.env.TRICID_WEBHOOK_SECRET!);
//   const job = JSON.parse(req.body.toString()); ... res.sendStatus(200);
// });
```

## 7. Webhooks: what you receive

`POST <webhook_success>` with the job object as JSON, the same shape as `GET /api/rest/{images|pdfs|videos}/{id}`. Headers:

```text
Content-Type: application/json
X-Render-Signature: t=1793047834,v1=5f2c…(64 hex)
X-Render-Delivery-Id: 1b4e…(uuid; the same on every retry of one delivery)
User-Agent: Tricid-Webhook/1.0
```
**Project webhooks** receive every matching job in the project, without `webhook_success` (Zapier/Make/n8n instant triggers use them):
```bash
curl -s https://render.example.com/api/rest/webhooks -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d '{"url":"https://example.com/hooks/render","events":["image.finished","pdf.finished","video.finished","*.error"]}'
# -> {"id":"…","url":"…","events":[…],"secret":"whsec_…"}   (the secret is shown once)
curl -s https://render.example.com/api/rest/webhooks -H "Authorization: Bearer $TOKEN"            # list
curl -s -X DELETE https://render.example.com/api/rest/webhooks/<id> -H "Authorization: Bearer $TOKEN"   # 204
```
Events are `image|pdf|video` × `.finished|.error`, plus `*.finished`, `*.error` and `*`. A delivery adds `"event"` to the job object and an
`X-Render-Event` header. It is signed with **that subscription's** secret; `webhook_success` deliveries use the project webhook secret.

Every job object also carries `output_mode` (`preview` | `final`) and `credits`. Send `"output_mode": "preview"` on any create for a
free watermarked render.

A delivery is retried with exponential backoff (6 attempts, about 1 h in total) on network errors, 5xx, 408 and 429.
Reply with any 2xx to acknowledge it. Make your handler idempotent per `X-Render-Delivery-Id`. The server
refuses webhook URLs that resolve to private or loopback addresses (SSRF protection).
