JavaScript

In-App Voiceコールを行うコードを作成する。

このチュートリアルのために、 Alice を呼ぶだろう。 Bob.

という名前のHTMLファイルを作成する。 client_alice.html の値として、先のステップで生成したアリスのJWTを貼り付けるようにしてください。 token 一定している:

<!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>

これは、Client SDKを使用して、アプリ内で相手先に音声通話を行うクライアントアプリケーションです。 ユーザー (ボブ)。

このコードの主な特徴は以下の通りである:

  1. 電話をかけるボタン。
  2. 電話を切るためのボタン。
  3. このコードは、先に生成されたJWTを使ってセッションを作成する。
  4. そして、通話ボタンと電話を切るボタンの2つのイベントリスナーをセットアップする。
    1. 最初のリスナーは serverCall 関数を使ってBobに発信します。Webhookサーバーはリクエスト・ボディのユーザーを受け取り、コールをルーティングします。
    2. 番目のリスナーは hangup で通話を終了する。