In order to have conversations persist across domains, it is necessary to initialize messenger with an existing cognito identity, so that the conversation can be loaded.
An example of doing this with just an identity is shown below.
<script src="https://servisbotcdn.com/messenger/latest/bundle-messenger.js"></script>
<script>
ServisBot.init({
organization: '{yourOrganization}',
shortBotId: '{yourBotId-within-Organization}',
displayWidget: true,
alwaysOpen: false,
context : { // context can be used for custom properties
phone: "+17811234567",
address: "3250 Airport Blvd, Mobile, AL 36606, USA"
},
identity: '{someCognitoIdentity}'
});
</script>
A more complex and realistic scenario would be storing each customer’s identity in some place, and fetching it before intializing the messenger on each of the desired domains.
A example of using an API to fetch the cognito identity tied to a customer reference is shown below. In this example we check if someCustomerReference
has a associated CognitoIdentity
, and if it does we add it to the ServisBot configuration before initing it.
// check if we have the user in our DB
const res = await fetch(`${API_URL}/check/${someCustomerReference}`, {
method: 'POST',
});
const reference = await res.json();
if (reference?.Exists) {
// set returning user's identity
console.log(`Set identity for ${someCustomerReference} to ${reference.CognitoIdentity}`);
sbConfig.identity = reference.CognitoIdentity;
}
const ServisBotApi = window.ServisBot.init(sbConfig);
The ServisBotApi which gets returned from the ServisBot.init call can be used to find the current customer reference or identity, using getCustomerReference()
or getIdentity()
respectively.
This can be used in combination with .on
to post the identity to a store when the conversation is ready and the identity is assigned. A good event to use for this is type: CONVERSATION
and value: Ready
, which will fire once at the start of a conversation.
For example:
ServisBotApi.on('Messenger', (event) => {
if (event.type === 'CONVERSATION' && event.value === 'Ready') {
const customerReference = ServisBotApi.getCustomerReference();
if (customerReference) {
// store the customer reference : identity pair
fetch(`${API_URL}/store/${customerReference}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
CognitoIdentity: ServisBotApi.getIdentity()
})
});
console.log(`Stored identity for ${customerReference} as ${ServisBotApi.getIdentity()}`);
}
}
});
Keep in mind the APIs in this example do not by default, and need to be created or requested from ServisBot.