Hosted Widgets: Retrieving Customer Details
This tutorial demonstrates how to extract customer authentication details from Cleeng hosted widgets and use them to fetch complete customer data in your (frontend) application.
Imagine you’re running a subscription service that uses Cleeng’s hosted login widget for authentication. A subscriber logs in on your website, and the widget successfully handles the authentication flow. Now, your front-end application needs more than just the fact that the user is logged in - you want to display their name on the homepage, check their subscription status, or personalize their dashboard.
By following these steps, you'll be able to maintain synchronized authentication state and access customer information through Cleeng's API.
Step 1: Initiate the widget and implement token monitoring
Ensure the Cleeng script is included in the <head>
section of your HTML document, and follow the steps as described in the global communication article to implement the onAuthTokensUpdate method and capture the JWT.
Please note that the Cleeng hosted widget automatically handles the refresh logic associated with the JWT.
Step 2: Extract customer ID from JWT token
The widgets return the JWT. Now extract from there the customer ID and place all items in your local Storage.
👉 Note, the JWT contains also the email address.
function extractCustomerIdFromJWT(jwt) {
try {
// Decode JWT to extract customer information
const payload = JSON.parse(atob(jwt.split('.')[1]));
return payload.customerId;
} catch (error) {
console.error('Error decoding JWT:', error);
return null;
}
}
function storeAuthenticationTokens(jwt, refreshToken) {
const customerId = extractCustomerIdFromJWT(jwt);
// Store tokens securely (consider using secure storage)
localStorage.setItem('cleeng_jwt', jwt);
localStorage.setItem('cleeng_refresh_token', refreshToken);
localStorage.setItem('customer_id', customerId);
}
Step 3: Fetch customer data from Cleeng API
With the JWT token and customer ID, you can now fetch complete customer details using Cleeng's fetch customer's data API endpoint.
async function fetchCustomerDetails(jwt) {
const customerId = extractCustomerIdFromJWT(jwt);
if (!customerId) {
console.error('No customer ID found in JWT');
return;
}
try {
const response = await fetch(
`https://mediastoreapi.cleeng.com/customers/${customerId}`,
{
method: 'GET',
headers: {
'Authorization': `Bearer ${jwt}`,
'Content-Type': 'application/json'
}
}
);
if (response.ok) {
const customerData = await response.json();
updateApplicationWithCustomerData(customerData);
} else {
console.error('Failed to fetch customer data:', response.status);
}
} catch (error) {
console.error('Error fetching customer details:', error);
}
}
Note: Once you have the JWT, you can use it for other MediaStore API endpoints, for example entitlements check.
Updated 3 days ago