Embed Chatbot into Your Website
Integrating a chatbot into your web application is straightforward; however, due to user authentication requirements, a session is necessary for interaction with the chatbot.
In this tutorial, you will learn the steps to incorporate a chatbot into your web application effectively.
If you are familiar with Stripe, you will find this process similar. Just as with Stripe, you need to generate a session on your backend and then direct the user to the session URL.
Step 1: Create a New Authorized Session
To initiate a new session, please call the following API from your backend to retrieve the session URL.
curl --location 'https://www.askyourdatabase.com/api/chatbot/v2/session' \
--header 'Accept: application/json, text/plain, */*' \
--header 'Accept-Language: en' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer ${{API_KEY}}' \
--data-raw '{
"chatbotid": "${{botid}}",
"name": "Sheldon",
"email": "test@gmail.com"
}'
Notice you have to pass the API key in the Authorization header like the following:
Authorization: Bearer ${{API_KEY}}
To get the API key, you can create a new API key in the API Key Page.
The response should resemble the following, it's basically an OAuth callback URL:
{"url":"https://www.askyourdatabase.com/api/chatbot/auth/callback?code=abcdefg"}
After receiving the URL, you can create an iframe in your web application using this URL to load the chatbot.
Step 2: Load the Chatbot
You can use our official Next.js demo (opens in a new tab) Github repository to learn the code.
Here's an example code snippet for next.js for loading the chatbot in your web app:
Backend code:
import { NextRequest, NextResponse } from "next/server";
export const revalidate = 0;
export const dynamic = "force-dynamic";
export async function POST(req: NextRequest) {
const { url } = await fetch("https://www.askyourdatabase.com/api/chatbot/v2/session", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer ${API_KEY}",
},
body: JSON.stringify({
"chatbotid": "${botid}",
"name": "Sheldon",
"email": "test@gmail.com"
}),
}).then((res) => res.json());
return NextResponse.json({ url });
}
The code snippet above creates an endpoint that generates a new session URL for the chatbot. The URL is then returned to the client to render the iframe.
Front-end code:
"use client";
import { useEffect, useState } from "react";
export default function Home() {
const [iframeUrl, setIframeUrl] = useState("");
useEffect(() => {
fetch("/api/ayd", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({}),
})
.then((res) => res.json())
.then(({ url }) => {
setIframeUrl(url);
});
}, []);
return (
<main>
<iframe
className="mx-auto"
style={{
height: 640,
width: 400,
}}
src={iframeUrl}
></iframe>
</main>
);
}
The code above first fetches the session URL from your backend and then renders the chatbot in an iframe.