# Lynn’s User Guide

Welcome to the next step in your journey with us!

Below, you'll find a carefully curated selection of learning resources designed to assist you in smoothly onboarding Lynn onto your platform.

These materials are structured to provide you with a comprehensive understanding of the process, ensuring that Lynn's integration is as seamless and efficient as possible.

## Documentation Guide

***

## Setting Up the Widget

[Building Up the Knowledge Base](/building-up-the-knowledge-base)

[Creating a Widget](/creating-a-widget)

[Add Suggested Questions to Your Widget](/add-suggested-questions-to-your-widget)

## How to Feed Lynn

[How to Update Your Knowledge Base](/how-to-update-your-knowledge-base)

[Setting Up Model Answers](/setting-up-model-answers)

## Integrating Lynn with Your Platform

[How to Embed A Chat Widget](/how-to-embed-a-chat-widget)

[Personality Customization](/personality-customization)

[How to Handover to Human Support](/how-to-handover-to-human-support)

[Trending Topics: AI Categorisation for Insightful Conversation Analysis](/trending-topics-ai-categorisation-for-insightful-conversation-analysis)

[Reports Dashboard](/reports-dashboard)

## API Access

[Lynn Javascript API](/lynn-javascript-api)

[ Webhooks](/webhooks)


# Building Up the Knowledge Base

To start creating a knowledge base in Lynn, click on the “Create a New Knowledge Source” block or the “Add Knowledge Source” button in the top right corner.

<figure><img src="https://2762017608-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FWsuD6nsscVhXqYf6UuRj%2Fuploads%2FH6k4dB9NHNTRrXFJlH9X%2FUntitled-2023-11-25-2030.png?alt=media&amp;token=f1476481-bd9c-4f96-9e9a-c1bd32a81aa6" alt=""><figcaption><p>Lynn’s Dashboard: Create knowledge sources by the using the knowledge base screen</p></figcaption></figure>

Once you do that, a side bar will appear with various options. Here, you can customize and create a knowledge source. You can add multiple knowledge sources to create your knowledge base.

<figure><img src="https://2762017608-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FWsuD6nsscVhXqYf6UuRj%2Fuploads%2FLsNofWnq0Jy504zCf5Lr%2FUntitled-2023-11-25-2030%201.png?alt=media&amp;token=952c592e-d8c3-44dd-8128-f619a8cffbe6" alt=""><figcaption><p>Lynn’s Dashboard: Personalize the knowledge source according to the knowledge using the side bar</p></figcaption></figure>

The options in the sidebar provide you with the tools to customize and add knowledge sources into Lynn. Let's take a look at what each option offers:

* **Title:** This is where you can give your knowledge source a unique title that makes it easy to identify later on.
* **Tags:** Tags allow you to categorize and organize your content effectively. Use this feature to assign keywords or labels that succinctly describe your content, making it easy to find and reference later on.
* **Source Type:** Here, you can add a link to your website.

  * **Webpage**: If you want Lynn to focus on just one page of your website, simply select “Web Pages” as the option. Then, simply add the URL of the desired webpage in the “Webpage URL” field. Lynn will then focus on and crawl only the data from that specified webpage.
  * **Website**: If you select “website” as your source type, you can provide either the sitemap or the base URL of your website. Lynn will then crawl all webpages under the base URL or those included in the sitemap, except for any links you've listed in the “Excluded URLs' section separate by a new line.
  * **Model Answers:** This is where you can add additional knowledge directly to Lynn, refining the existing knowledge provided by another source. Refer to the article below for the additional information about adding a model answer.

  [Setting Up Model Answers](/setting-up-model-answers)

  * **Notion:** In this section, you can connect directly to your Notion workspace to manage access for the pages that Lynn should include in the knowledge base. Once you select “Notion” you will see a button called Connect Notion in the bottom right corner. After clicking on it, you will be redirected to a page where you can select the pages that Lynn should access to pick up the knowledge.

<figure><img src="https://2762017608-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FWsuD6nsscVhXqYf6UuRj%2Fuploads%2Fs9pA72A7F1FWHcuBj2e1%2FUntitled-2023-11-25-2030%202.png?alt=media&amp;token=858bf1ff-1a57-44c0-85bf-fb626242f09f" alt=""><figcaption><p>Lynn’s Dashboard: Add Notion as a knowledge source (Connect Notion)</p></figcaption></figure>

<figure><img src="https://2762017608-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FWsuD6nsscVhXqYf6UuRj%2Fuploads%2FmM8b73QMBWurSY76CrTr%2FUntitled-2023-11-25-2030%203.png?alt=media&amp;token=d1c80fb7-6a69-409b-8607-e04d813b868a" alt=""><figcaption><p>Connect Notion: Select pages and grant access to Lynn to add the selected pages as the knowledge source.</p></figcaption></figure>

> Note: It is recommended to exclude URLs you don't want included in your knowledge base. To do this, simply copy and paste the URL of the page or a list of URLs, each separated by a new line. These URLs won't be added to your knowledge base. If you decide later that you want them to be included, you'll need to add these excluded URLs as a new knowledge source.

Once Lynn has gone through your website, you can still choose which links to include or exclude in your knowledge base. Simply use the toggle associated with the webpages listed in the “view source” section to make your selections (Only available with the website knowledge source).

<figure><img src="https://2762017608-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FWsuD6nsscVhXqYf6UuRj%2Fuploads%2Fv8O3ZpxK1xvTnrIZQ6Kf%2FUntitled.png?alt=media&amp;token=de72b0bc-ae37-476b-aac7-4c4d2545311a" alt=""><figcaption><p>Edit Knowledge Source: Personalize the knowledge source by including or excluding webpages</p></figcaption></figure>

If Lynn can't access the knowledge source due to service unavailability, a 'Retry Crawling' button will appear, allowing you to attempt to add the knowledge source again.

<figure><img src="https://2762017608-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FWsuD6nsscVhXqYf6UuRj%2Fuploads%2FfBRAPXLgO7ByFrrJUYBN%2FUntitled%201.png?alt=media&amp;token=f049a65a-de0c-49c8-9dde-29cc6aadfb99" alt=""><figcaption><p>Retry Knowledge Source: Retry crawling for failed knowledge sources</p></figcaption></figure>


# Creating a Widget

To start creating a widget, just click on 'Create a New Widget' or the 'Create Widget' button at the top right corner.

<figure><img src="https://2762017608-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FWsuD6nsscVhXqYf6UuRj%2Fuploads%2FVDcjpgFU378L30HBSl5P%2FUntitled-2023-11-25-2030.png?alt=media&amp;token=716197fb-e4d5-4733-9e78-da95c69e6dfa" alt=""><figcaption><p>Lynn’s Dashboard: Create and personalize widgets on Widget creation page</p></figcaption></figure>

First, you’ll need to give your widget a name. This name is for internal use only so your team can differentiate between widgets. (Ex: Sales page widget vs. Customer support widget)

<figure><img src="https://2762017608-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FWsuD6nsscVhXqYf6UuRj%2Fuploads%2FgmbGOoBCMAW07XQOKARb%2FUntitled.png?alt=media&amp;token=a053006c-1e3f-47c9-9f75-dc7bb961d97e" alt=""><figcaption></figcaption></figure>

After you've named your widget, you'll see several fields to personalize the personality of your widget. To learn more about how to use the personality customization, please take a look at the article below.

[Personality Customization](/personality-customization)

Once you’ve set the personality for your widget, select “Add” to continue on to the appearance customization screen.

<figure><img src="https://2762017608-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FWsuD6nsscVhXqYf6UuRj%2Fuploads%2Fi2JV8tlBYBPEEt9R7Ixi%2Fapp.lynn.chat_ycVQtaYXyUY8S4cTOABm_widgets_(1).png?alt=media&amp;token=bf68bf92-6d8b-4aad-9819-c781f96228d4" alt=""><figcaption><p>Edit Widget: Customize your widgets on widget customization page (Part 1)</p></figcaption></figure>

<figure><img src="https://2762017608-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FWsuD6nsscVhXqYf6UuRj%2Fuploads%2FdTzNH5kV0wJjR1EzPv6p%2FUntitled%201.png?alt=media&amp;token=0da37a57-ca04-4e70-b4b8-93422cf339be" alt=""><figcaption><p>Edit Widget: Customize your widgets on widget customization page (Part 2)</p></figcaption></figure>

In this section, you'll be able to customize multiple aspects of your widget including the appearance and message suggestions.

* **Widget Name:** This is where you can give your chatbot a unique name that customers will see.
* **Initial** **Message:** This is the first message users will see from your chatbot when it appears on their webpage. This field is not required.
* **Message Suggestions:** You can easily set up quick questions as suggestions that pop up instantly, helping your customers know what to ask your chatbot. This field is not mandatory.
* **Theme:** Personalize the widget's appearance by choosing a color theme. Simply click on the moon icon for a dark theme or the sun icon for a light theme, depending on what suits your style best.
* **Message Color and Widget Bubble Button Color:** Here, you can customize the colors of your chatbot's message text and bubble background. Choose colors from the color picker or enter hex codes directly to precisely match your brand colors.
* **Chat Alignment:** This option allows you to select the side of the screen where you want to Lynn to appear on your site.
* **Enable Raise for Support:** Here, you can choose whether the chat widget should show the button to raise human support or not show it at all within the widget as a button.
* **Show Knowledge Sources in Responses:** This is the option that allows you to choose whether the widget should show the reference articles used for answering the questions within Lynn's responses.

After you click '**Save Changes**', your widget will start loading. Finally, and importantly, you'll see a preview of your creation on the right side, where you can watch your chatbot comes to life.

If you’d like to test the chatbot on your site before embedding it, go ahead and use the widget preview feature which is accessible through the “Widget Preview” button in the top right corner.

<figure><img src="https://2762017608-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FWsuD6nsscVhXqYf6UuRj%2Fuploads%2FCGah3yM7qUnmignSrebY%2FUntitled%202.png?alt=media&amp;token=f303310c-c7a3-429c-bc84-92156c6ab035" alt=""><figcaption></figcaption></figure>


# Add Suggested Questions to Your Widget

"Now, you can set up quick questions to instantly suggest inquiries for your chatbot. Here's how:

1. Navigate to the “Customize” page and enter your desired quick questions in the “Message Suggestions” section.

<figure><img src="https://2762017608-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FWsuD6nsscVhXqYf6UuRj%2Fuploads%2FScvv5OygejthScXcKVvc%2FUntitled.png?alt=media&amp;token=76737a27-05ca-43de-83ba-9d8965fa2a76" alt=""><figcaption><p>Edit Widget: Add message suggestions on widget customization page (Part 1)</p></figcaption></figure>

1. Hit “Enter” or click on the “+” button to submit these as message suggestions.
2. Don't forget to click “Save Changes” to finalize your changes. It’s that easy.
3. See the quick questions pop up on your chat widget.

<figure><img src="https://2762017608-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FWsuD6nsscVhXqYf6UuRj%2Fuploads%2FepnHR5vvTy8clLpRo86E%2FUntitled%201.png?alt=media&amp;token=ecb1ec84-8a7f-4665-8c65-a3274bddfc1e" alt=""><figcaption><p>Lynn’s Widget: The way that message suggestions appealing on Lynn’s widgets</p></figcaption></figure>


# How to Update Your Knowledge Base

Lynn will automatically crawl your website every month if you activate the auto-recrawl feature.

<figure><img src="https://2762017608-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FWsuD6nsscVhXqYf6UuRj%2Fuploads%2FwUg25vc81j1EaBRVj4vV%2FUntitled.png?alt=media&amp;token=9cd58a8f-bc8b-429f-a8b6-04f5f72d826c" alt=""><figcaption></figcaption></figure>

Lynn offers two recrawling behaviors, allowing you to choose how you want your site to be recrawled.

* **Whole Site Revamp:** In case you've given your website a complete overhaul, Lynn will do a thorough sweep. This ensures Lynn's knowledge base is perfectly aligned with all the new additions and deletions on your updated site.
* **Focused Updates:** If your updates are limited to the pages we've already crawled and tracking, choose this option. Lynn will concentrate on updating those specific pages and leave the rest unchanged

If you need to update your knowledge source in the meantime, Lynn is always ready to incorporate new information. This means you can delete your existing knowledge source and add it again as a new one with updated knowledge.


# Setting Up Model Answers

While Lynn does a great job with answering the vast majority of questions, occasionally it gets something wrong. These mistakes usually stem from one of these common causes: the customer asks a question that cannot be answered by your existing knowledge sources or, Lynn may misunderstand some of the content in your knowledge sources.

To improve Lynn’s ability to tackle these questions, simply head over to the “History” tab to access previous conversations. This is where you can find and improve Lynn's responses to previously asked questions.

<figure><img src="https://2762017608-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FWsuD6nsscVhXqYf6UuRj%2Fuploads%2F8fENHrLOkBngkq1PlATI%2FUntitled.png?alt=media&amp;token=7d140988-bf7d-4539-9939-6bc426ed052a" alt=""><figcaption></figcaption></figure>

Then, click on the small grey icon located to the left of the chat bubble where Lynn gave an incorrect response. This opens a side bar where you can edit or rewrite a better answer to the question.

💡 If you're making a small change, like switching “Edit Widget” to “Customize Widget”, it's a good idea to rephrase the entire sentence. This makes the correction clearer and helps Lynn learn better.

Edit the model answer as you see fit and then click “Add.” Your changes will be stored in the “Model Answers” tab in the Knowledge Base tab. You can then test Lynn by asking the same question again to see if it now provides a satisfactory answer.

<figure><img src="https://2762017608-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FWsuD6nsscVhXqYf6UuRj%2Fuploads%2FsZHQJmxeS4pPbH96SGca%2FUntitled%201.png?alt=media&amp;token=3e30213f-46a2-406e-a155-d6a2dff4fbce" alt=""><figcaption></figcaption></figure>

Alternatively, you can add a model answer as a new knowledge source in the Knowledge Base tab.

<figure><img src="https://2762017608-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FWsuD6nsscVhXqYf6UuRj%2Fuploads%2FZpFKMzDqrmLfGb0dbAaF%2FUntitled%202.png?alt=media&amp;token=13f6ea21-2779-41ca-96ed-e0b84ecf2f5f" alt=""><figcaption></figcaption></figure>

After successfully creating the model answer, the status will be changed to `Active` to show that the model answer creation has been completed.

<figure><img src="https://2762017608-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FWsuD6nsscVhXqYf6UuRj%2Fuploads%2FwUOffRbxgMYXo0CsXsgA%2FUntitled%203.png?alt=media&amp;token=30f70629-07ed-4668-b882-388c4141e271" alt=""><figcaption></figcaption></figure>

You can view a full overview of your model answers in the “Model Answers” tab. Lynn will be trained to remember these model answers and respond accurately when faced with similar questions in the future.


# How to Embed A Chat Widget

In the digital era, chat widgets are crucial for businesses to engage with customers. By embedding a chat widget on your site, you offer instant support, enhance engagement, and potentially increase sales. An automated chatbot like Lynn adds even more appeal to your website and what you have to offer.

After you're done creating a widget, you'll get a code to embed it into your website. This code can be found while you're creating the widget, or later by visiting the widgets page in your workspace.

To find the guide for creating a widget, simply head over to the link provided below.

[Creating a widget](/creating-a-widget)

<figure><img src="https://2762017608-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FWsuD6nsscVhXqYf6UuRj%2Fuploads%2F8OG9pz71LSjXxRdXpbhW%2FUntitled.png?alt=media&amp;token=d330bcaf-ad2b-4f94-80f9-9747b4708e5c" alt=""><figcaption></figcaption></figure>

<figure><img src="https://2762017608-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FWsuD6nsscVhXqYf6UuRj%2Fuploads%2Fc3K0hxtCmWK3bT07VkqX%2FUntitled%201.png?alt=media&amp;token=5a810230-b3b4-4204-82c1-eb17cba954e1" alt=""><figcaption></figcaption></figure>

Once you are equipped with the code now it's time to integrate the chat widget into your site. Simply open your site's HTML code and paste the embed code within the **`<body>`** tag. Remember to save your changes and then test the widget to make sure it's functioning properly.

With the chat widget active on your site, you're all set to start responding to chats quickly. This is a key step in offering outstanding customer support and fostering lasting connections with your customers.

By following the simple steps in this guide, you can quickly and effortlessly embed a chat widget on your site.


# Personality Customization

With personality customization, you have the flexibility to tailor the prompt to your organization's preferences, ensuring it aligns perfectly with your unique perspective and goals. Customize it to suit your needs and style, making it a perfect fit for your organization's voice and character.

You have the ability to fine-tune and personalize the prompt according to the following parameters.

* **Role:** Specify Lynn's role within your organization that it should emulate. (Ex: Customer Success Team Member)
* **Traits:** Traits shape the personality of the chatbot, influencing its communication style, the tone of its responses, and its overall approach to customer service. You can select up to four of these traits as personalization parameters for your widget.
* **Organization’s Name:** Here, Include the exact name of your company as Lynn will represent it in conversations.
* **Organization’s Description:** Provide a brief description of your company's services or products. This will help Lynn to contextualize responses and align with your company’s offerings.

You can customize these while creating the widget or within the customization settings of the widget at any time.

Additionally, you can include the organization name and description in the workspace settings to automatically populate them when creating a widget. This feature also allows you to edit the organization name and description in bulk for already created widgets.

**Note:** In the brief description of your company's services or products, you should use the present tense to convey the current and ongoing nature of your offerings. This approach keeps the description relevant and immediate, helping Lynn to provide responses that are in line with what your company is currently providing to its customers.


# How to Handover to Human Support

While Lynn offers great benefits by automating customer interactions, it's important to remember that it operates within the existing capabilities of AI technology.

Because of that, occasionally, your AI chatbot might not have the answers to all questions. In such cases, a human agent can step in to handle queries the chatbot can't. To enable users to reach human support, just follow these easy steps below.

## Setting up the Handover Rule Feature

To set up the handover, head over to the “Handover Rules” tab. There, you can click on the “Add Handover Rule” block, or simply use the “Add Handover Rule” button located at the top right corner.

<figure><img src="https://2762017608-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FWsuD6nsscVhXqYf6UuRj%2Fuploads%2FbBiAK3PscjHaKV565fh1%2FUntitled.png?alt=media&amp;token=9bd932a2-d662-487a-8107-ad2ed85f603e" alt=""><figcaption></figcaption></figure>

Once you do that, a side bar will appear with various options. Here, you can customize and create a handover rule just the way you want it.

<figure><img src="https://2762017608-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FWsuD6nsscVhXqYf6UuRj%2Fuploads%2FxHGwsCV0FknB2gBA4iHJ%2FUntitled%201.png?alt=media&amp;token=3f347f22-4e26-43dc-a696-418931762cba" alt=""><figcaption></figcaption></figure>

The side bar options allow you to customize and create a handover rule for the AI chatbot to human support transition. Here's a breakdown of the options:

1. **Title:** Here, you can name your handover rule with a unique title that makes it easy to identify later on.
2. **Trigger Conditions:** Under trigger conditions, you have several conditions that can be set to trigger a handover. These conditions are checked during each customer interaction with Lynn and when multiple options are selected, **ALL** conditions must be satisfied for the handover to occur.
   1. **Direct Handover:** This trigger includes three specific scenarios, with only one being able to be chosen for each handover role.
      1. **Customer wants to talk to a human:** When this option is selected, Lynn will hand over any conversation where a customer specifically asks for human support.
      2. **Lynn fails to answer using the available knowledge base:** When this option is selected, Lynn hands over the conversation when it fails to answer the question from the knowledge base.
      3. **Lynn uses the selected model answer in a reply:** This option will hand the conversation over when Lynn uses the model answer selected, to answer a question. Further, you can select whether Lynn should capture the email address or not for this handover rule.
   2. **Customer gives a 👎 feedback:** This option will initiate a handover upon receiving a thumbs-down from a customer.
   3. **Confidence Score (AI-Generated Metadata):** With this option, you can set a percentage threshold for AI-confidence, below which a handover is triggered.
   4. **Satisfaction Score (AI-Generated Metadata):** With this option you can set a percentage threshold for customer satisfaction, below which a handover is triggered.
3. **Rule Type:** You can select the type of handover rule to create. Choose either 'Email Rule', 'Webhook Rule', or both from the available options. If you have Tidio integrated with your workspace, it will also be available as an option.
4. **Email Addresses or** **Webhook URL**: The field where you can enter the endpoint URL for the webhook or the email addresses for Lynn to send a message to when a handover is triggered.

With these options, you can craft a customized handover rule that smoothly transitions interactions from Lynn to human support whenever necessary.

For more information on working with webhooks, you can go through the detailed article provided below.

[Webhooks](/webhooks)

## Begin getting conversations that Lynn isn't equipped to handle

After activating your handover rules, you will start receiving handovers either as emails in your inbox or as <mark style="color:red;">`POST`</mark> requests to your webhook. While Lynn's AI may not handle every conversation, it's smart enough to identify those needing human support. Plus, users also have the option to trigger a manual handover request when needed.

Feel free to check out the examples below for more insight

<figure><img src="https://2762017608-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FWsuD6nsscVhXqYf6UuRj%2Fuploads%2FUTGXdIwtFvPoTuAPMfMc%2FUntitled-2024-09-01-1839.png?alt=media&amp;token=4dfe15ba-7235-4c25-9764-80b3ebd5206c" alt=""><figcaption><p>Lynn’s Email Handover: The way that Lynn handover the conversations to the emails</p></figcaption></figure>

<figure><img src="https://2762017608-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FWsuD6nsscVhXqYf6UuRj%2Fuploads%2Fpqr7cqHIvquROWtqWs2p%2FUntitled-2024-09-01-1839%201.png?alt=media&amp;token=a8bb50a0-411f-466d-9b50-dd66ee1c4172" alt=""><figcaption><p>Lynn’s Webhook Handover: The way that Lynn handover the conversations to the webhooks</p></figcaption></figure>

If a customer is willing to share their email with you, you can easily reach out to them via email for any additional support they might need just by clicking on the reply button in their message.

**Note**

* When multiple options are selected, all of the options need to be fulfilled to trigger a handover.
* The nested options under the Direct Handover cannot be combined under the same handover rule. You will need to create separate rules for each.


# Trending Topics: AI Categorisation for Insightful Conversation Analysis

The "Trending Topics" section in your analytics dashboard seems to list the most frequently discussed topics by users within a given timeframe.

Trending Topics in Lynn, plays a pivotal role in the analysis and categorization of conversation summaries, streamlining the process of interaction classification.

By parsing through conversation metadata, Lynn is able to generate topics automatically, ensuring that each conversation is sorted with precision. Through its algorithms, Lynn evaluates and determines whether a conversation aligns with a pre-existing topic, necessitates the establishment of a new category, or falls outside the norm as an outlier.

## How Lynn Generates the Trending Topics

This intelligent categorization aids in maintaining a well-organized and efficient system for managing customer interactions.

Operating with a keen eye for detail, Lynn performs a daily analysis at the end of each day in UTC, or upon expiration of cached analytics during your live interactions. It meticulously looks back over the past three days to gather metadata from recent conversations and outliers, integrating this information to generate relevant topics.

In addition to recognizing new trends, Lynn also incorporates these conversations into existing topic categories, provided they align with subjects identified within the last 30 days.

**Note:** Lynn is unable to generate topics in two scenarios:

1. If the daily conversations are less than 10.
2. If the sum of conversations for a certain day and its subsequent days, which are included in the already selected three days, is also less than 10.


# Reports Dashboard

Here, you can take a quick look at how many chats Lynn is having with customers. Notice a spike? That could be a promotional success or a product issue. A dip? Maybe it’s time to boost your marketing efforts.

**Note**: Please ensure that the selected date range for the charts is within 7 days to 100 days to obtain accurate insights and trends.

* **Conversation Trends Chart**: This shows the volume of conversations over time within the selected date range. It allows you to identify trends, such as peak times or days when conversation volume is high or low.
* **Messages Trends Chart**: Similar to the Conversation Trends Chart, this tracks the number of messages exchanged rather than the number of conversations. It can give you insight into how engaged users are and how complex the conversations might be.
* **User Satisfaction Trends Chart**: This tracks user satisfaction over time. It indicates how many users expressed satisfaction or dissatisfaction with the service they received. Note that "N/A" means there is no available data for the selected period or that the user hasn't provided any feedback regarding the conversation.
* **Problem Resolution Trends Chart**: This indicates the percentage of conversations that were resolved without human assistance. High percentages suggest effective communication with users through Lynn in resolving user issues.
* **Compositions of Tags**: The tags section breaks down the types of interactions by keywords or tags that were generated by AI according to the conversation.
  * **Occurrences**: The number of times the tag was mentioned in conversations.
  * **Composition Percentage**: The percentage that this tag represents out of all tags.
  * **Occurrences Over Time**: A visual representation of the tag's frequency over the selected date range.

This dashboard is a powerful tool for understanding the performance and efficiency of your customer support or chat service. You can use this data to make informed decisions about staffing, training, and improving automated systems.


# Lynn Javascript API

Lynn provides a JavaScript API to control some of the widget functionalities. This guide will teach you how to use the Javascript API to interact with the widget.

## **Prerequisites**

* [Integrate a widget into the target webpage.](https://www.notion.so/lynn-docs/How-do-I-add-Lynn-to-my-website-620d963e9fda44c5bd61dc3d3f2ddb92)

Once you integrate a widget into a webpage, Lynn attaches a global variable `LynnAPI` to the `window` object. This variable is your gateway to interacting with Lynn programmatically.

## API features

### Detect when Lynn widget is ready to be used (`LynnAPI.onLoad`)

Method signature: `onLoad(callbackFn: () => unknown):void`

Example snippet:

```jsx
LynnAPI.onLoad(handleLynnWidgetLoaded);

function handleLynnWidgetLoaded(){
	// Do stuff
}
```

### Set **conversation metadata (`LynnAPI.setMetadata`)**

Method signature: `setMetadata(key: string, value: unknown):void`

Example snippet:

```jsx
LynnAPI.onload(setupWidget);

function setupWidget(){
	LynnAPI.setMetadata('foo', 'bar');
}
```

Once you set metadata to a conversation, it can be accessed through Lynn’s back office & in handover requests.

<figure><img src="https://2762017608-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FWsuD6nsscVhXqYf6UuRj%2Fuploads%2FwJjTro5dUMsfqFVFKwnX%2FUntitled.png?alt=media&amp;token=37ea233a-9b73-4e34-accf-c19258f23ead" alt=""><figcaption></figcaption></figure>

Screenshot showcasing where you can find metadata in a conversation through Lynn’s back-office application

### Remove conversation metadata (`LynnAPI.removeMetadata`)

Method signature: `removeMetadata(key: string):void`

Example snippet:

```jsx
if(somethingHasHappened){
	LynnAPI.removeMetadata('foo');
}
```

### Reset conversation metadata (`LynnAPI.resetMetadata`)

Method signature: `resetMetadata():void`

Example snippet:

```jsx
if(needToResetAllMetadata){
	LynnAPI.resetMetadata();
}
```

This is going to clear all the metadata that had been set.

### Open widget (`LynnAPI.open`)

Method signature: `open():void`

Example snippet:

```jsx
LynnAPI.onlad(() => {
	LynnAPI.open();
});
```

### Close widget (`LynnAPI.close`)

Method signature: `close():void`

Example snippet:

```jsx
if(needToCloseTheWidget){
	LynnAPI.close();
}
```

### **Send chat message (`LynnAPI.sendMessage`)**

Method signature: `sendMessage(text:string):void`

Example snippet:

```jsx
if(err){
	// Open the widget
	LynnAPI.open();

	// Send message
	LynnAPI.sendMessage(`Hey, I'm on page ${pageUrl} and I'm running into ${err.message}. What can I do?`);
}
```

### **Adjusting the Position of the Lynn Widget (`LynnAPI.updateWidgetPositionConfig`)**

Method Signature: \*\*\*\*`updateWidgetPositionConfig(config: { yOffset: number, xOffset: number, zIndex: number }): void`

This method allows you to customize the position and stacking order of the Lynn widget on your page by specifying the vertical offset (**`yOffset`**), horizontal offset (**`xOffset`**), and z-index (**`zIndex`**).

Example snippet:

```jsx
LynnAPI.updateWidgetPositionConfig({
  yOffset: 50, // Vertical offset in pixels
  xOffset: 200, // Horizontal offset in pixels
  zIndex: 100  // Stacking order
});
```

**Function Description**

* **`yOffset`**: The number of pixels to move the widget up from its default position/bottom of the page.
* **`xOffset`**: The number of pixels to move the widget to the right/left from its default position/start or end of the page.
* **`zIndex`**: The CSS z-index property specifies the stack order of the widget. A higher index means the widget will be in front of other elements.

**Notes**

* Ensure that the Lynn API is fully loaded and available before calling this function. You might want to call this function within the **`LynnAPI.onLoad`** callback to ensure the API is ready.
* Adjusting the **`zIndex`** is particularly useful in complex layouts where multiple elements overlap.
* The values for **`yOffset`** and **`xOffset`** are relative to the edge of the page , not the widget's default position.

### **Hiding/Showing the Chat Bubble of the Lynn Widget (`LynnAPI.hideChatBubble` or `LynnAPI.showChatBubble`)**

Method Signature: **`hideChatBubble(): void` or `showChatBubble(): void`**

This method allows you to programmatically hide the chat bubble of the Lynn widget on your page. This can be useful for manage the visibility of the widget under certain conditions.

```jsx
if(needToHideTheWidget){
	LynnAPI.hideChatBubble();
} else {
	LynnAPI.showChatBubble();
}
```

**Note**

* Ensure that the Lynn API is fully loaded and available before calling this function. You might want to call this function within the **`LynnAPI.onLoad`** callback to ensure the API is ready.


# Webhooks

While Lynn's AI-powered chatbots bring significant value by automating customer interactions, it's essential to recognize that they work within the current boundaries of AI technology.

With Lynn, there are several effective methods to address these challenges and ensure customer satisfaction by seamlessly transitioning them to human assistance when the AI encounters limitations. Let's explore how you can leverage Lynn's features to achieve this.

The guide provides you with the capability to configure webhooks to receive a <mark style="color:red;">`POST`</mark> request when a requirement for a human handover event is triggered.

## Setup

The image shows a user interface for setting up handover rules in Lynn.

For the section to add a new handover rule, you should fill in details such as:

* **Title**: The name or identifier for the new rule.
* **Rule Type**: Options to select whether the handover is a webhook rule (as in the example shown) or an email rule.
* **Webhook URL**: The field where the user would enter the endpoint URL for Lynn to send data to when the handover is triggered.

<figure><img src="https://2762017608-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FWsuD6nsscVhXqYf6UuRj%2Fuploads%2FsbdHOIGxLywTT06B878h%2FUntitled.png?alt=media&amp;token=aebb5425-0f67-45d2-8fd7-1c5d3b71b9fb" alt=""><figcaption></figcaption></figure>

* **Secret Key**: Once you've set up the handover rule, you'll notice a part of the screen that keeps the secret key just out of sight. Think of this key as a secret handshake between Lynn and the endpoint. This key is used to sign requests to verify their authenticity.

## Payload

| **Key**          | Type   | Description                                                        |
| ---------------- | ------ | ------------------------------------------------------------------ |
| `conversationId` | String | Identifier for the conversation.                                   |
| `workspaceId`    | String | Identifier for the workspace.                                      |
| `widgetId`       | String | Widget identifier to identify the widget that triggered the event. |
| `messages`       | Array  | An array of messages that exchanged in the conversation.           |
| `createdAt`      | String | Timestamp for when the message was created.                        |
| `updatedAt`      | String | Timestamp for when the message was last updated.                   |
| `contactEmail`   | String | Email address provided by the user who need the support.           |

Example:

```json
{
  "conversationId": "clP5fVfvHISpzpLkJub2",
  "workspaceId": "04JchTJQCSG4GyYobqi1",
  "widgetId": null,
  "messages": [
    { "text": "Hi", "senderRole": "human" },
    {
      "resources": [],
      "text": "Hello! How can I assist you today?",
      "senderRole": "lynn"
    },
    { "text": "I need human support", "senderRole": "human" },
    {
      "resources": [],
      "text": "Sure, would you be able to share your email address for our awesome support team to get back?",
      "senderRole": "lynn"
    },
    {
      "text": "Here's my email address - vinsurakumuthu@gmail.com.",
      "senderRole": "human"
    },
    {
      "resources": [],
      "text": "Well received, thank you!",
      "senderRole": "lynn"
    }
  ],
  "createdAt": "2023-11-23T07:48:23.119Z",
  "updatedAt": "2023-11-23T07:48:59.400Z",
  "contactEmail": "vinsurakumuthu@gmail.com",
  "customMetadata": null
}
```

For testing the functionality of your webhook, you can use [webhook.site](https://webhook.site/) as a convenient tool to simulate receiving and inspecting the requests.

<figure><img src="https://2762017608-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FWsuD6nsscVhXqYf6UuRj%2Fuploads%2FPK2UoXgU4aSIfBrxCtTL%2FUntitled%201.png?alt=media&amp;token=3452f4ce-4bbb-47db-b30a-0b04b06b4a72" alt=""><figcaption></figcaption></figure>

## Receiving the Request

You can easily get the information you need from the request body, just like you would with any request. However, for added security and to prevent spam from people who are aware of your endpoint, it's a good idea to check the `x-lynn-hmac-sha256` in the request header. This helps ensure that only legitimate requests are processed.

To verify the data's authenticity, encrypt the entire request body using `HMAC-SHA256` with a `secret key` that Lynn’s admin portal. Then compare the generated signature with the `x-lynn-hmac-sha256` value in the request headers. If they match, it confirms the message's legitimacy.

The following Next.js code example demonstrates a secure way to handle webhook requests.

[Next.js](/webhooks/next.js)


# Next.js

```jsx
import crypto from 'crypto';
import { NextApiRequest, NextApiResponse } from 'next';
import getRawBody from 'raw-body';

// Raw body is required for signature verification
export const config = {
  api: {
    bodyParser: false
  }
}

async function webhookHandler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method === 'POST') {
    const SECRET_KEY = process.env.SECRET_KEY;

    if (typeof SECRET_KEY !== 'string') {
      throw new Error('No secret key found');
    }

    // Get the raw body of the request
    const rawBody = await getRawBody(req);

    // Generate HMAC-SHA256 signature of the raw body using the secret key
    const signature = hmacSha256(rawBody, SECRET_KEY);

    // Compare the generated signature with the 'x-lynn-hmac-sha256' header
    if (signature !== req.headers['x-lynn-hmac-sha256']) {
      return res.status(400).json({ message: "Signature didn't match" });
    }

    // If the signature matches, parse the JSON body
    const receivedJson = JSON.parse(rawBody.toString());
    console.log('Received:', receivedJson);

    // Respond with a 200 OK status
    res.status(200).end('OK');
  } else {
    // If the request method is not POST, return 405 Method Not Allowed
    res.setHeader('Allow', 'POST');
    res.status(405).end('Method Not Allowed');
  }
}

// Function to generate HMAC-SHA256 signature
function hmacSha256(data: Buffer, secret: string): string {
  return crypto.createHmac('sha256', secret).update(data).digest('hex');
}

export default webhookHandler;
```


# How to Integrate Tidio with Lynn for Seamless Customer Support with Live Agents

It’s true that Lynn is a powerful tool for automating customer interactions, but even the most advanced AI has its limits. Sometimes, a customer might have a question that requires a human touch or a more complex understanding than the chatbot can provide. That's where the Tidio Integration feature comes in, seamlessly bridging the gap between automated service and live support.

By integrating Tidio with Lynn, you can effortlessly transfer conversations from the chatbot to a live agent whenever needed. This ensures your customers always get the assistance they require, whether it's from Lynn or a human agent. Ready to enhance your customer support capabilities? Follow these steps to set up the Tidio integration:

## Set Up Tidio Integration

<figure><img src="https://2762017608-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FWsuD6nsscVhXqYf6UuRj%2Fuploads%2FYgz1E3dzF8vDfPEJbKUc%2Fda7e8043%205c01%204abb%20b254%20c0b5fa45c566.png?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://2762017608-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FWsuD6nsscVhXqYf6UuRj%2Fuploads%2FexI5iwbBUlnKhDNJZlUw%2Fimage.png?alt=media" alt=""><figcaption></figcaption></figure>

1. **Access the Integrations Section:**
   * Go to the **Integrations** tab in your Lynn dashboard to view available third-party integrations.
2. **Configure Your Integration:**
   * Click on **Tidio** to open the configuration settings.
   * **Add Your Tidio Widget Code:** Paste your Tidio widget code snippet into the provided field. You can find this snippet in your Installation tab under the settings of your Tidio account under chat widget settings (use manual install).
3. **Save Your Configuration:**
   * Click **Save Changes** to apply the settings and complete the integration process.
4. **Enable Tidio Integration:**
   * Locate the **Tidio** option and toggle it to **Enabled,** or enable it once directly from the configuration page. This set up the environment to make a connection between Lynn and Tidio.

<div data-full-width="true"><figure><img src="https://2762017608-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FWsuD6nsscVhXqYf6UuRj%2Fuploads%2FskGzRQtepJLgpGwNabJb%2F1bf06d08%2081b9%204441%20a3ae%20939931f67331.png?alt=media" alt=""><figcaption></figcaption></figure></div>

Once you have set up the Tidio integration, you can further customize how and when Lynn hands over conversations to your Tidio agents. This allows you to control the flow of customer interactions and ensure timely human support during your business hours.

## Configuring Handover Actions with Tidio

1. **Access Handover Rules:**
   * Navigate to the **Handover Rules** section in the Lynn dashboard.
2. **Select an Action Type:**
   * Under the **Action Type** settings, you will now see an additional option for **Connect with an Integration**. Select this option to set up your Tidio handover.
   * In the dropdown menu under **Connect with an Integration**, select **Tidio**. This links the handover action directly to your Tidio integration.
3. **Set Active Days:**
   * Under **Settings**, specify the days of the week when your Tidio agents are available. Click on the days (Sun, Mon, Tue, etc.) to select or deselect them. This ensures that handovers only occur when your team is ready to assist.
4. **Define Active Times:**
   * Set the **Active Time** for each selected day. Use the dropdown menus to choose the start and end times in a 12-hour format. This controls the hours during which Lynn will transfer conversations to Tidio.
5. **Select Timezone:**
   * Choose the appropriate **Timezone** from the dropdown menu. This ensures that your handover schedule aligns with your local time and business hours.
6. **Save Changes:**
   * Once all settings are configured, click **Save Changes** to apply your handover rules.

<figure><img src="https://2762017608-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FWsuD6nsscVhXqYf6UuRj%2Fuploads%2F4B4tyVWqFux6ELL1uBIc%2F3ca5694f%202a81%2044c8%209472%20fc5eb2c3e251.png?alt=media" alt=""><figcaption></figcaption></figure>

## Additional Features on Tidio Integration Features

Once your Tidio integration is set up, the customer experience becomes even more interactive and dynamic with these additional features:

* **Live Agent Notification:** When a Tidio agent joins the conversation, your widget will automatically display a message such as "Live agent has Joined" This lets the customer know that a human is now handling their query, adding a personal touch and transparency to the support process.
* **Seamless Conversation End:** When the live agent finishes assisting the customer, they can send a special **END\_CONVERSATION** message. This command will smoothly end the live chat session and hand control back to Lynn. The chatbot can then continue assisting the customer with any additional queries or provide automated follow-ups, ensuring a seamless transition back to AI support.

{% hint style="info" %}
**TIP**

You can set up a [canned response](https://www.tidio.com/panel/settings/canned-responses) from Tidio's end to make this a little easier.
{% endhint %}

<figure><img src="https://2762017608-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FWsuD6nsscVhXqYf6UuRj%2Fuploads%2F0XTfpgtdhWdA5OuP8fd0%2Fwww.tidio.com_panel_settings_canned%20responses.png?alt=media" alt=""><figcaption></figcaption></figure>

### Additional Setup Required in Tidio

To ensure that the Tidio integration works smoothly, there are a few steps you need to complete on the Tidio side:

1. **Set Up Contact Properties:**
   * Configure contact properties in Tidio to sync with the data captured by Lynn. This ensures that all relevant customer information is available to your agents when a conversation is handed over. For example, you might set up properties for the customer's name, email, and previous chat history.
2. **Turn Off Pre-Chat Survey:**
   * To provide a seamless handover experience from Lynn to Tidio, **turning off the pre-chat survey** in Tidio's appearance settings is important. This prevents any interruptions or additional steps for the customer when they are transferred from Lynn to a live agent.

**Note**

* The Tidio integration only works with Direct Handovers.
* The nested options under the Direct Handover cannot be combined under the same handover rule. You will need to create separate rules for each.


# How to Capture Your Leads Through the Lynn’s Widgets

The Lead Capturing feature allows users to collect leads directly from their widget. This feature lets you capture essential user details such as email addresses, phone numbers, and other custom fields. You can customize messages displayed to users during the lead capture process and integrate these leads directly into your system using webhooks.

## How to Enable Lead Capturing

1. **Access the Lead Capture Settings:**
   * Navigate to the widget settings where you want to enable lead capturing.
2. **Enable Lead Capturing:**
   * Toggle the **Enable Lead Capturing** switch to turn on the lead capture feature.
3. **Export Captured Leads:**
   * Here you can use the **Export Captured Leads** button to download all captured leads in a CSV format.

<figure><img src="https://2762017608-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FWsuD6nsscVhXqYf6UuRj%2Fuploads%2FIvSC9lAEuoBT3awAPN2f%2F2aafc251%20829a%2046d9%20848f%203bde4f79fbc3.png?alt=media" alt=""><figcaption></figcaption></figure>

<figure><img src="https://2762017608-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FWsuD6nsscVhXqYf6UuRj%2Fuploads%2F3wYCOK1tMSdaAgCudWm3%2Fc33a50c9%20b9da%2046b1%209b96%2017439c79c186.png?alt=media" alt=""><figcaption></figcaption></figure>

### Customizing Messages and Fields

1. **Customize Acknowledgement and Session End Messages:**
   * **Acknowledgment Message:** This message is displayed to users before collecting their details. Here you can edit the text to create a welcoming message.
   * **Session End Message:** This message is shown after collecting user details. Customize it to thank users or inform them of the next steps.
2. **Configure Fields to Capture:**
   * Click on the **Fields to Capture** section to add or edit fields.
   * **Add Field:** Once you select the field type from the Text, Number, Email, or Mobile Number fields, you can add the field to the questionnaire by clicking on this button.
   * For each field, set:
     * **Request Message:** The prompt shown to users asking for their information.
     * **Appreciation Message:** A confirmation message is shown after the user provides their details. Use placeholders like `{{value}}` to dynamically insert user-provided information.

<figure><img src="https://2762017608-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FWsuD6nsscVhXqYf6UuRj%2Fuploads%2FgGDYf1sBnLaJaIyS2fxU%2Fimage.png?alt=media" alt=""><figcaption></figcaption></figure>

### Integrating with Webhooks

1. **Webhook Connection:**

   * To integrate lead data into your system in real-time, connect your widget to a webhook.
   * **Enter the Webhook URL:** Provide the endpoint URL where lead data will be sent.
   * **Secret Key:** For security purposes, use the provided secret key in your server to verify the authenticity of incoming requests.

   When a lead is captured through Lynn's widget, the information is sent via a webhook. Here’s a breakdown of the webhook body content:

   ```jsx
   {
     "workspaceId": "qprBF5koDdOjmdCPikl2",
     "widgetId": "fwanJl2WUoFqqUkilAKe",
     "leadCaptureId": "RCvTDLf0K3qLN1or3S5Z",
     "fieldValues": {
       "eCQUiOd7YbIGQei0ZMA1o": "Kumuthu",
       "fLR4QPLDMIDaL3jsaKGmI": "email@lynn.chat"
     },
     "createdAt": "2024-09-01T14:31:59.906Z"
   }
   ```

   * **workspaceId**: Unique identifier for your Lynn workspace.
   * **widgetId**: Identifier for the widget that captured the lead.
   * **leadCaptureId**: Unique ID for the lead capture event.
   * **fieldValues**: Contains the captured user data with a unique fieldId (e.g., name, email).
   * **createdAt**: Timestamp of when the lead was captured.

   You may use this data to integrate captured leads into your CRM or database.

   #### Receiving the Request

   You can easily get the information you need from the request body, just like you would with any request. However, for added security and to prevent spam from people who are aware of your endpoint, it's a good idea to check the `x-lynn-hmac-sha256` in the request header. This helps ensure that only legitimate requests are processed.

   To verify the data's authenticity, encrypt the entire request body using `HMAC-SHA256` with a `secret key` that Lynn’s admin portal. Then compare the generated signature with the `x-lynn-hmac-sha256` value in the request headers. If they match, it confirms the message's legitimacy.

   The following Next.js code example demonstrates a secure way to handle webhook requests.

   [Next.js](/how-to-capture-your-leads-through-the-lynns-widgets/next.js)
2. **Testing the Webhook:**
   * Once the webhook is connected, conduct tests to ensure that lead data is correctly being sent and received.

### Managing and Exporting Leads

* All captured leads can be reviewed and exported from the widget’s settings. Ensure your settings are correctly configured to prevent data loss and ensure compliance with data privacy regulations.

**Note**

* Once you change the schema or the set of questions for lead capturing, the leads collected under the previous schema will be cleared. Therefore, we strongly recommend downloading the already captured leads before making any changes to the question schema.
* The questionnaire will appear as soon as a user starts a conversation with Lynn, before Lynn responds to the user's first message.


# Next.js

```javascript
import crypto from 'crypto';
import { NextApiRequest, NextApiResponse } from 'next';
import getRawBody from 'raw-body';

// Raw body is required for signature verification
export const config = {
  api: {
    bodyParser: false
  }
}

async function webhookHandler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method === 'POST') {
    const SECRET_KEY = process.env.SECRET_KEY;

    if (typeof SECRET_KEY !== 'string') {
      throw new Error('No secret key found');
    }

    // Get the raw body of the request
    const rawBody = await getRawBody(req);

    // Generate HMAC-SHA256 signature of the raw body using the secret key
    const signature = hmacSha256(rawBody, SECRET_KEY);

    // Compare the generated signature with the 'x-lynn-hmac-sha256' header
    if (signature !== req.headers['x-lynn-hmac-sha256']) {
      return res.status(400).json({ message: "Signature didn't match" });
    }

    // If the signature matches, parse the JSON body
    const receivedJson = JSON.parse(rawBody.toString());
    console.log('Received:', receivedJson);

    // Respond with a 200 OK status
    res.status(200).end('OK');
  } else {
    // If the request method is not POST, return 405 Method Not Allowed
    res.setHeader('Allow', 'POST');
    res.status(405).end('Method Not Allowed');
  }
}

// Function to generate HMAC-SHA256 signature
function hmacSha256(data: Buffer, secret: string): string {
  return crypto.createHmac('sha256', secret).update(data).digest('hex');
}

export default webhookHandler;
```


