JavaScript

Criar um aplicativo do lado do cliente

Crie um arquivo HTML chamado client_js.html. Adicione o código a seguir, mas certifique-se de colar o JWT que você gerou para o usuário na etapa 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 é a sua aplicação web que utiliza o Client SDK para fazer uma chamada de saída para um telefone.

As principais características desse código são:

  1. Um botão para ligar.
  2. Um botão para desligar.
  3. O código cria uma sessão usando o JWT gerado anteriormente.
  4. Em seguida, o código configura dois ouvintes de evento para os botões de ligar e desligar.
    1. O primeiro ouvinte utilizará o serverCall função para realizar a chamada de saída. Seu servidor de webhook receberá o número de telefone de destino no corpo da solicitação e encaminhará a chamada.
    2. O segundo ouvinte ligará hangup para encerrar a ligação.
  5. É definido outro manipulador de eventos para as atualizações de status da ligação provenientes do destinatário da chamada. Assim que ele atender, o botão para desligar será exibido e o botão para ligar ficará oculto; quando a ligação terminar, essa configuração será revertida.