JavaScript

Crear una aplicación del lado del cliente

Cree un archivo HTML llamado client_js.html. Añade el siguiente código, pero asegúrate de pegar el JWT que has generado 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:

  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 para 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.
    2. El segundo oyente llamará hangup para finalizar la llamada.
  5. Se ha configurado otro controlador de eventos para las actualizaciones del estado de la llamada por parte del destinatario. Una vez que este responda, se mostrará el botón para colgar y se ocultará el botón de llamar; cuando finalice la llamada, se revertirá esta situación.