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 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;
    }
    #answer, #reject, #hangup {
      display: none;
    }
  </style>
</head>

<body>
  <h1>Inbound PSTN phone call</h1>
  <p id="notification">Lines are open for calls...</p>
  <br />
  <button type="button" id="answer">Answer</button>
  <button type="button" id="reject">Reject</button>
  <button type="button" id="hangup">Hang Up</button>

  <script>
    const answerButton = document.getElementById("answer");
    const rejectButton = document.getElementById("reject");
    const hangUpButton = document.getElementById("hangup");
    const notification = document.getElementById("notification");
    const token = 'ALICE_JWT';
    const client = new vonageClientSDK.VonageClient();
    let callId = null;

    client.createSession(token)
      .then(sessionId => {
        console.log("Id of created session: ", sessionId);
      })
      .catch(error  => { 
        console.error("Error creating session: ", error);
      });

    client.on('callInvite', (_callId) => {
      callId = _callId;
      notification.textContent = "You are receiving a call";
      answerButton.style.display = "inline";
      rejectButton.style.display = "inline";
    });

    client.on('legStatusUpdate', (_callId, legId, status) => {
      notification.textContent = `Caller Leg Status is: ${status}`;
    });

    client.on("callHangup", (_callId, callQuality, reason) => {
      console.log(`Call ${_callId} has hung up, callQuality:${callQuality}, reason:${reason}`);
      callId = null;
      notification.textContent = "Lines are open for calls...";
      answerButton.style.display = "none";
      rejectButton.style.display = "none";
      hangUpButton.style.display = "none";
    });

    // Answer the call.
    answerButton.addEventListener("click", () => {
      client.answer(callId)
        .then(() => {
          console.log("Success answering call.");
          notification.textContent = "You are on a call";
          answerButton.style.display = "none";
          rejectButton.style.display = "none";
          hangUpButton.style.display = "inline";
        })
        .catch(error => {
          console.error("Error answering call: ", error);
        });    
    });

    // Reject the call
    rejectButton.addEventListener("click", () => {
      client.reject(callId)
        .then(() => {
          console.log("Success rejecting call.");
          notification.textContent = "You rejected the call";
          answerButton.style.display = "none";
          rejectButton.style.display = "none";
        })
        .catch(error => {
          console.error("Error rejecting call: ", error);
        });          
    });

    // Hang up the call
    hangUpButton.addEventListener("click", () => {
      client.hangup(callId)
        .then(() => {
          console.log("Success hanging up call.");
          notification.textContent = "You ended the call";
          answerButton.style.display = "none";
          rejectButton.style.display = "none";
          hangUpButton.style.display = "none";
        })
        .catch(error => {
          console.error("Error hanging up call: ", error);
        });                
    });
  </script>
</body>

</html>

Esta es su aplicación web que utiliza el Client SDK para aceptar una llamada entrante.

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

  1. Un cuadro de notificación que puede actualizarse con el estado de la llamada.
  2. Un botón para responder a una llamada entrante.
  3. Un botón para rechazar una llamada entrante.
  4. Un botón para colgar una llamada entrante.
  5. El código crea una sesión utilizando el JWT generado anteriormente.
  6. El código establece dos controladores de eventos principales.
    1. El primero se activa cuando se recibe una llamada entrante. Esto a su vez establece 3 controladores de eventos de botón de clic que responde, rechaza y cuelga la llamada entrante utilizando los métodos de Client SDK answer, rejecty hangup respectivamente.
    2. La segunda, recibe actualizaciones del estado del tramo de llamada y establece el texto del cuadro de notificación en el estado de la llamada entrante.