JavaScript

Crie o código para realizar uma chamada de voz dentro do aplicativo

Para este tutorial, Alice entrará em contato Bob.

Crie um arquivo HTML chamado client_alice.html e adicione o código a seguir, certificando-se de colar o JWT da Alice — que você gerou na etapa anterior — como o valor para o 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>

Este é o seu aplicativo cliente que utiliza o Client SDK para realizar uma chamada de voz dentro do aplicativo para o destinatário usuário (Bob).

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 para o Bob. Seu servidor de webhook receberá o nome do usuário no corpo da solicitação e encaminhará a chamada.
    2. O segundo ouvinte ligará hangup para encerrar a ligação.