JavaScript

クライアント側アプリケーションの作成

という名前のHTMLファイルを作成する。 client_js.html.以下のコードを追加するが、先のステップでユーザー用に生成したJWTを貼り付けることを確認する:

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

これは、Client SDKを使用して電話に発信するWebアプリケーションです。

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

  1. 電話をかけるボタン。
  2. 電話を切るためのボタン。
  3. このコードは、先に生成されたJWTを使ってセッションを作成する。
  4. そして、通話ボタンと電話を切るボタンの2つのイベントリスナーをセットアップする。
    1. 最初のリスナーは serverCall 関数を使って発信します。ウェブフック・サーバーは、リクエスト・ボディの宛先電話番号を受信し、コールをルーティングします。
    2. 番目のリスナーは hangup で通話を終了する。
  5. 着信側からのレッグステータス更新のために、別のイベントハンドラが設定される。相手が応答すると、電話を切るボタンが表示され、通話ボタンは非表示になります。