Aller au contenu principal

API Reference

Documentation complète de l'API VocalIA pour intégrer Voice Widget et Voice Telephony dans vos applications.

REST API

Endpoints HTTP pour créer, gérer et monitorer vos appels vocaux.

WebSockets

Connexion temps réel pour audio streaming et événements live.

Authentification

L'API VocalIA utilise des clés API pour l'authentification. Incluez votre clé dans le header Authorization de chaque requête.

HTTP Header
Authorization: Bearer voc_sk_live_xxxxxxxxxxxxxxxxxxxxxxxx

Sécurité des clés API

  • Ne jamais exposer vos clés côté client (frontend)
  • Utilisez des variables d'environnement
  • Régénérez vos clés si compromises

Base URL

Production
https://api.vocalia.ma/v1
Sandbox (Test)
https://sandbox.api.vocalia.ma/v1

Voice Widget - Intégration

Intégrez le Voice Widget en ajoutant simplement une balise script à votre page.

HTML
<!-- VocalIA Voice Widget -->
<script>
  window.VOCALIA_CONFIG = {
    tenant_id: 'votre-tenant-id',
    api_url: 'https://api.vocalia.ma',
    language: 'fr',
    position: 'bottom-right'
  };
</script>
<script src="https://vocalia.ma/voice-assistant/voice-widget-b2b.js" async></script>

Voice Widget - Configuration

Paramètre Type Description
apiKey requis string Clé API publique (voc_pk_*)
agentId requis string ID de l'agent vocal configuré
language optionnel string Langue: fr, en, ar, es, ary (default: fr)
position optionnel string bottom-right, bottom-left, top-right, top-left
theme optionnel object Personnalisation couleurs (primaryColor, etc.)
onReady optionnel function Callback quand le widget est prêt

Voice Widget - Événements

JavaScript
VocalIA.on('conversationStart', (data) => {
});

VocalIA.on('message', (data) => {
});

VocalIA.on('conversationEnd', (data) => {
});

VocalIA.on('error', (error) => {
  console.error('Erreur:', error.message);
});

POST Créer un appel

Initie un appel sortant vers un numéro de téléphone.

Endpoint
POST /v1/calls

Paramètres

Paramètre Type Description
to requis string Numéro destination (E.164: +212612345678)
agentId requis string ID de l'agent vocal
from optionnel string Numéro appelant (si plusieurs configurés)
metadata optionnel object Données personnalisées à passer à l'agent
webhookUrl optionnel string URL pour recevoir les événements de l'appel

Exemple de requête

cURL
curl -X POST https://api.vocalia.ma/v1/calls \
  -H "Authorization: Bearer voc_sk_live_xxxx" \
  -H "Content-Type: application/json" \
  -d '{
    "to": "+212612345678",
    "agentId": "agent_support_fr",
    "metadata": {
      "customerId": "cust_123",
      "orderId": "ord_456"
    }
  }'

Réponse

JSON - 201 Created
{
  "id": "call_abc123xyz",
  "status": "initiating",
  "to": "+212612345678",
  "from": "+212520123456",
  "agentId": "agent_support_fr",
  "createdAt": "2026-01-29T15:30:00Z",
  "metadata": {
    "customerId": "cust_123",
    "orderId": "ord_456"
  }
}

GET Récupérer un appel

Endpoint
GET /v1/calls/{call_id}
JSON - 200 OK
{
  "id": "call_abc123xyz",
  "status": "completed",
  "duration": 127,
  "to": "+212612345678",
  "from": "+212520123456",
  "transcript": [
    {"role": "agent", "content": "Bonjour, VocalIA..."},
    {"role": "user", "content": "Je voudrais..."}
  ],
  "sentiment": "positive",
  "cost": 0.13,
  "createdAt": "2026-01-29T15:30:00Z",
  "endedAt": "2026-01-29T15:32:07Z"
}

GET Lister les appels

Endpoint
GET /v1/calls?limit=20&status=completed&from=2026-01-01

Query Parameters

Paramètre Type Description
limit integer Nombre de résultats (max 100, default 20)
offset integer Offset pour pagination
status string Filtrer par status: initiating, ringing, in-progress, completed, failed
from date Date de début (ISO 8601)
to date Date de fin (ISO 8601)

POST Transférer un appel

Endpoint
POST /v1/calls/{call_id}/transfer
Request Body
{
  "to": "+212520999888",
  "message": "Je vous transfère vers un conseiller."
}

WS WebSocket - Connexion

Connexion WebSocket pour audio streaming bidirectionnel en temps réel.

WebSocket URL
wss://realtime.vocalia.ma/v1/stream?apiKey=voc_sk_live_xxxx
JavaScript
const ws = new WebSocket(
  'wss://realtime.vocalia.ma/v1/stream?apiKey=voc_sk_live_xxxx'
);

ws.onopen = () => {
  // Envoyer configuration initiale
  ws.send(JSON.stringify({
    type: 'config',
    agentId: 'agent_support_fr',
    language: 'fr',
    sampleRate: 16000
  }));
};

ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  if (data.type === 'audio') {
    // Jouer l'audio de réponse
    playAudio(data.audio);
  }
};

WebSocket - Événements

audio

Audio PCM 16-bit mono encodé en base64 à jouer.

transcript

Transcription en temps réel (partielle et finale).

function_call

L'agent veut exécuter une fonction (transfer, booking, etc.).

end

Fin de la conversation avec résumé et metadata.

Webhooks - Configuration

Configurez des webhooks pour recevoir des notifications en temps réel sur vos appels.

Exemple de payload webhook
{
  "event": "call.completed",
  "timestamp": "2026-01-29T15:32:07Z",
  "data": {
    "callId": "call_abc123xyz",
    "duration": 127,
    "status": "completed",
    "sentiment": "positive",
    "leadScore": 85
  }
}

Webhooks - Types d'événements

Événement Description
call.initiated Appel initié, en attente de connexion
call.ringing Téléphone sonne chez le destinataire
call.answered Appel décroché, conversation en cours
call.completed Appel terminé avec succès
call.failed Appel échoué (occupé, pas de réponse, etc.)
call.transferred Appel transféré vers un humain
lead.qualified Lead qualifié (score BANT disponible)
booking.created RDV créé via l'agent vocal

Webhooks - Sécurité

Validez l'authenticité des webhooks avec la signature HMAC-SHA256.

Node.js - Vérification signature
const crypto = require('crypto');

function verifyWebhook(payload, signature, secret) {
  const expected = crypto
    .createHmac('sha256', secret)
    .update(payload)
    .digest('hex');

  return crypto.timingSafeEqual(
    Buffer.from(signature),
    Buffer.from('sha256=' + expected)
  );
}

AUTH Authentication Endpoints

User registration, login, JWT management, and password flows.

POST /api/auth/register

Register a new user + auto-provision tenant with API key.

// Request
{ "email": "user@example.com",
  "password": "secure123",
  "name": "John Doe",
  "company": "Acme Corp",
  "plan": "pro" }

// Response 201
{ "success": true,
  "tenant": { "id": "acme_corp_k7m2", "api_key": "vk_a1b2c3..." },
  "provisioned": true }
POST /api/auth/login

Login with email/password. Returns JWT access + refresh tokens.

POST /api/auth/refresh

Refresh JWT token using refresh_token.

GET /api/auth/me

Get current user profile. Requires Bearer token.

PUT /api/auth/me

Update user profile (name, company, language).

POST /api/auth/logout POST /api/auth/forgot POST /api/auth/reset POST /api/auth/verify-email PUT /api/auth/password

TENANT Tenant Management

Multi-tenant configuration: origins, API keys, webhooks, usage, and GDPR compliance.

GET /api/tenants/:id/usage

Unified usage dashboard: plan, quotas (calls/sessions/KB), conversation count, features.

// Response
{ "plan": "pro",
  "quotas": {
    "calls": { "used": 42, "limit": 500, "pct": 8 },
    "sessions": { "used": 156, "limit": 2000, "pct": 8 }
  },
  "features_enabled": ["voice_widget", "cloud_voice", "webhooks"] }
GET PUT /api/tenants/:id/allowed-origins

CORS domain management for widget embed. Max 10 origins per tenant.

GET /api/tenants/:id/api-key POST /api/tenants/:id/api-key/rotate

Read and rotate API keys (vk_ format). Rotation is audit-logged.

GET PUT /api/tenants/:id/webhooks

Configure outbound webhook endpoints with HMAC-SHA256 signing. 8 event types. Pro+ plans only.

GET PUT /api/tenants/:id/widget-config

Widget display configuration: branding, position, features, persona.

GET PUT /api/tenants/:id/actions

Tenant automation actions (booking, CRM, email, SMS triggers).

DELETE /api/tenants/:id/data

GDPR right-to-erasure. Erases conversations, KB, UCP. Requires confirmation: "DELETE_ALL_DATA_{tenantId}".

BILLING Billing & Subscriptions

Stripe-powered billing: checkout sessions, subscriptions, portal, and usage-based metering.

GET /api/tenants/:id/billing

Get invoices and billing history for tenant.

POST /api/tenants/:id/billing/checkout

Create Stripe Checkout session. Returns redirect URL. Body: { priceId, successUrl, cancelUrl }.

POST /api/tenants/:id/billing/portal

Stripe Customer Portal link for self-service subscription management.

GET /api/tenants/:id/billing/subscription POST /api/tenants/:id/billing/cancel

KB Knowledge Base

Smart knowledge base with hybrid search and tenant isolation.

GET /api/tenants/:id/kb — List entries
POST /api/tenants/:id/kb/import — Import documents
POST /api/tenants/:id/kb/crawl — Web crawler
GET /api/tenants/:id/kb/search — Semantic search
DELETE /api/tenants/:id/kb/:entryId POST /api/tenants/:id/kb/rebuild-index GET /api/tenants/:id/kb/diagnostics GET /api/tenants/:id/kb/quota GET /api/kb/stats

ECOM E-Commerce Catalog

WooCommerce/Shopify connector, semantic product search, AI recommendations, catalog sync, and cart recovery.

GET /api/tenants/:id/catalog — List products
POST /api/tenants/:id/catalog/search — Search products
POST /api/tenants/:id/catalog/recommendations — AI recommendations
GET /api/tenants/:id/catalog/:productId POST /api/tenants/:id/catalog/browse POST /api/tenants/:id/catalog/import POST /api/tenants/:id/catalog/sync GET /api/tenants/:id/catalog/connector GET /api/catalog/connectors POST /api/recommendations POST /api/leads POST /api/cart-recovery GET /api/cart-recovery POST /api/promo/generate POST /api/promo/validate

DATA Conversations & UCP

Conversation history, call recordings, unified customer profiles, and data export.

GET /api/tenants/:id/conversations — List all
GET /api/tenants/:id/calls — Paginated call list with duration & transcripts
GET /api/tenants/:id/conversations/:sessionId GET /api/tenants/:id/conversations/export GET /api/tenants/:id/ucp/profiles GET /api/tenants/:id/widget/interactions POST /api/ucp/sync POST /api/ucp/interaction POST /api/ucp/event

ADMIN Admin & Operations

System health, HITL moderation, telephony stats, NLP operator, and export.

GET /api/health GET /api/db/health GET /api/admin/engine-stats GET /api/hitl/pending GET /api/hitl/history GET /api/hitl/stats POST /api/hitl/approve/:id POST /api/hitl/reject/:id GET /api/telephony/stats GET /api/telephony/cdrs POST /api/nlp-operator POST /api/quota/sync GET /api/logs GET /api/exports/:id

79 endpoints across 7 domains. All endpoints require JWT Bearer authentication (except /api/health and /api/auth/register). Tenant-scoped endpoints enforce ownership check: you can only access your own tenant's data.

Codes d'erreur

Code Status Description
invalid_api_key 401 Clé API invalide ou expirée
insufficient_permissions 403 Permissions insuffisantes pour cette action
resource_not_found 404 Ressource non trouvée (appel, agent, etc.)
invalid_phone_number 400 Numéro de téléphone invalide (format E.164)
rate_limit_exceeded 429 Limite de requêtes dépassée
insufficient_credits 402 Crédits insuffisants pour cette opération
agent_not_configured 400 Agent non configuré ou désactivé
internal_error 500 Erreur interne, réessayez plus tard

Rate Limits

Plan Requêtes/min Appels simultanés
Starter 60 5
Pro 300 25
Enterprise 1000+ 100+

Headers de rate limit

X-RateLimit-Limit: 300
X-RateLimit-Remaining: 287
X-RateLimit-Reset: 1706540400

SDKs & Libraries

Node.js

npm install @vocalia/sdk
Available

Python

pip install vocalia
Available

Ruby

REST API via net/http
require 'net/http'
require 'json'

uri = URI('https://api.vocalia.ma/respond')
res = Net::HTTP.post(uri,
  { message: 'Bonjour',
    language: 'fr',
    tenant_id: 'your_tenant'
  }.to_json,
  'Content-Type' => 'application/json',
  'Authorization' => "Bearer #{api_key}"
)
puts JSON.parse(res.body)

Go

REST API via net/http
import ("bytes"; "net/http"; "encoding/json")

body, _ := json.Marshal(map[string]string{
  "message":   "Bonjour",
  "language":  "fr",
  "tenant_id": "your_tenant",
})
req, _ := http.NewRequest("POST",
  "https://api.vocalia.ma/respond",
  bytes.NewBuffer(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+apiKey)
resp, _ := http.DefaultClient.Do(req)

Prêt à intégrer VocalIA ?

Créez votre compte et obtenez vos clés API en quelques minutes.

Restez informé des actualités IA conversationnelle

Recevez nos conseils IA conversationnelle et mises à jour produit.