Search code examples
tokenbotframework

Token Generation for Botframework Webchat


I've been migrating my Direct Line Bot from Webchat v3 to v4. The new version demands the use of tokens rather than the Direct Line secret in the calling page. Here is the code (index.html) used to start the bot:

<!DOCTYPE html>
<html lang="en-US">
<head>
    <title>Web Chat: Full-featured bundle</title>

    <script src="https://cdn.botframework.com/botframework-webchat/master/webchat.js"></script>

    <style>
         html, body {
            height: 100%
        }

         body {
            margin: 0
        }

         #webchat,
         #webchat > * {
             height: 100%;
             width: 100%;

        }


    </style>
</head>
<body>
       <div id="webchat" role="main"></div>

    <script>
    (async function () {
        const res = await fetch('https://bellamspt.azurewebsites.net/Forms/Webchat/directline/token', { method: 'POST' });

      const { token } = await res.json();

      window.WebChat.renderWebChat({
        directLine: window.WebChat.createDirectLine({ token })
      }, document.getElementById('webchat'));

      document.querySelector('#webchat > *').focus();
    })().catch(err => console.error(err));
   </script>
</body>
</html>

Question: What code do I need to write to generate the token in other to be called by https://bellamspt.azurewebsites.net/Forms/Webchat/directline/token ?? Realize it's got to be something like

POST https://directline.botframework.com/v3/directline/tokens/generate
Authorization: Bearer SECRET

but I don't know if it's got to be a php, js or other type of file to work.

Thanks in advance


Solution

  • I used php to solve this. You could give it a try.

    <?php
    $botSecret = '<your secret>';
    $response = wp_remote_get( 'https://webchat.botframework.com/api/tokens', array( 'headers' => 'Authorization: BotConnector ' . $botSecret ) );
    if( is_array($response) ) {
      $header = $response['headers'];
      $token = $response['body'];
    }
    ?>
    <script type="text/javascript">
            var webChatToken = <?php echo $token; ?>;
    </script>