JavaScript
Crear una aplicación cliente
Cree un archivo HTML llamado client_js.html. Añade el siguiente código, pero asegúrate de pegar el JWT que generaste para el usuario en el paso anterior:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="./node_modules/@vonage/client-sdk/dist/vonageClientSDK.min.js"></script>
<style>
input, button {
font-size: 1rem;
}
#call, #hangup {
display: none;
}
</style>
</head>
<body>
<h1>Call Phone from App</h1>
<label for="phone-number">Your Phone Number:</label>
<input type="text" name="phone-number" value="" placeholder="i.e. 14155550100" id="phone-number" size="30">
<button type="button" id="call">Call</button>
<button type="button" id="hangup">Hang Up</button>
<div id="status"></div>
<script>
const callButton = document.getElementById("call");
const hangUpButton = document.getElementById("hangup");
const statusElement = document.getElementById("status");
const token = 'ALICE_JWT';
const client = new vonageClientSDK.VonageClient();
let callId = null;
client.createSession(token)
.then((sessionId) => {
console.log("Id of created session: ", sessionId);
callButton.style.display = "inline";
})
.catch((error) => {
console.error("Error creating session: ", error);
});
client.on('legStatusUpdate', (callId, legId, status) => {
if (status === "ANSWERED") {
callButton.style.display = "none";
hangUpButton.style.display = "inline";
}
if (status === "COMPLETED") {
callId = null;
callButton.style.display = "inline";
hangUpButton.style.display = "none";
}
});
callButton.addEventListener("click", event => {
const destination = document.getElementById("phone-number").value;
if (destination !== "") {
client.serverCall({ to: destination })
.then((_callId) => {
callId = _callId;
})
.catch((error)=>{
console.error(`Error making call: ${error}`);
});
} else {
statusElement.innerText = 'Please enter your phone number.';
}
});
hangUpButton.addEventListener("click", () => {
client.hangup(callId)
.then(() => {
hangUpButton.style.display = "none";
callButton.style.display = "inline";
})
.catch(error => {
console.error("Error hanging up call: ", error);
});
});
</script>
</body>
</html>
Esta es su aplicación web que utiliza el Client SDK para realizar una llamada saliente a un teléfono.
Las principales características de este código son:
- Un botón para llamar.
- Un botón para colgar.
- El código crea una sesión utilizando el JWT generado anteriormente.
- A continuación, el código establece dos escuchadores de eventos para los botones de llamada y colgar.
- El primer oyente utilizará la función
serverCallpara realizar la llamada saliente. Su servidor webhook recibirá el número de teléfono de destino en el cuerpo de la solicitud y enrutará la llamada. - El segundo oyente llamará a
hanguppara finalizar la llamada.
- El primer oyente utilizará la función
- Otro controlador de eventos se establece para las actualizaciones de estado de la pierna de la persona que llama. Una vez que contesten, se mostrará el botón de colgar y se ocultará el botón de llamar, y cuando finalice la llamada esto se revertirá.
Hacer una llamada de voz dentro de la aplicación
Realiza una llamada de voz desde una aplicación web a un teléfono utilizando el SDK JavaScript Client.
Pasos
1
Introducción2
Prerequisites3
Crear un servidor webhook4
Crear una aplicación de Vonage5
Vincular un número de Vonage6
Crear un usuario7
Generar un JWT8
Instalar Client SDK9
Crear una aplicación cliente10
Ejecute su aplicación11
¿Y ahora qué?