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.
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
https://api.vocalia.ma/v1
https://sandbox.api.vocalia.ma/v1
Voice Widget - Intégration
Intégrez le Voice Widget en ajoutant simplement une balise script à votre page.
<!-- 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
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.
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 -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
{
"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
GET /v1/calls/{call_id}
{
"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
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
POST /v1/calls/{call_id}/transfer
{
"to": "+212520999888",
"message": "Je vous transfère vers un conseiller."
}
WS WebSocket - Connexion
Connexion WebSocket pour audio streaming bidirectionnel en temps réel.
wss://realtime.vocalia.ma/v1/stream?apiKey=voc_sk_live_xxxx
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.
{
"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.
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.
/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 }
/api/auth/login
Login with email/password. Returns JWT access + refresh tokens.
/api/auth/refresh
Refresh JWT token using refresh_token.
/api/auth/me
Get current user profile. Requires Bearer token.
/api/auth/me
Update user profile (name, company, language).
TENANT Tenant Management
Multi-tenant configuration: origins, API keys, webhooks, usage, and GDPR compliance.
/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"] }
/api/tenants/:id/allowed-origins
CORS domain management for widget embed. Max 10 origins per tenant.
/api/tenants/:id/api-key
POST
/api/tenants/:id/api-key/rotate
Read and rotate API keys (vk_ format). Rotation is audit-logged.
/api/tenants/:id/webhooks
Configure outbound webhook endpoints with HMAC-SHA256 signing. 8 event types. Pro+ plans only.
/api/tenants/:id/widget-config
Widget display configuration: branding, position, features, persona.
/api/tenants/:id/actions
Tenant automation actions (booking, CRM, email, SMS triggers).
/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.
/api/tenants/:id/billing
Get invoices and billing history for tenant.
/api/tenants/:id/billing/checkout
Create Stripe Checkout session. Returns redirect URL. Body: { priceId, successUrl, cancelUrl }.
/api/tenants/:id/billing/portal
Stripe Customer Portal link for self-service subscription management.
KB Knowledge Base
Smart knowledge base with hybrid search and tenant isolation.
/api/tenants/:id/kb — List entries
/api/tenants/:id/kb/import — Import documents
/api/tenants/:id/kb/crawl — Web crawler
/api/tenants/:id/kb/search — Semantic search
ECOM E-Commerce Catalog
WooCommerce/Shopify connector, semantic product search, AI recommendations, catalog sync, and cart recovery.
/api/tenants/:id/catalog — List products
/api/tenants/:id/catalog/search — Search products
/api/tenants/:id/catalog/recommendations — AI recommendations
DATA Conversations & UCP
Conversation history, call recordings, unified customer profiles, and data export.
/api/tenants/:id/conversations — List all
/api/tenants/:id/calls — Paginated call list with duration & transcripts
ADMIN Admin & Operations
System health, HITL moderation, telephony stats, NLP operator, and export.
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
Python
pip install vocalia
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.