# Recettes rapides API : copier, coller, exécuter

_API · Lecture de 7 min · Mis à jour 2026-10-22 · https://lanachat.ai/guides/fr/api-recipes/_

Huit recettes complètes pour les tâches que les agences automatisent en premier. Chacune est prête à être copiée, en cURL et en JavaScript (Node 20 ou plus récent, sans bibliothèque). Configurez votre token une fois, comme dans le [quick start](https://lanachat.ai/guides/fr/api-overview/), et chaque bloc s'exécute tel quel.

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

Les recettes JavaScript utilisent ce petit helper. Collez-le une fois en haut de votre fichier :

```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. Ajouter une créatrice et connecter son compte Telegram

Nécessite `can_setup`, et un token **owner** pour la licence (étape 4). Créez la créatrice, remplissez son identité, ajoutez son compte avec son token bot, puis attribuez une licence au compte pour qu’il puisse répondre.

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

Le compte reste `pending` jusqu’à ce que la créatrice confirme la connexion business dans ses paramètres Telegram. Un [webhook](https://lanachat.ai/guides/fr/api-webhooks/) vous informe quand il devient `connected` : l’événement `account.health_changed`. Voir [Telegram accounts](https://lanachat.ai/guides/fr/api-telegram-accounts/) et [Billing](https://lanachat.ai/guides/fr/api-billing/).

## 2. Lire les ventes du jour

Nécessite `can_sales_read`. `/stats` donne les totaux d’une journée, par lien et par source ; les Stars comptent $0.013 chacune en ventes nettes.

```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');
```

Ajoutez `creator_id=cr_lea` pour une seule créatrice. Les jours sont en UTC. Pour obtenir chaque vente au moment où elle arrive, utilisez la recette 6.

## 3. Envoyer un message à un fan

Nécessite `can_chat`. Trouvez la conversation, puis envoyez. Un message envoyé via l’API compte comme envoyé par une personne et prend la main sur la conversation jusqu’à ce que vous la rendiez (recette 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"
```

Ajoutez `"send_at"` (ISO 8601, jusqu’à 7 jours à l’avance) pour programmer l’envoi. Voir [Conversations](https://lanachat.ai/guides/fr/api-conversations/).

## 4. Prendre le contrôle d’une conversation, puis la rendre à l’IA

Nécessite `can_chat`. Tant qu’une personne tient la conversation, l’IA ne répond pas à ce 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
```

Une conversation arrêtée pour raison de sécurité ne peut pas être rendue à l’IA : l’API répond `409`.

## 5. Créer un lien de tracking

Nécessite `can_tracking`. Un lien par pub ou par bio, pour savoir lequel vend.

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

Ajoutez `"domain"` pour utiliser un de vos domaines vérifiés. Lisez ses clics, conversations et acheteurs avec `GET /links/{id}` ou `/stats`. Voir [Tracking](https://lanachat.ai/guides/fr/api-tracking/).

## 6. Recevoir chaque vente sur votre serveur, en temps réel

Nécessite un token **owner** pour ajouter le endpoint. LanaChat envoie un `POST` signé pour chaque vente vérifiée et chaque remboursement.

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

Le secret de signature est donné une fois, dans la réponse du premier appel : stockez-le comme `LANACHAT_WEBHOOK_SECRET`. Appuyez sur **Test** (`POST /webhooks/{id}/test`) pour recevoir un `ping`. Python, les retries et tous les événements sont dans [Webhooks](https://lanachat.ai/guides/fr/api-webhooks/).

## 7. Télécharger une photo dans le Vault et la tarifer

Nécessite `can_setup`. Demandez une URL d’upload, envoyez le fichier là-bas, confirmez, puis fixez son prix.

```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' });
```

Le média est `processing`, puis `ready` : le webhook `media.ready` vous informe quand. Voir [Vault](https://lanachat.ai/guides/fr/api-vault/).

## 8. Modifier un brain, le tester, le publier

Nécessite `can_engine`, et `can_publish` pour la dernière étape. Le brain live ne change qu’à la publication.

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

Le Playground n’écrit jamais à un fan et ne vend jamais. Voir [AI Brains](https://lanachat.ai/guides/fr/api-ai-brains/).

## Articles liés

- [API LanaChat : démarrage rapide, authentification et erreurs](https://lanachat.ai/guides/fr/api-overview/)
- [API : webhooks, événements et signatures](https://lanachat.ai/guides/fr/api-webhooks/)
- [API & MCP : connecter un assistant IA](https://lanachat.ai/guides/fr/api-mcp/)
