JavaScript

Crear el código para realizar una llamada de voz dentro de la aplicación

Para este tutorial, Alice llamará Bob.

Cree un archivo HTML llamado client_alice.html y añade el siguiente código, asegurándote de pegar el JWT de Alice que generaste en el paso anterior como valor para el campo token constante:

<!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>Outbound App Call (Alice)</h1>
  <button type="button" id="call">Call</button>
  <button type="button" id="hangup">Hang Up</button>

  <script>
    const callButton = document.getElementById("call");
    const hangUpButton = document.getElementById("hangup");
    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") {
        callButton.style.display = "inline";
        hangUpButton.style.display = "none";
      }
    });

    callButton.addEventListener("click", () => {
      console.log("Calling Bob...");
      client.serverCall({ to: 'Bob' })
        .then((_callId) => {
          callId = _callId;
        })
        .catch((error)=>{
          console.error(`Error making call: ${error}`);
        });
    });

    hangUpButton.addEventListener("click", () => {
      console.log("Hanging up...");
      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 la aplicación cliente que utiliza el Client SDK para realizar una llamada de voz dentro de la aplicación al destino. usuario (Bob).

Las principales características de este código son:

  1. Un botón para llamar.
  2. Un botón para colgar.
  3. El código crea una sesión utilizando el JWT generado anteriormente.
  4. A continuación, el código configura dos detectores de eventos para los botones de «Llamar» y «Colgar».
    1. El primer oyente utilizará la función serverCall función para realizar la llamada saliente a Bob. Tu servidor de webhooks recibirá el nombre del usuario en el cuerpo de la solicitud y redirigirá la llamada.
    2. El segundo oyente llamará hangup para finalizar la llamada.