Primera llamada saliente
serverCall() inicia una llamada saliente enviando el contexto de la llamada a la API de Vonage. A continuación, la API de Vonage invoca tu webhook de respuesta con el contexto como custom_data, y tu webhook devuelve un NCCO que determina el enrutamiento.
Flujo de salida
- Llamadas de la aplicación de cliente
serverCall(context). - La API de Vonage activa tu webhook de respuesta con el contexto siguiente:
custom_data. - Tu webhook devuelve NCCO.
- La API de Vonage conecta el contenido multimedia con el destinatario de la llamada.
Fragmento del cliente
const context = {
to: 'sip:alice@example.com',
from: 'agent-123'
};
try {
const callId = await client.serverCall(context);
console.log(`Outbound call started, callId: ${callId}`);
} catch (error) {
console.error('Failed to start outbound call', error);
}
val context = mapOf(
"to" to "sip:alice@example.com",
"from" to "agent-123"
)
client.serverCall(context) { error, callId ->
if (error != null) {
println("Failed to start outbound call: $error")
return@serverCall
}
println("Outbound call started, callId: $callId")
}
HashMap<String, String> context = new HashMap<>();
context.put("to", "sip:alice@example.com");
context.put("from", "agent-123");
client.serverCall(context, (error, callId) -> {
if (error != null) {
System.out.println("Failed to start outbound call: " + error);
return null;
}
System.out.println("Outbound call started, callId: " + callId);
return null;
});
let context = [
"to": "sip:alice@example.com",
"from": "agent-123"
]
client.serverCall(context) { error, callId in
guard error == nil, let callId = callId else {
print("Failed to start outbound call: \(error?.localizedDescription ?? "unknown")")
return
}
print("Outbound call started, callId: \(callId)")
}
NSDictionary *context = @{
@"to": @"sip:alice@example.com",
@"from": @"agent-123"
};
[client serverCall:context callback:^(NSError * _Nullable error, VGCallId _Nullable callId) {
if (error != nil || callId == nil) {
NSLog(@"Failed to start outbound call: %@", error);
return;
}
NSLog(@"Outbound call started, callId: %@", callId);
}];
Webhook de respuesta del servidor
El ejemplo que aparece a continuación muestra el formato que debe tener la respuesta del webhook. Tu implementación concreta variará en función del lenguaje y el marco de trabajo de tu backend.
Tu webhook de respuesta debe ser accesible públicamente y devolver un NCCO válido.
Uso "type": "app" en el punto final de conexión para desviar la llamada a un Client SDK por nombre de usuario. Utiliza "type": "phone" para desviar la llamada a un número de la red pública de telefonía (PSTN). Consulta el Tipos de puntos finales de NCCO Connect para todas las opciones.
const customData =
(req.body.custom_data as { to?: string } | undefined) ?? {};
const destination = customData.to ?? 'callee-username';
const answerNcco = [
{
action: 'connect',
endpoint: [
{
type: 'app',
user: destination
}
]
}
];
res.json(answerNcco);
Referencia NCCO: aquí
Gestión de errores
serverCall Puede fallar si no hay ninguna sesión activa, si se agota el tiempo de espera del establecimiento de la llamada o si la API de Vonage detecta un problema con tu webhook. Gestiona siempre el error:
try {
const callId = await client.serverCall({ context });
console.log("Call started:", callId);
} catch (error) {
console.error("Call failed:", error.type, error.message);
}
client.serverCall(context) { error, callId ->
if (error != null) {
println("Call failed: ${error.message}")
// Common causes:
// - No active session (call createSession first)
// - Network timeout
// - Answer webhook returned invalid NCCO
return@serverCall
}
println("Call started: $callId")
}
client.serverCall(context) { error, callId in
if let error = error {
print("Call failed: \(error.localizedDescription)")
return
}
print("Call started: \(callId ?? "")")
}
Para consultar una lista completa de los posibles tipos de error, véase Errores.