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:

  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 establece dos escuchadores de eventos para los botones de llamada 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á a hangup para finalizar la llamada.
  5. 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á.