# Poiiky Studio API — Complete Integration Guide (v1.0)

> **For AI coding assistants:** This document is the single source of truth for integrating with the Poiiky Studio API. It describes every endpoint, parameter, response field, status value, error and webhook behavior. Follow it exactly. Do not invent endpoints or fields that are not listed here.
>
> **Dành cho khách hàng:** Gửi nguyên file này cho AI code (ChatGPT, Claude, Cursor, Copilot...) kèm yêu cầu của bạn, ví dụ: *"Đọc tài liệu này và viết cho tôi hàm PHP tạo video từ prompt rồi chờ kết quả."*

Last updated: 2026-11-27

---

## Table of Contents

1. Overview
2. Authentication
3. Base URL & Conventions
4. Rate Limits & Concurrency
5. Errors
6. Generation Lifecycle (status values)
7. Billing
8. Endpoints
   - 8.1 POST /generate.php — Create generation
   - 8.2 GET /status.php — Get generation status
   - 8.3 GET /generations.php — List generations
   - 8.4 POST /cancel.php — Cancel generation
   - 8.5 POST /estimate.php — Estimate price
   - 8.6 GET /models.php — List models
   - 8.7 GET /model-detail.php — Model detail
   - 8.8 POST /upload.php — Upload file
   - 8.9 GET /balance.php — Balance
   - 8.10 GET /account.php — Account info
   - 8.11 GET /usage.php — Usage statistics
   - 8.12 /webhooks.php — Webhook management
9. Webhooks (delivery, payload, signature)
10. Complete Examples (Python, Node.js, PHP)
11. Best Practices
12. FAQ
13. Checklist for AI Assistants

---

## 1. Overview

Poiiky Studio generates AI **video, image, audio and text** through many AI models behind one API.

Every generation is **asynchronous**:

```
1. (optional) GET  /models.php         → choose a model_id
2. (optional) POST /estimate.php       → check the price
3. (optional) POST /upload.php         → upload an input image/video/audio, get a URL
4.            POST /generate.php       → create the job, receive a uuid (balance is charged)
5.            GET  /status.php?id=uuid → poll until status is final
              (or receive a webhook)
6.            Download output_files[] URLs
```

---

## 2. Authentication

All requests require an API key sent in the `Authorization` header using the Bearer scheme. Keys start with `pk_` and are created in the Developer Dashboard (`/pages/developer.php`).

```
Authorization: Bearer <YOUR_API_KEY>
```

Rules:

- Keep the key on your **server**. Never put it in browser JavaScript, mobile apps or public repositories.
- Store it in an environment variable, e.g. `POIIKY_API_KEY`.
- If a key leaks, revoke it in the Developer Dashboard and create a new one.
- A missing or invalid key returns `401`.

---

## 3. Base URL & Conventions

```
https://poiikystudio.com/api/v1/
```

All paths below are relative to this base, e.g. `https://poiikystudio.com/api/v1/generate.php`.

- Request bodies are JSON (`Content-Type: application/json`) except `/upload.php` (multipart/form-data).
- Responses are JSON. Successful responses contain `"success": true`.
- Money is in **VND** (integer).
- Timestamps are strings (`YYYY-MM-DD HH:MM:SS` or ISO 8601). Webhook `timestamp` is a Unix integer.

---

## 4. Rate Limits & Concurrency

| Limit | Value |
|---|---|
| Requests per minute (per API key) | 30 |
| Concurrent active generations (queued + processing) | depends on your plan (default 10) |

Every response includes:

```
X-RateLimit-Limit: 30
X-RateLimit-Remaining: 25
X-RateLimit-Reset: 1732612800   (Unix seconds)
```

When exceeded, the API returns `429`. Two different causes return 429:

- `Rate limit exceeded` → wait until `X-RateLimit-Reset`.
- `Too many concurrent generations. Maximum: N...` → wait for an active generation to finish.

---

## 5. Errors

| HTTP | Meaning | Retry? |
|---|---|---|
| 200 / 201 | Success | — |
| 400 | Missing or invalid parameter | No — fix the request |
| 401 | Invalid or missing API key | No |
| 402 | Insufficient balance | No — top up first |
| 404 | Resource / model / provider not found | No |
| 405 | Method not allowed | No |
| 429 | Rate limit or concurrency limit | Yes, after waiting |
| 500 | Server error | Yes, with backoff |

Error body (current format):

```json
{
  "error": true,
  "message": "Insufficient balance. Required: 5000, Available: 2000"
}
```

Some responses may use the structured format. **Handle both**:

```json
{
  "error": { "code": "bad_request", "message": "model_id is required", "status": 400 }
}
```

Robust parsing: `message = body.error.message if body.error is an object else body.message`.

---

## 6. Generation Lifecycle (status values)

```
queued ──► processing ──► succeeded
   │            │
   │            └────────► failed
   └────────────┴────────► cancelled
```

| Status | Final? | Meaning |
|---|---|---|
| `queued` | No | Accepted, waiting for the AI provider |
| `processing` | No | Being generated. `progress` goes 0 → 100 |
| `succeeded` | Yes | Done. Results in `output_files` (and/or `output_text`) |
| `failed` | Yes | Error. Reason in `error`. Check `is_refunded` |
| `cancelled` | Yes | Cancelled via `/cancel.php`, cost refunded |

**Important:** the only valid status values are `queued`, `processing`, `succeeded`, `failed`, `cancelled`. Do not check for `pending` or `completed`.

Some image models return the result immediately: `/generate.php` may already respond with `status: "succeeded"`. Always check the status in the create response before polling.

---

## 7. Billing

- Prepaid balance in VND.
- The price is **charged when the generation is created**.
- If the provider refunds a failed generation, the amount returns to your balance and `is_refunded` becomes `true`.
- Cancelling a `queued`/`processing` generation refunds it.
- Use `/estimate.php` to show the price before creating.
- Insufficient balance → `402`.

---

## 8. Endpoints

### 8.1 POST /generate.php — Create generation

Creates a new asynchronous generation and charges the balance.

**Body (JSON):**

| Field | Type | Required | Description |
|---|---|---|---|
| `model_id` | string | **Yes** | Model ID from `/models.php`. Max 200 chars, `[a-zA-Z0-9._-/]` |
| `prompt` | string | No* | Text prompt, max 10,000 chars. *Required by most models |
| `provider` | string | No | Provider slug. Default `zova`. The system can fall back to another provider automatically |
| `server` | string | No | Server ID (e.g. `sv15`) or `auto` (default, recommended). Mapped to `server_id` for provider routing |
| `aspect_ratio` | string | No | `16:9`, `9:16`, `1:1`, `3:4`, `4:3`, `3:2`, `2:3`, `21:9`, `9:21`, `4:5`, `5:4`, `20:9`, `9:19.5`, `auto` |
| `duration` | number/string | No | Duration in seconds (video/audio) |
| `resolution` | string | No | e.g. `720p`, `1080p` |
| `quality` | string | No | Quality preset, e.g. `standard`, `high` |
| `image_url` | string | No | Input image URL (image-to-video, image editing). Use the `url` from `/upload.php` |
| `image_urls` | array | No | Multiple input images |
| `last_frame_url` | string | No | End frame image (first/last-frame video models) |
| `video_url` | string | No | Input video URL |
| `audio_url` | string | No | Input audio URL |
| `mask_url` | string | No | Mask image for inpainting |
| `reference_images` | array | No | Reference images |
| `negative_prompt` | string | No | What to avoid |
| `seed` | integer | No | Random seed for reproducibility |
| `mode` | string | No | Model-specific mode |
| `n` | integer | No | Number of outputs (image models) |
| `style` | string | No | Style preset |
| `with_audio` / `enable_audio` | boolean | No | Generate audio with video (if supported) |
| `voice` | string | No | Voice ID for TTS/subtitle models |
| `instrumental` | boolean | No | Instrumental only — no vocals (music models) |
| `language` | string | No | Language code for TTS/subtitle models (e.g. `vi`, `en`) |
| `speed` | string | No | Reading speed for TTS/subtitle models |
| `format` | string | No | Output format for TTS models (`mp3`, `wav`) |
| `srt` | string | No | Subtitle text content (SRT format) for subtitle-to-voice models |
| `subtitle_file_url` | string | No | Subtitle file URL (.srt/.vtt) from `/upload.php` |
| `p_*` | various | No | Model-specific parameters prefixed with `p_` (e.g. `p_voice_id`, `p_language_code`, `p_speed`, `p_stability`). See the model's `params` schema |
| `cfg_scale`, `guidance_scale`, `steps`, `fps`, `motion_strength`, `camera_motion`, `watermark` | various | No | Advanced, model-specific |

Which optional fields a model supports depends on the model. Read `params` from `/model-detail.php`. Only parameters declared in the model's schema are forwarded to the provider; unrecognized fields are stripped to prevent errors.

**Example request:**

```bash
curl -X POST "https://poiikystudio.com/api/v1/generate.php" \
  -H "Authorization: Bearer $POIIKY_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model_id": "kling-v2",
    "prompt": "A serene mountain landscape at sunset, cinematic",
    "aspect_ratio": "16:9",
    "duration": 5
  }'
```

**Response 200:**

```json
{
  "success": true,
  "generation": {
    "id": 98765,
    "uuid": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
    "model_id": "kling-v2",
    "status": "queued",
    "progress": 0,
    "cost": 5000,
    "output_type": "video",
    "created_at": "2026-11-26 10:30:00"
  }
}
```

Save `generation.uuid`. It is used by `/status.php` and `/cancel.php`.

**Errors:** `400` invalid params · `401` · `402` insufficient balance · `404` provider not found · `429` rate/concurrency limit · `500`.

---

### 8.2 GET /status.php — Get generation status

**Query:** `id` (string, required) = the generation `uuid`.

```bash
curl "https://poiikystudio.com/api/v1/status.php?id=a1b2c3d4-e5f6-7890-abcd-ef1234567890" \
  -H "Authorization: Bearer $POIIKY_API_KEY"
```

**Response 200:**

```json
{
  "success": true,
  "data": {
    "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
    "status": "succeeded",
    "progress": 100,
    "model_id": "kling-v2",
    "output_type": "video",
    "output_files": ["https://poiikystudio.com/outputs/video-abc123.mp4"],
    "output_text": null,
    "error": null,
    "is_refunded": false,
    "cost": 5000,
    "created_at": "2026-11-26 10:30:00",
    "completed_at": "2026-11-26 10:32:15"
  }
}
```

| Field | Description |
|---|---|
| `id` | Generation uuid |
| `status` | `queued` / `processing` / `succeeded` / `failed` / `cancelled` |
| `progress` | 0–100 |
| `output_files` | Array of result URLs (empty until succeeded) |
| `output_text` | Text result for text models |
| `error` | Failure reason, or null |
| `is_refunded` | Whether the cost was refunded |
| `cost` | Cost in VND |

**Download outputs promptly.** Output files may expire (default about 24 hours after completion). Copy them to your own storage.

**Errors:** `400` missing id · `401` · `404` not found or not yours · `429`.

---

### 8.3 GET /generations.php — List generations

| Query | Type | Default | Description |
|---|---|---|---|
| `page` | integer | 1 | Page number (≥1) |
| `limit` | integer | 20 | Items per page, 1–100 |
| `status` | string | — | `queued`, `processing`, `succeeded`, `failed`, `cancelled` |
| `output_type` | string | — | `video`, `image`, `audio`, `text` |
| `model_id` | string | — | Filter by model |
| `search` | string | — | Search in prompt |

```bash
curl "https://poiikystudio.com/api/v1/generations.php?page=1&limit=20&status=succeeded&output_type=video" \
  -H "Authorization: Bearer $POIIKY_API_KEY"
```

**Response 200:**

```json
{
  "success": true,
  "data": [ { "id": "...", "status": "succeeded", "model_id": "kling-v2", "output_files": ["..."], "cost": 5000 } ],
  "pagination": { "page": 1, "limit": 20, "total": 150, "total_pages": 8 }
}
```

---

### 8.4 POST /cancel.php — Cancel generation

Cancels a `queued` or `processing` generation and refunds it. Final generations cannot be cancelled (`400`).

**Body:** `{ "uuid": "a1b2c3d4-..." }`

```bash
curl -X POST "https://poiikystudio.com/api/v1/cancel.php" \
  -H "Authorization: Bearer $POIIKY_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"uuid": "a1b2c3d4-e5f6-7890-abcd-ef1234567890"}'
```

**Response 200:**

```json
{ "success": true, "message": "Generation cancelled successfully", "refunded": 5000, "new_balance": 155000 }
```

---

### 8.5 POST /estimate.php — Estimate price

Accepts the same body as `/generate.php` (at least `model_id`). Price can depend on `duration`, `resolution`, `aspect_ratio`, etc. Nothing is charged.

```bash
curl -X POST "https://poiikystudio.com/api/v1/estimate.php" \
  -H "Authorization: Bearer $POIIKY_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model_id": "kling-v2", "duration": 5, "resolution": "1080p"}'
```

**Response 200:**

```json
{
  "success": true,
  "provider_cost": 3500,
  "sell_price": 5000,
  "original_cost": 3500,
  "discount": 0,
  "currency": "VND",
  "formatted": "5.000₫"
}
```

Use `sell_price`. That is the amount charged.

---

### 8.6 GET /models.php — List models

**Query:** `type` (optional): `video`, `image`, `audio`, `text`.

```bash
curl "https://poiikystudio.com/api/v1/models.php?type=video" \
  -H "Authorization: Bearer $POIIKY_API_KEY"
```

**Response 200:**

```json
{
  "success": true,
  "models": [
    { "model_id": "kling-v2", "name": "Kling v2", "provider": "zova", "output_type": "video", "is_featured": true, "pricing": { } }
  ],
  "total": 42
}
```

The model list changes over time. Load it dynamically instead of hardcoding IDs.

---

### 8.7 GET /model-detail.php — Model detail

**Query:** `model_id` (required), `provider` (optional).

```bash
curl "https://poiikystudio.com/api/v1/model-detail.php?model_id=kling-v2" \
  -H "Authorization: Bearer $POIIKY_API_KEY"
```

**Response 200:**

```json
{
  "success": true,
  "model_id": "kling-v2",
  "server_id": "...",
  "name": "Kling v2",
  "output_type": "video",
  "provider": "zova",
  "params": { },
  "pricing": { },
  "sell_price": 5000,
  "duration_info": ""
}
```

`params` describes which inputs this model accepts (aspect ratios, durations, resolutions, image input...). Build your form from it.

---

### 8.8 POST /upload.php — Upload file

Upload an input file and get a URL to pass to `/generate.php` (`image_url`, `video_url`, `audio_url`...).

**Body (multipart/form-data):**

| Field | Type | Required | Description |
|---|---|---|---|
| `file` | file | **Yes** | Max **50 MB** |
| `provider` | string | No | Default `zova` |
| `upload_to_provider` | string | No | `1` (default) or `0` |

Allowed types:

- Image: `jpg`, `jpeg`, `png`, `webp`, `gif`
- Video: `mp4`, `mov`, `webm`
- Audio: `mp3`, `wav`, `m4a`

```bash
curl -X POST "https://poiikystudio.com/api/v1/upload.php" \
  -H "Authorization: Bearer $POIIKY_API_KEY" \
  -F "file=@/path/to/image.png"
```

Do **not** set `Content-Type` manually for multipart. Let your HTTP library set the boundary.

**Response 200:**

```json
{
  "success": true,
  "id": 321,
  "url": "https://.../image.png",
  "local_url": "/uploads/2026/11/upload_xxx.png",
  "provider_url": "https://.../image.png",
  "name": "image.png",
  "mime_type": "image/png",
  "size": 2048576
}
```

Use `url` as the input for generation. If `warning` is present, the file was saved but the provider upload failed, so some models may not accept it.

---

### 8.9 GET /balance.php — Balance

```bash
curl "https://poiikystudio.com/api/v1/balance.php" -H "Authorization: Bearer $POIIKY_API_KEY"
```

```json
{
  "success": true,
  "balance": 150000,
  "plan": { "name": "Pro", "slug": "pro" },
  "rate_limit": { "limit": 30, "remaining": 27, "reset": 1732600000 }
}
```

---

### 8.10 GET /account.php — Account info

Returns profile, balance, plan and usage summary.

```bash
curl "https://poiikystudio.com/api/v1/account.php" -H "Authorization: Bearer $POIIKY_API_KEY"
```

```json
{
  "success": true,
  "user": { "id": 42, "username": "creator", "display_name": "Creator", "email": "user@example.com" },
  "balance": 50000,
  "plan": { "name": "Pro" },
  "usage": { "total_generations": 1250 }
}
```

---

### 8.11 GET /usage.php — Usage statistics

**Query:** `days` (optional, 1–90, default 14).

```bash
curl "https://poiikystudio.com/api/v1/usage.php?days=30" -H "Authorization: Bearer $POIIKY_API_KEY"
```

```json
{
  "success": true,
  "summary": { "total_requests": 15420, "total_generations": 1250, "total_cost": 6250000 },
  "daily": [ { "date": "2026-11-26", "requests": 45, "generations": 12, "cost": 60000 } ]
}
```

---

### 8.12 /webhooks.php — Webhook management

Max **5 webhooks** per account. URLs must be **HTTPS**.

Supported events: `generation.succeeded`, `generation.failed`.

| Action | Method & URL | Body |
|---|---|---|
| List | `GET /webhooks.php` | — |
| Get one | `GET /webhooks.php?id=123` | — |
| Delivery log | `GET /webhooks.php?id=123&deliveries=1` | — |
| Create | `POST /webhooks.php` | `{ "url", "events", "description"? }` |
| Regenerate secret | `POST /webhooks.php?action=regenerate&id=123` | — |
| Update | `PUT /webhooks.php?id=123` | `{ "url"?, "events"?, "description"?, "is_active"? }` |
| Delete | `DELETE /webhooks.php?id=123` | — |

Note: `id` goes in the **query string** for get, update, delete and regenerate.

**Create:**

```bash
curl -X POST "https://poiikystudio.com/api/v1/webhooks.php" \
  -H "Authorization: Bearer $POIIKY_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://yourapp.com/webhooks/poiiky", "events": ["generation.succeeded", "generation.failed"], "description": "Production"}'
```

**Response 201:**

```json
{
  "success": true,
  "message": "Webhook created",
  "data": {
    "id": 42,
    "url": "https://yourapp.com/webhooks/poiiky",
    "events": ["generation.succeeded", "generation.failed"],
    "secret": "whsec_...",
    "is_active": true
  }
}
```

The `secret` is shown **only on create and regenerate**. Store it securely.

**List response:** `{ "success": true, "data": [ ...webhooks ], "supported_events": ["generation.succeeded", "generation.failed"] }`

**Update / Delete response:** `{ "success": true, "message": "Webhook updated" }` / `{ "success": true, "message": "Webhook deleted" }`

---

## 9. Webhooks (delivery, payload, signature)

When a generation reaches `succeeded` or `failed`, Poiiky sends a `POST` to each active subscribed webhook.

**Headers:**

```
Content-Type: application/json
User-Agent: Poiiky-Webhook/1.0
X-Poiiky-Event: generation.succeeded
X-Poiiky-Signature: sha256=<hex HMAC-SHA256 of the raw body using your secret>
X-Poiiky-Delivery: <unique delivery id>
```

**Body:**

```json
{
  "event": "generation.succeeded",
  "data": {
    "id": 98765,
    "uuid": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
    "model_id": "kling-v2",
    "status": "succeeded",
    "output_type": "video",
    "output_files": ["https://poiikystudio.com/outputs/video-abc123.mp4"],
    "output_text": null,
    "cost": 5000,
    "is_refunded": false,
    "error": null,
    "created_at": "2026-11-26 10:30:00",
    "completed_at": "2026-11-26 10:32:15"
  },
  "timestamp": 1732617135
}
```

Note: in webhook payloads, `data.id` is the internal integer ID and `data.uuid` is the generation uuid. Match on `data.uuid`.

**Delivery rules:**

- Respond with any **2xx** within **5 seconds**. Do heavy work asynchronously after responding.
- Redirects are **not** followed.
- Each event is delivered **once**. Failed deliveries are **not retried**.
- After **10 consecutive failed deliveries**, the webhook is **automatically disabled**. Re-enable it with `PUT /webhooks.php?id=...` and `{"is_active": true}`.
- Delivery may be duplicated in rare cases. Make your handler idempotent: ignore a `uuid` you have already processed.
- Because webhooks are not retried, also keep polling `/status.php` as a fallback for important jobs.

**Signature verification** (compute HMAC over the **raw** request body bytes, before JSON parsing):

Python:

```python
import hmac, hashlib

def verify(raw_body: bytes, signature_header: str, signing_key: str) -> bool:
    expected = "sha256=" + hmac.new(signing_key.encode(), raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, signature_header or "")
```

Node.js:

```javascript
const crypto = require("crypto");

function verify(rawBody, signatureHeader, secret) {
  const expected = "sha256=" + crypto.createHmac("sha256", secret).update(rawBody).digest("hex");
  const a = Buffer.from(expected);
  const b = Buffer.from(signatureHeader || "");
  return a.length === b.length && crypto.timingSafeEqual(a, b);
}
```

PHP:

```php
function verify(string $rawBody, string $signatureHeader, string $secret): bool {
    $expected = 'sha256=' . hash_hmac('sha256', $rawBody, $secret);
    return hash_equals($expected, $signatureHeader);
}
```

---

## 10. Complete Examples

All examples read the key from the `POIIKY_API_KEY` environment variable.

### 10.1 Python — text-to-video, wait, download

```python
import os, time, requests

API = "https://poiikystudio.com/api/v1/"
HEADERS = {"Authorization": f"Bearer {os.environ['POIIKY_API_KEY']}"}
FINAL = {"succeeded", "failed", "cancelled"}


class PoiikyError(Exception):
    pass


def call(method, path, **kwargs):
    for attempt in range(5):
        r = requests.request(method, API + path, headers=HEADERS, timeout=60, **kwargs)
        if r.status_code in (429, 500, 502, 503) and attempt < 4:
            time.sleep(min(60, 2 ** attempt * 2))
            continue
        body = r.json()
        if r.status_code >= 400 or body.get("error"):
            err = body.get("error")
            msg = err.get("message") if isinstance(err, dict) else body.get("message")
            raise PoiikyError(f"HTTP {r.status_code}: {msg}")
        return body


def generate_and_wait(payload, timeout_s=900):
    price = call("POST", "estimate.php", json=payload)
    print("Price:", price["formatted"])

    gen = call("POST", "generate.php", json=payload)["generation"]
    uuid = gen["uuid"]
    print("Created:", uuid)

    deadline = time.time() + timeout_s
    delay = 5
    while True:
        data = call("GET", "status.php", params={"id": uuid})["data"]
        print(data["status"], data["progress"], "%")
        if data["status"] in FINAL:
            return data
        if time.time() > deadline:
            raise PoiikyError("Timed out waiting for generation")
        time.sleep(delay)
        delay = min(delay + 2, 15)


def download(url, path):
    with requests.get(url, stream=True, timeout=120) as r:
        r.raise_for_status()
        with open(path, "wb") as f:
            for chunk in r.iter_content(1 << 16):
                f.write(chunk)


if __name__ == "__main__":
    result = generate_and_wait({
        "model_id": "kling-v2",
        "prompt": "A serene mountain landscape at sunset, cinematic",
        "aspect_ratio": "16:9",
        "duration": 5,
    })
    if result["status"] == "succeeded":
        for i, url in enumerate(result["output_files"]):
            download(url, f"output_{i}.mp4")
            print("Saved", url)
    else:
        print("Failed:", result["error"], "refunded:", result["is_refunded"])
```

### 10.2 Python — image-to-video

```python
with open("photo.jpg", "rb") as f:
    up = call("POST", "upload.php", files={"file": f})

result = generate_and_wait({
    "model_id": "kling-v2",
    "prompt": "The person slowly turns and smiles",
    "image_url": up["url"],
    "duration": 5,
})
```

### 10.3 Node.js (18+) — full workflow

```javascript
const fs = require("fs");
const API = "https://poiikystudio.com/api/v1/";
const AUTH = { Authorization: `Bearer ${process.env.POIIKY_API_KEY}` };
const FINAL = new Set(["succeeded", "failed", "cancelled"]);
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

async function call(method, path, { json, form, query } = {}) {
  const url = new URL(path, API);
  if (query) Object.entries(query).forEach(([k, v]) => url.searchParams.set(k, v));
  for (let attempt = 0; attempt < 5; attempt++) {
    const res = await fetch(url, {
      method,
      headers: json ? { ...AUTH, "Content-Type": "application/json" } : AUTH,
      body: json ? JSON.stringify(json) : form,
    });
    if ([429, 500, 502, 503].includes(res.status) && attempt < 4) {
      await sleep(Math.min(60000, 2000 * 2 ** attempt));
      continue;
    }
    const body = await res.json();
    if (!res.ok || body.error) {
      const msg = typeof body.error === "object" ? body.error.message : body.message;
      throw new Error(`HTTP ${res.status}: ${msg}`);
    }
    return body;
  }
}

async function generateAndWait(payload, timeoutMs = 900000) {
  const { generation } = await call("POST", "generate.php", { json: payload });
  const deadline = Date.now() + timeoutMs;
  let delay = 5000;
  while (true) {
    const { data } = await call("GET", "status.php", { query: { id: generation.uuid } });
    console.log(data.status, data.progress + "%");
    if (FINAL.has(data.status)) return data;
    if (Date.now() > deadline) throw new Error("Timed out");
    await sleep(delay);
    delay = Math.min(delay + 2000, 15000);
  }
}

async function uploadFile(filePath) {
  const form = new FormData();
  form.append("file", new Blob([fs.readFileSync(filePath)]), require("path").basename(filePath));
  return call("POST", "upload.php", { form });
}

(async () => {
  const result = await generateAndWait({
    model_id: "kling-v2",
    prompt: "A serene mountain landscape at sunset, cinematic",
    aspect_ratio: "16:9",
    duration: 5,
  });
  if (result.status === "succeeded") {
    for (const [i, url] of result.output_files.entries()) {
      const res = await fetch(url);
      fs.writeFileSync(`output_${i}.mp4`, Buffer.from(await res.arrayBuffer()));
    }
  } else {
    console.error("Failed:", result.error, "refunded:", result.is_refunded);
  }
})();
```

### 10.4 PHP — full workflow

```php
<?php
const POIIKY_API = 'https://poiikystudio.com/api/v1/';

function poiiky(string $method, string $path, ?array $json = null, ?array $multipart = null, array $query = []): array
{
    $url = POIIKY_API . $path . ($query ? '?' . http_build_query($query) : '');
    $headers = ['Authorization: Bearer ' . getenv('POIIKY_API_KEY')];

    for ($attempt = 0; $attempt < 5; $attempt++) {
        $ch = curl_init($url);
        $opts = [
            CURLOPT_CUSTOMREQUEST  => $method,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 60,
        ];
        if ($json !== null) {
            $headers[] = 'Content-Type: application/json';
            $opts[CURLOPT_POSTFIELDS] = json_encode($json);
        } elseif ($multipart !== null) {
            $opts[CURLOPT_POSTFIELDS] = $multipart; // e.g. ['file' => new CURLFile('photo.jpg')]
        }
        $opts[CURLOPT_HTTPHEADER] = array_unique($headers);
        curl_setopt_array($ch, $opts);
        $raw = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if (in_array($code, [429, 500, 502, 503], true) && $attempt < 4) {
            sleep(min(60, 2 ** $attempt * 2));
            continue;
        }
        $body = json_decode((string) $raw, true) ?: [];
        if ($code >= 400 || !empty($body['error'])) {
            $msg = is_array($body['error'] ?? null) ? $body['error']['message'] : ($body['message'] ?? 'Unknown error');
            throw new RuntimeException("HTTP $code: $msg");
        }
        return $body;
    }
    throw new RuntimeException('Request failed after retries');
}

function generateAndWait(array $payload, int $timeoutSec = 900): array
{
    $gen = poiiky('POST', 'generate.php', $payload)['generation'];
    $deadline = time() + $timeoutSec;
    $delay = 5;
    while (true) {
        $data = poiiky('GET', 'status.php', null, null, ['id' => $gen['uuid']])['data'];
        if (in_array($data['status'], ['succeeded', 'failed', 'cancelled'], true)) {
            return $data;
        }
        if (time() > $deadline) {
            throw new RuntimeException('Timed out');
        }
        sleep($delay);
        $delay = min($delay + 2, 15);
    }
}

// Text-to-video
$result = generateAndWait([
    'model_id'     => 'kling-v2',
    'prompt'       => 'A serene mountain landscape at sunset, cinematic',
    'aspect_ratio' => '16:9',
    'duration'     => 5,
]);

if ($result['status'] === 'succeeded') {
    foreach ($result['output_files'] as $i => $url) {
        file_put_contents("output_$i.mp4", fopen($url, 'r'));
    }
} else {
    echo 'Failed: ' . $result['error'];
}

// Image-to-video
$up = poiiky('POST', 'upload.php', null, ['file' => new CURLFile(__DIR__ . '/photo.jpg')]);
$result = generateAndWait(['model_id' => 'kling-v2', 'prompt' => 'The person smiles', 'image_url' => $up['url']]);
```

### 10.5 Webhook receivers

Python (Flask):

```python
import os, hmac, hashlib
from flask import Flask, request, abort

app = Flask(__name__)
SIGNING_KEY = os.environ["POIIKY_WEBHOOK_SECRET"]

@app.post("/webhooks/poiiky")
def poiiky_webhook():
    raw = request.get_data()
    expected = "sha256=" + hmac.new(SIGNING_KEY.encode(), raw, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, request.headers.get("X-Poiiky-Signature", "")):
        abort(401)
    event = request.get_json()
    gen = event["data"]
    # enqueue background work keyed by gen["uuid"] (idempotent)
    print(event["event"], gen["uuid"], gen.get("output_files"))
    return "", 200
```

Node.js (Express):

```javascript
const express = require("express");
const crypto = require("crypto");
const app = express();
const SIGNING_KEY = process.env.POIIKY_WEBHOOK_SECRET;

app.post("/webhooks/poiiky", express.raw({ type: "application/json" }), (req, res) => {
  const expected = "sha256=" + crypto.createHmac("sha256", SIGNING_KEY).update(req.body).digest("hex");
  const got = req.get("X-Poiiky-Signature") || "";
  if (expected.length !== got.length || !crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(got))) {
    return res.sendStatus(401);
  }
  const event = JSON.parse(req.body.toString());
  res.sendStatus(200);
  // process event.data.uuid asynchronously, idempotently
  console.log(event.event, event.data.uuid);
});

app.listen(3000);
```

PHP:

```php
<?php
$raw = file_get_contents('php://input');
$signingKey = getenv('POIIKY_WEBHOOK_SECRET');
$expected = 'sha256=' . hash_hmac('sha256', $raw, $signingKey);

if (!hash_equals($expected, $_SERVER['HTTP_X_POIIKY_SIGNATURE'] ?? '')) {
    http_response_code(401);
    exit;
}

$event = json_decode($raw, true);
$gen = $event['data'];

http_response_code(200);
// Save $gen['uuid'], $gen['status'], $gen['output_files'] — skip if uuid already processed
```

---

## 11. Best Practices

**Polling**

- Start polling 3–5 s after creating.
- Interval: 5–10 s for video, 2–3 s for images. Increase gradually (max ~15 s).
- Stop when status is `succeeded`, `failed` or `cancelled`.
- Polling counts toward the 30 requests/minute limit. Don't poll many jobs in tight loops; space them out.

**Errors**

- Retry only `429` and `5xx`, with exponential backoff (2 s, 4 s, 8 s… max 60 s).
- Never retry `400`, `401`, `402`, `404` automatically.
- **Do not blindly retry `/generate.php` on network timeouts.** A retry can create and charge a second job. Check `/generations.php` first.
- Log the full error message.

**Money**

- Call `/estimate.php` and show the price before generating.
- Check `/balance.php` before large batches.

**Files**

- Upload once, reuse the `url`.
- Input images should match the target aspect ratio.
- Download outputs promptly to your own storage. Result URLs can expire.

**Security**

- API key only on the server, in environment variables.
- Verify webhook signatures with a constant-time comparison.
- Your webhook URL must be HTTPS.

**Concurrency**

- Respect your plan's concurrent limit. Queue jobs on your side and submit when a slot frees up.

---

## 12. FAQ

**Which output formats are returned?** Video: usually MP4. Image: PNG/JPEG/WebP. Audio: MP3/WAV. Check the file extension in `output_files`.

**How long does a generation take?** Images: seconds to about 1 minute. Video: usually 1–10 minutes depending on model, duration and load.

**Am I refunded if it fails?** Failed jobs refunded by the provider return to your balance (`is_refunded: true`). Cancelled jobs are refunded.

**What is the rate limit?** 30 requests/minute per key, plus a concurrent generation limit per plan.

**Is there an official SDK?** Not yet. Use the examples in section 10, or give this document to an AI assistant to generate a client.

**Are webhooks retried?** No. Each event is sent once. Keep a polling fallback. A webhook is disabled after 10 consecutive failures.

**Can I use the API from the browser?** No. Call it from your backend so your key stays secret.

**Can I get the OpenAPI spec?** Yes: `/docs/openapi.yaml` (import into Postman or Swagger).

---

## 13. Checklist for AI Assistants

When writing an integration from this document:

- [ ] Base URL `https://poiikystudio.com/api/v1/`; every path ends with `.php`.
- [ ] Header `Authorization: Bearer <key>`; key from environment variable.
- [ ] Use `generation.uuid` from `/generate.php` for `/status.php?id=` and `/cancel.php`.
- [ ] Status values are exactly `queued`, `processing`, `succeeded`, `failed`, `cancelled`.
- [ ] Check whether `/generate.php` already returned `succeeded`.
- [ ] Poll with an interval and a timeout; stop on final statuses.
- [ ] Handle both error formats (`error: true` + `message`, or `error.message`).
- [ ] Retry only 429/5xx with backoff; don't auto-retry `/generate.php` after a timeout.
- [ ] `/upload.php` is multipart with field `file`; use the returned `url`.
- [ ] Webhook signature = `sha256=` + HMAC-SHA256(raw body, secret); respond 2xx within 5 s; idempotent on `data.uuid`.
- [ ] Download `output_files` promptly.
