Chat Widget Setup

Instrutions to integrate and use the Tugi Widget

The following guide explains how to integrate and use the Tugi Widget in your web application. The widget provides two main methods: initialize and refresh. The integration process involves importing the widget's script into your HTML and setting up the necessary configurations, including generating a JWT (JSON Web Token) to authenticate users.

Required Values

Tugi Tark provides several values to help with JWT creation:

- Issuer: "https://yourwebsite.com" (Your homepage)

- Audience: "https://tugi.ai"

- Secret: "J4DX67****************************************"

- Token lifetime: 3200 seconds

These should be included in your code as demonstrated.

Step 1: Import the Tugi Widget Script


First, include the Tugi Widget script in your webpage.

Here is an example of how to embed it within your HTML:

<!doctype html>

<html lang="en">

  <head>
    ...
  </head>
 
 <body>
    ...
    
    <!-- tugi-widget -->
    
    <script crossorigin="anonymous" src="https://app.tugi.ai/tugi.widget/script"></script>
    
    <!-- end of tugi-widget -->
    
  </body>

</html>
Step 2: Initialize the Widget

To initialize the widget, use the initialize method with the required options. Here's how to define the options:


Widget Initialize Options

- jwtFn: A function that generates the JWT token client-side.

- tenantId: The ID of your tenant (provided by Tugi Tark).

- brandId: The ID of your brand (provided by Tugi Tark).

- brandName: The name of your brand (provided by Tugi Tark or Client).

- customize (optional): A customization object with optional fields like title logo colors etc.

- httpUrl (optional): The URL for HTTP connections (e.g., https://app.tugi.ai/tugi.widget provided by Tugi Tark ).

- wsUrl (optional): The URL for WebSocket connections (e.g., wss://ws.tugi.ai provided by Tugi Tark).


Example Code (TypeScript):


const tenantId = "tugitark";

const brandId = "192e43************************************";

const brandName = "Your brand name";

const httpUrl = "https://app.tugi.ai/tugi.widget";

const wsUrl = "wss://ws.tugi.ai";

const loadWidget = async () => {

  window.tugiWidget.initialize({

    jwtFn: retrieveJwt, // Function to generate JWT

    tenantId: tenantId,

    brandId: tenantId,

    brandName: tenantId,

    httpUrl: httpUrl,

    wsUrl: wsUrl,

  });

}
Step 3: Refreshing the Widget

To refresh the widget (e.g., when user login details change), call the refresh method:

const changeLogin = () => {

  window.tugiWidget.refresh();

}
Step 4: Generating a JWT

To authenticate the widget, you need to generate a JWT. The widget expects a function (jwtFn) that creates and returns the JWT.

Here’s an example using the jose library to generate the token:

const issuer = ref("https://yourwebsite.com");

const audience = ref("https://tugi.ai");

const secret = ref("JA3DXDD*****************************************")

const lifetimeSeconds = ref("3200");

const endUserEmail = ref("userLoggedIn@email.com"); //User e-mail that's logged in your website

const endUserName = ref("userFirstName"); //User first name

const endUserLastName = ref("userLastName"); //User last name

const endUserSubject = ref("1");

const retrieveJwt = async () => {

  const lifetime = parseFloat(lifetimeSeconds.value);

  const claimsPayload = isAuthenticated.value

    ? {

      name: endUserName.value,

      last_name: endUserLastName.value,

      display_name: endUserName.value,

      email: endUserEmail.value

    }

    : {};

  console.log(

    `Generating JWT with claims payload ${claimsPayload} with secret ${secret.value} and lifetime of ${lifetime}`

  );

  const token = await generateJwt(

    claimsPayload,

    secret.value,

    audience.value,

    issuer.value,

    isNaN(lifetime) ? 3200 : lifetime,

    isAuthenticated.value ? endUserSubject.value : null

  );

  jwt.value = token;

  console.log(`Generated JWT: ${token}`);

  return token;

};
Step 5: JWT Generation Function

The function generateJwt is responsible for generating a signed JWT using the jose library. Here’s how the function works:


Parameters

- claimsPayload: The payload with user-specific data (e.g., name, email).

- secret: A secret key to sign the token (provided by Tugi Tark).

- audience: The intended recipient of the token (provided by Tugi Tark).

- issuer: The issuer of the token (provided by Tugi Tark).

- lifeTimeSeconds: The token's expiration time.

- subject (optional): The subject of the token (e.g., user ID).


Example Code (TypeScript):

import * as jose from "jose";

export const generateJwt = async (

  claimsPayload: jose.JWTPayload,

  secret: string,

  audience: string,

  issuer: string,

  lifeTimeSeconds: number,

  subject: string | null

): Promise<string> => {

  const secretEncoded = new TextEncoder().encode(secret);

  const alg = "HS256";

  const typ = "JWT";

  const currentDateUtc = new Date();

  const beforeTimeMs = currentDateUtc.getTime() - 60 * 1000;

  const beforeDate = new Date(beforeTimeMs);

  const expirationTimeMs = currentDateUtc.getTime() + lifeTimeSeconds * 1000;

  const expirationDate = new Date(expirationTimeMs);

  const payload = new jose.SignJWT(claimsPayload)

    .setProtectedHeader({ alg, typ })

    .setIssuedAt(currentDateUtc)

    .setNotBefore(beforeDate)

    .setAudience(audience)

    .setIssuer(issuer)

    .setExpirationTime(expirationDate);

  if (subject) {

    payload.setSubject(subject);

  }

  const jwt = await payload.sign(secretEncoded);

  return jwt;

};
Step 6: Widget Customization

Coming soon...