/**
* Fetches an embed token for a customer user and generates an embed URL.
*
* This function demonstrates how to call the GUIDEcx API to obtain an embed token
* for a specific customer user, then constructs an embed URL using the token.
* The URL is intended for use in an iframe to embed GUIDEcx functionality in your application.
*
* @returns {Promise<string>} A promise that resolves to the embed URL.
*/
async function fetchAndGenerateEmbedUrl() {
const apiUrl = 'https://api.guidecx.com/api/v2/users/embed-token';
// Replace this with the actual email of the customer user.
const customerUserEmail = "customer@example.com";
const requestBody = {
customerUserEmail: customerUserEmail
};
const requestOptions = {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_ACCESS_TOKEN', // Replace YOUR_ACCESS_TOKEN with your actual Open API organization token found in the Open API tab of your organization settings.
'Content-Type': 'application/json'
},
body: JSON.stringify(requestBody)
};
try {
const response = await fetch(apiUrl, requestOptions);
if (!response.ok) {
throw new Error(`API request failed with status: ${response.status}`);
}
const responseData = await response.json();
if (!responseData.embedToken || responseData.projects.length === 0) {
throw new Error('Invalid response data: Missing embedToken or projects.');
}
/**
* Construct the embed URL using the embed token and project ID.
* Using the value of responseData.projects[0].id assumes you want to embed the first project that is returned in the list.
* Adjust this value as needed if you have customers that belong to multiple projects.
*/
const embedUrl = `https://app.guidecx.com/auth/customer-login/sso?token=${responseData.embedToken}&projectId=${responseData.projects[0].id}&page=TODAY&email=${customerUserEmail}`;
return embedUrl;
} catch (error) {
console.error('Error fetching embed token:', error);
throw error; // Rethrow to allow error handling by the caller.
}
}
// Example usage
async function runExample() {
try {
const embedUrl = await fetchAndGenerateEmbedUrl();
console.log('Embed URL:', embedUrl);
// Embed the URL in an iframe or handle it as needed.
} catch (error) {
console.error('Failed to generate embed URL:', error);
}
}
// Run the example
runExample();