How to auto fillup the user information fetched from application where I integrated tawk and show them when user opens the widget?

I have used tawk chat-bot into my application. Now I want the functionality that when a user log in to the app and open the chat widget the user info such as name email auto fill there from the database of my application and show it there rather showing this interface.

I used the following code but it does not work yet.
`
// @ts-ignore
import TawkMessengerReact from ‘@tawk.to/tawk-messenger-react’;
import CryptoJS from ‘crypto-js’;
import { useCallback, useEffect, useRef } from ‘react’;

interface ITawkComponent {
authUser: any;
lang: string;
}

declare global {
interface Window {
Tawk_API: any; // Adjust the type accordingly if you have more specific information about the Tawk API
}
}

const TawkComponent: React.FC = ({ authUser, lang }) => {
const tawkMessengerRef = useRef();

// Function to hash user ID
function hashInBase64(userId: string): string {
const secretKey = ‘b4a7d6783ff8**********f3c952d2a561dba883’;
const hash = CryptoJS.HmacSHA256(userId, secretKey);
const hashInBase64 = CryptoJS.enc.Hex.stringify(hash);
return hashInBase64;
}

const loginToTawk = useCallback(() => {
if (!authUser) return; // Check if user information is available

const hash = hashInBase64(authUser.userId);

window.Tawk_API = window.Tawk_API || {};
window.Tawk_API.login(
  {
    hash: hash,
    userId: authUser.userId,
    name: authUser.userName,
    email: authUser.userEmail,
  },
  function (error: any) {
    if (error) {
      console.error('Error occurred while logging in to Tawk:', error);
      // Handle error if needed
    } else {
      console.log('User logged in to Tawk successfully');
      // You can add further actions if login is successful
    }
  }
);

}, [authUser]);

const onChatMaximized = useCallback(() => {
loginToTawk();
}, [loginToTawk]);

useEffect(() => {
const script = document.createElement(‘script’);
script.async = true;
script.charset = ‘UTF-8’;
script.setAttribute(‘crossorigin’, ‘*’);

const widgetId = lang === 'en' || lang === 'de' ? '1g***d3ld' : '1ge***ccu';
script.src = `https://embed.tawk.to/633605c******e12d8979f6c/${widgetId}`;

script.onload = () => {
  window.Tawk_API = window.Tawk_API || {};
  window.Tawk_API.onLoad = () => {
    // Additional logic on Tawk load if needed
  };
};

document.head.appendChild(script);

return () => {
  document.head.removeChild(script);
};

}, [lang]);

return (
<TawkMessengerReact
propertyId=‘633605ce12d8979f6c’
widgetId={lang === ‘en’ || lang === ‘de’ ? '1g
d3ld’ : '1ge
ccu’}
ref={tawkMessengerRef}
onChatMaximized={onChatMaximized}
/>
);
};

export default TawkComponent;
`

How can get my desired functionality?

1 Like

[quote=“Shihab7432 Socrates GM, post:1, topic:3218”]
I used the following code but it does not work yet.
`
// @ ts-ignore
import TawkMessengerReact from ‘@ tawk . to/tawk-messenger-react’;
import CryptoJS from ‘crypto-js’;
import { useCallback, useEffect, useRef } from ‘react’;

interface ITawkComponent {
authUser: any;
lang: string;
}

declare global {
interface Window {
Tawk_API: any; // Adjust the type accordingly if you have more specific information about the Tawk API
}
}

const TawkComponent: React.FC = ({ authUser, lang }) => {
const tawkMessengerRef = useRef();

// Function to hash user ID
function hashInBase64(userId: string): string {
const secretKey = ‘b4a7d6783ff8**********f3c952d2a561dba883’;
const hash = CryptoJS.HmacSHA256(userId, secretKey);
const hashInBase64 = CryptoJS.enc.Hex.stringify(hash);
return hashInBase64;
}

const loginToTawk = useCallback(() => {
if (!authUser) return; // Check if user information is available

const hash = hashInBase64(authUser .userId);

window.Tawk_API = window.Tawk_API || {};
window.Tawk_API.login(
  {
    hash: hash,
    userId: authUser.userId,
    name: authUser.userName,
    email: authUser.userEmail,
  },
  function (error: any) {
    if (error) {
      console.error('Error occurred while logging in to Tawk:', error);
      // Handle error if needed
    } else {
      console.log('User logged in to Tawk successfully');
      // You can add further actions if login is successful
    }
  }
);

}, [authUser]);

const onChatMaximized = useCallback(() => {
loginToTawk();
}, [loginToTawk]);

useEffect(() => {
const script = document.createElement(‘script’);
script.async = true;
script.charset = ‘UTF-8’;
script.setAttribute(‘crossorigin’, ‘*’);

const widgetId = lang === 'en' || lang === 'de' ? '1g***d3ld' : '1ge***ccu';
script.src = `https://embed.tawk.to/633605c******e12d8979f6c/${widgetId}`;

script.onload = () => {
  window.Tawk_API = window.Tawk_API || {};
  window.Tawk_API.onLoad = () => {
    // Additional logic on Tawk load if needed
  };
};

document.head.appendChild(script);

return () => {
  document.head.removeChild(script);
};

}, [lang]);

return (
<TawkMessengerReact
propertyId=‘633605ce12d8979f6c’
widgetId={lang === ‘en’ || lang === ‘de’ ? '1g
d3ld’ : '1ge
ccu’}
ref={tawkMessengerRef}
onChatMaximized={onChatMaximized}
/>
);
};

export default TawkComponent;
`

How can get my desired functionality?
[/quote]

Hello, @Shihab7432

To autofill user information in the Tawk chat widget from your application’s database, you can use the Tawk API to set the visitor’s name and email. Here’s a simplified version of your code that should achieve this:

import TawkMessengerReact from ‘@tawk.to/tawk-messenger-react’;
import { useEffect } from ‘react’;

const TawkComponent = ({ authUser, lang }) => {
// Function to hash user ID
const hashInBase64 = (userId) => {
const secretKey = ‘your-secret-key’;
return btoa(CryptoJS.HmacSHA256(userId, secretKey).toString());
};

useEffect(() => {
const script = document.createElement(‘script’);
script.async = true;
script.charset = ‘UTF-8’;
script.setAttribute(‘crossorigin’, ‘*’);
const widgetId = lang === ‘en’ || lang === ‘de’ ? ‘widget-id-1’ : ‘widget-id-2’;
script.src = https://embed.tawk.to/your-property-id/${widgetId};

script.onload = () => {
  if (authUser) {
    window.Tawk_API = window.Tawk_API || {};
    window.Tawk_API.visitor = {
      name: authUser.userName,
      email: authUser.userEmail,
      hash: hashInBase64(authUser.userId)
    };
  }
};

document.head.appendChild(script);
return () => {
  document.head.removeChild(script);
};

}, [authUser, lang]);

return ;
};

export default TawkComponent;

Make sure to replace ‘your-secret-key’, ‘widget-id-1’, ‘widget-id-2’, and ‘your-property-id’ with your actual secret key, widget IDs, and property ID. Also, ensure that the hashInBase64 function is correctly implemented and that you’re using the correct hashing algorithm as per Tawk.to’s requirements.

If you want more details please tell me I am happy to help you.

Best Regard,
ryan1969

1 Like

Thank you so much for your help. I tried your way by following the following code. But I don’t see it working.

// @ts-ignore
import TawkMessengerReact from ‘@tawk.to/tawk-messenger-react’;
import CryptoJS from ‘crypto-js’;
import { useCallback, useEffect, useRef } from ‘react’;
import UserId from ‘…/…/…/pages/admin/user-info/[userId]’;

interface ITawkComponent {
lang: string;
}

declare global {
interface Window {
Tawk_API: any; // Adjust the type accordingly if you have more specific information about the Tawk API
}
}

const TawkComponent: React.FC = ({ lang }) => {
console.log(‘Form tawk:’, lang);

const tawkMessengerRef = useRef();
// const hash = CryptoJS.HmacSHA256(‘hello X4T’, ‘1ge5gd3ld’);
// const hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
// Function to hash user ID
const hashInBase64 = (userId: any) => {
const secretKey = ‘1ge5gd3ld’;
const hash = CryptoJS.HmacSHA256(userId, secretKey);
return CryptoJS.enc.Base64.stringify(hash);
};

const onChatMaximized = useCallback(() => {
tawkMessengerRef.current.setAttributes(
{
userId: localStorage.getItem(‘userId’),
},
function (error: any) {
console.log(error);
}
);

tawkMessengerRef.current.setAttributes(
  {
    name: localStorage.getItem('userName'),
  },
  function (error: any) {
    console.log(error);
  }
);

tawkMessengerRef.current.setAttributes(
  {
    email: localStorage.getItem('userEmail'),
  },
  function (error: any) {
    console.log(error);
  }
);

tawkMessengerRef.current.setAttributes(
  {
    hash: hashInBase64(UserId),
  },
  function (error: any) {
    console.log(error);
  }
);

}, );

useEffect(() => {
// Dynamically create and append the Tawk script
const script = document.createElement(‘script’);
script.async = true;
script.charset = ‘UTF-8’;
script.setAttribute(‘crossorigin’, ‘*’);

const widgetId =
  lang === 'en' || lang === 'de' || lang === 'es'
    ? '1ge5gd3ld'
    : '1gepgeccu';
script.src = `https://embed.tawk.to/633605c554f06e12d8979f6c/${widgetId}`;

script.onload = () => {
  window.Tawk_API = window.Tawk_API || {};
  window.Tawk_API.onLoad = () => {
    // Additional logic on Tawk load if needed
  };
  ///////
  window.Tawk_API.visitor = {
    name: localStorage.getItem('userName'),
    email: localStorage.getItem('userEmail'),
    hash: hashInBase64(localStorage.getItem('userId')),
  };
};

document.head.appendChild(script);

// Clean up the script tag when the component unmounts
return () => {
  document.head.removeChild(script);
};

}, [lang]);

return (
<>
{localStorage.getItem(‘userId’) ? (

) : (

)}
</>
);
};

export default TawkComponent;

Please, give me your feedback as soon as possible.

Regards,
Shihab