# Rețete rapide API: copiază, lipește, rulează

_API · 7 min de citit · Actualizat 2026-10-22 · https://lanachat.ai/guides/ro/api-recipes/_

Opt rețete complete pentru primele automatizări pe care le fac agențiile. Fiecare este gata de copiat, în cURL și JavaScript (Node 20 sau mai nou, fără biblioteci). Setează tokenul o singură dată, ca în [quick start](https://lanachat.ai/guides/ro/api-overview/), și fiecare bloc rulează așa cum este.

```bash
export LANACHAT_TOKEN="lc_live_8f2c1d0e9b7a4c6f"
```

Rețetele JavaScript folosesc acest mic helper. Lipește-l o dată în partea de sus a fișierului:

```js
const API = 'https://api.lanachat.ai/v1';

async function lanachat(method, path, body) {
  const res = await fetch(API + path, {
    method,
    headers: {
      Authorization: `Bearer ${process.env.LANACHAT_TOKEN}`,
      'Content-Type': 'application/json',
      ...(method === 'POST' ? { 'Idempotency-Key': crypto.randomUUID() } : {}),
    },
    body: body ? JSON.stringify(body) : undefined,
  });
  const data = await res.json();
  if (!res.ok) throw new Error(`${res.status} ${data.error.code}: ${data.error.message}`);
  return data;
}
```

## 1. Adaugă o creatoare și conectează-i contul Telegram

Necesită `can_setup` și un token **owner** pentru licență (pasul 4). Creează creatoarea, completează-i identitatea, adaugă-i contul cu tokenul botului, apoi dă contului o licență ca să poată răspunde.

```bash
# 1. the creator
curl -X POST https://api.lanachat.ai/v1/creators \
  -H "Authorization: Bearer $LANACHAT_TOKEN" -H "Idempotency-Key: $(uuidgen)" -H "Content-Type: application/json" \
  -d '{"name": "Lea", "timezone": "Europe/Paris"}'

# 2. her identity (she must be 18 or older)
curl -X PUT https://api.lanachat.ai/v1/creators/cr_lea/identity \
  -H "Authorization: Bearer $LANACHAT_TOKEN" -H "Content-Type: application/json" \
  -d '{"first_name": "Lea", "date_of_birth": "2001-04-12", "nationality": "FR", "languages": ["fr", "en"]}'

# 3. her Telegram account
curl -X POST https://api.lanachat.ai/v1/accounts \
  -H "Authorization: Bearer $LANACHAT_TOKEN" -H "Idempotency-Key: $(uuidgen)" -H "Content-Type: application/json" \
  -d '{"creator_id": "cr_lea", "bot_token": "<bot token>", "market": "fr", "traffic": "instagram"}'

# 4. a licence from your stock
curl -X POST https://api.lanachat.ai/v1/billing/licences/assign \
  -H "Authorization: Bearer $LANACHAT_TOKEN" -H "Idempotency-Key: $(uuidgen)" -H "Content-Type: application/json" \
  -d '{"account_id": "acc_1001"}'
```

```js
const creator = await lanachat('POST', '/creators', { name: 'Lea', timezone: 'Europe/Paris' });
await lanachat('PUT', `/creators/${creator.id}/identity`, {
  first_name: 'Lea', date_of_birth: '2001-04-12', nationality: 'FR', languages: ['fr', 'en'],
});
const account = await lanachat('POST', '/accounts', {
  creator_id: creator.id, bot_token: process.env.BOT_TOKEN, market: 'fr', traffic: 'instagram',
});
await lanachat('POST', '/billing/licences/assign', { account_id: account.id });
console.log(account.id, account.health);   // "pending" until she confirms in Telegram
```

Contul rămâne `pending` până când creatoarea confirmă conexiunea de business în setările Telegram. Un [webhook](https://lanachat.ai/guides/ro/api-webhooks/) te anunță când devine `connected`: evenimentul `account.health_changed`. Vezi [Telegram accounts](https://lanachat.ai/guides/ro/api-telegram-accounts/) și [Billing](https://lanachat.ai/guides/ro/api-billing/).

## 2. Citește vânzările de azi

Necesită `can_sales_read`. `/stats` oferă totalurile pe zi, pe link și pe sursă; Stars valorează $0.013 fiecare în vânzări nete.

```bash
TODAY=$(date -u +%F)
curl "https://api.lanachat.ai/v1/stats?from=$TODAY&to=$TODAY" \
  -H "Authorization: Bearer $LANACHAT_TOKEN"
```

```js
const today = new Date().toISOString().slice(0, 10);
const stats = await lanachat('GET', `/stats?from=${today}&to=${today}`);
const stars = stats.days.reduce((sum, d) => sum + d.revenue_stars, 0);
console.log(`${stars} Stars today, about $${(stars * 0.013).toFixed(2)}`);
for (const l of stats.links) console.log(l.link_id, l.buyers, 'buyers', l.revenue_stars, 'Stars');
```

Adaugă `creator_id=cr_lea` pentru o singură creatoare. Zilele sunt în UTC. Pentru fiecare vânzare imediat ce se întâmplă, folosește rețeta 6.

## 3. Trimite un mesaj unui fan

Necesită `can_chat`. Găsește conversația, apoi trimite mesajul. Un mesaj trimis prin API contează ca trimis de o persoană și preia conversația până când o dai înapoi (rețeta 4).

```bash
# conversations of Lea with unread messages
curl "https://api.lanachat.ai/v1/conversations?creator_id=cr_lea&unread=true" \
  -H "Authorization: Bearer $LANACHAT_TOKEN"

# send a text and a paid photo
curl -X POST https://api.lanachat.ai/v1/conversations/conv_1001_88231/messages \
  -H "Authorization: Bearer $LANACHAT_TOKEN" -H "Idempotency-Key: $(uuidgen)" -H "Content-Type: application/json" \
  -d '{"text": "Only for you, tonight", "media": [{"id": "med_5522", "stars": 250}]}'
```

```js
const { data: convs } = await lanachat('GET', '/conversations?creator_id=cr_lea&unread=true');
const conv = convs[0];
const msg = await lanachat('POST', `/conversations/${conv.id}/messages`, {
  text: 'Only for you, tonight',
  media: [{ id: 'med_5522', stars: 250 }],
});
console.log(msg.status);   // "queued", then "sent" and "read"
```

Adaugă `"send_at"` (ISO 8601, până la 7 zile înainte) pentru programare. Vezi [Conversations](https://lanachat.ai/guides/ro/api-conversations/).

## 4. Preia o conversație, apoi dă-o înapoi AI-ului

Necesită `can_chat`. Cât timp o persoană deține conversația, AI-ul nu răspunde acestui fan.

```bash
curl -X POST https://api.lanachat.ai/v1/conversations/conv_1001_88231/takeover \
  -H "Authorization: Bearer $LANACHAT_TOKEN" -H "Idempotency-Key: $(uuidgen)"

# ... your team replies ...

curl -X POST https://api.lanachat.ai/v1/conversations/conv_1001_88231/release \
  -H "Authorization: Bearer $LANACHAT_TOKEN" -H "Idempotency-Key: $(uuidgen)"
```

```js
const id = 'conv_1001_88231';
await lanachat('POST', `/conversations/${id}/takeover`);   // state: "human"
// ... your team replies ...
await lanachat('POST', `/conversations/${id}/release`);    // back to the AI
```

O conversație oprită din motive de siguranță nu poate fi dată înapoi AI-ului: API răspunde cu `409`.

## 5. Creează un link de tracking

Necesită `can_tracking`. Un link per reclamă sau bio, ca să știi care vinde.

```bash
curl -X POST https://api.lanachat.ai/v1/links \
  -H "Authorization: Bearer $LANACHAT_TOKEN" -H "Idempotency-Key: $(uuidgen)" -H "Content-Type: application/json" \
  -d '{"name": "Insta bio · Lea", "slug": "lea-bio", "creator_id": "cr_lea", "source": "instagram", "destination": "pool"}'
```

```js
const link = await lanachat('POST', '/links', {
  name: 'Insta bio · Lea', slug: 'lea-bio', creator_id: 'cr_lea', source: 'instagram', destination: 'pool',
});
console.log(link.public_url);   // put this URL in her bio
```

Adaugă `"domain"` pentru a folosi unul dintre domeniile tale verificate. Citește click-urile, conversațiile și cumpărătorii cu `GET /links/{id}` sau `/stats`. Vezi [Tracking](https://lanachat.ai/guides/ro/api-tracking/).

## 6. Primește fiecare vânzare pe serverul tău, imediat ce se întâmplă

Necesită un token **owner** pentru a adăuga endpoint-ul. LanaChat trimite un `POST` semnat pentru fiecare vânzare verificată și fiecare rambursare.

```bash
curl -X POST https://api.lanachat.ai/v1/webhooks \
  -H "Authorization: Bearer $LANACHAT_TOKEN" -H "Idempotency-Key: $(uuidgen)" -H "Content-Type: application/json" \
  -d '{"url": "https://hooks.mia-agency.com/lanachat/webhook", "events": ["sale.completed", "sale.refunded"]}'
```

```js
import express from 'express';
import { createHmac, timingSafeEqual } from 'node:crypto';

// once: add the endpoint (keep the secret of the answer as LANACHAT_WEBHOOK_SECRET)
// await lanachat('POST', '/webhooks', { url: 'https://hooks.mia-agency.com/lanachat/webhook', events: ['sale.completed', 'sale.refunded'] });

// the receiver: check the signature, answer 200 fast, then work

function verify(raw, header, secret) {
  const parts = (header || '').split(',').map((p) => p.trim().split('='));
  const t = parts.find(([k]) => k === 't')?.[1];
  if (!t || !(Math.abs(Date.now() / 1000 - Number(t)) < 300)) return false;
  const want = createHmac('sha256', secret).update(t + '.').update(raw).digest('hex');
  return parts.some(([k, v]) => k === 'v1' && v.length === want.length && timingSafeEqual(Buffer.from(v), Buffer.from(want)));
}

const app = express();
app.post('/lanachat/webhook', express.raw({ type: 'application/json' }), (req, res) => {
  if (!verify(req.body, req.get('LanaChat-Signature'), process.env.LANACHAT_WEBHOOK_SECRET)) return res.sendStatus(400);
  res.sendStatus(200);
  const event = JSON.parse(req.body);
  if (event.type === 'sale.completed') console.log('Sale:', event.data.stars, 'Stars,', event.data.creator_id, event.data.sent_by);
  if (event.type === 'sale.refunded') console.log('Refund of', event.data.sale_id);
});
app.listen(3000);
```

Secretul de semnare vine o singură dată, în răspunsul primei apelări: stochează-l ca `LANACHAT_WEBHOOK_SECRET`. Apasă **Test** (`POST /webhooks/{id}/test`) pentru a primi un `ping`. Python, retry-uri și toate evenimentele sunt în [Webhooks](https://lanachat.ai/guides/ro/api-webhooks/).

## 7. Încarcă o poză în Vault și setează prețul

Necesită `can_setup`. Cere un URL de upload, trimite fișierul acolo, confirmă, apoi setează prețul.

```bash
# 1. upload URL
curl -X POST https://api.lanachat.ai/v1/media/uploads \
  -H "Authorization: Bearer $LANACHAT_TOKEN" -H "Idempotency-Key: $(uuidgen)" -H "Content-Type: application/json" \
  -d '{"creator_id": "cr_lea", "file_name": "beach-01.jpg", "content_type": "image/jpeg", "size_bytes": 2483201}'

# 2. the file, to the "url" of the answer (no Authorization header there)
curl -X PUT "<url from step 1>" -H "Content-Type: image/jpeg" --data-binary @beach-01.jpg

# 3. confirm, 4. price it
curl -X POST https://api.lanachat.ai/v1/media/uploads/up_7781/complete \
  -H "Authorization: Bearer $LANACHAT_TOKEN" -H "Idempotency-Key: $(uuidgen)"
curl -X PATCH https://api.lanachat.ai/v1/media/med_5521 \
  -H "Authorization: Bearer $LANACHAT_TOKEN" -H "Content-Type: application/json" \
  -d '{"access": "paid", "stars": 300, "description": "Beach, golden hour, white bikini"}'
```

```js
import { readFile, stat } from 'node:fs/promises';

const file = 'beach-01.jpg';
const up = await lanachat('POST', '/media/uploads', {
  creator_id: 'cr_lea', file_name: file, content_type: 'image/jpeg', size_bytes: (await stat(file)).size,
});
const put = await fetch(up.url, { method: up.method, headers: up.headers, body: await readFile(file) });
if (!put.ok) throw new Error('Upload failed: ' + put.status);
const media = await lanachat('POST', `/media/uploads/${up.upload_id}/complete`);
await lanachat('PATCH', `/media/${media.id}`, { access: 'paid', stars: 300, description: 'Beach, golden hour, white bikini' });
```

Media este `processing`, apoi `ready`: webhook-ul `media.ready` te anunță când. Vezi [Vault](https://lanachat.ai/guides/ro/api-vault/).

## 8. Schimbă un brain, testează-l, publică-l

Necesită `can_engine` și `can_publish` pentru ultimul pas. Brain-ul live se schimbă doar la publicare.

```bash
curl -X PATCH https://api.lanachat.ai/v1/brains/br_lea_main/draft \
  -H "Authorization: Bearer $LANACHAT_TOKEN" -H "Content-Type: application/json" \
  -d '{"settings": {"first_offer_after_messages": 6}}'

curl -X POST https://api.lanachat.ai/v1/playground/br_lea_main/message \
  -H "Authorization: Bearer $LANACHAT_TOKEN" -H "Idempotency-Key: $(uuidgen)" -H "Content-Type: application/json" \
  -d '{"text": "hey, are you real?", "fan": {"language": "en", "is_new": true}}'

curl -X POST https://api.lanachat.ai/v1/brains/br_lea_main/publish \
  -H "Authorization: Bearer $LANACHAT_TOKEN" -H "Idempotency-Key: $(uuidgen)"
```

```js
await lanachat('PATCH', '/brains/br_lea_main/draft', { settings: { first_offer_after_messages: 6 } });
const test = await lanachat('POST', '/playground/br_lea_main/message', {
  text: 'hey, are you real?', fan: { language: 'en', is_new: true },
});
console.log(test.reply.text, '|', test.explain);
// happy with the answer? publish
const live = await lanachat('POST', '/brains/br_lea_main/publish');
console.log('Live version', live.version);
```

Playground nu scrie niciodată unui fan și nu vinde. Vezi [AI Brains](https://lanachat.ai/guides/ro/api-ai-brains/).

## Articole conexe

- [API LanaChat: început rapid, autentificare și erori](https://lanachat.ai/guides/ro/api-overview/)
- [API: webhook-uri, evenimente și semnături](https://lanachat.ai/guides/ro/api-webhooks/)
- [API & MCP: conectează un asistent AI](https://lanachat.ai/guides/ro/api-mcp/)
