Skip to content
Browse

Universal Chat

Universal Chat Integration

Last updated

Embed Universal Chat in your website or app, configure allowed domains, and pass signed customer details to connect conversations with existing customer profiles.

To integrate Universal Chat into your web page, take the following steps:

  • Set up a brand. In Universal Chat Settings you can customize how Universal Chat behaves and looks. You can also list the domains that are allowed to include Universal Chat.
  • Add the integration code to your web page. Copy the code from Universal Chat Settings and paste it into your web page to show the chat to the customer.
  • Pass customer data to the chat. This is optional but highly recommended, as it links the conversation to the customer's data.

Set Up a Brand

You can set up a Universal Chat brand directly in the Salted CX app. The brand enables you to customize the behavior and look of the chat. You can set up multiple brands to provide different customer experiences for different segments of your customers.

Add every domain where you want to use Universal Chat to the brand setup. Universal Chat doesn't load on domains that aren't listed there.

Include Code in Page

Copy the integration code for the brand of your choice from Universal Chat Settings and paste it into your web page. The code has two parts. Include the following snippet in the head section of the HTML file:

<script type="module" src="https://cdn.salted.cx/universal-chat/universal-chat.js"></script>

Place the following code at the end of the body of your HTML file:

<universal-chat accountId="<domain name in Salted CX without region>" brandId="<unique identifier of the brand from Universal Chat brand settings>"></universal-chat>

The element accepts these attributes:

AttributeRequiredDescription
accountIdYesYour account name in Salted CX, without the region.
brandIdYesThe brand whose chat to show.
regionNoThe region of your account. Defaults to eu.
langNoThe language of the chat, for example en. Changing it reloads the chat.
contextTokenNoThe signed customer data. See Pass Customer Data to Chat below.
openNoWhether the chat window is open.
Example of implementation using JavaScript only
const scriptElement = document.createElement('script');
scriptElement.type = 'module';
scriptElement.src = 'https://cdn.salted.cx/universal-chat/universal-chat.js';

const chatElement = document.createElement('universal-chat');
chatElement.setAttribute('accountId', '<domain name in Salted CX without region>');
chatElement.setAttribute('brandId', '<unique identifier of the brand from Universal Chat brand settings>');

document.body.appendChild(scriptElement);
document.body.appendChild(chatElement);

Pass Customer Data to Chat

Passing customer data enables linking the chat session to a specific customer. This enables Your Logic and human agents to access the customer data. Salted CX requires that you digitally sign the data in a secure environment, such as your server, so that a bad actor cannot impersonate someone else. Salted CX verifies the data on the server side as well.

Each step passes: Timestamp · Customer data · Signature

Pass signed customer data to Universal ChatPass signed customer data to Universal Chat. Your server signs the customer data. The browser passes that signed payload through Universal Chat, and Salted CX verifies it before associating it with the session. Your server: Extract customer information from your systems. Sign the data with your private key. The private key stays on your server. Timestamp, Customer data, Signature pass from Your server to Your web page, then to Universal Chat, then to Salted CX. Salted CX: Check that the timestamp is recent. Verify the signature. Associate the data with the session. Public key: Provided by you in Universal Chat brand settings.BrowserServerYour web pageYour serverUniversal ChatSalted CX123Extract customer informationfrom your systemsSign the data with your privatekeyPrivate key stays hereCheck that the timestamp isrecentVerify the signatureAssociate the data with thesessionPublic key from brand settingsEmbedded on your pagePass signed customer data to Universal ChatPass signed customer data to Universal Chat. Your server signs the customer data. The browser passes that signed payload through Universal Chat, and Salted CX verifies it before associating it with the session. Your server: Extract customer information from your systems. Sign the data with your private key. The private key stays on your server. Timestamp, Customer data, Signature pass from Your server to Your web page, then to Universal Chat, then to Salted CX. Salted CX: Check that the timestamp is recent. Verify the signature. Associate the data with the session. Public key: Provided by you in Universal Chat brand settings.BrowserServerYour web pageYour serverUniversal ChatSalted CX123Extract customerinformation fromyour systemsSign the data withyour private keyPrivate key stayshereCheck that thetimestamp is recentVerify thesignatureAssociate the datawith the sessionPublic key frombrand settingsEmbedded on yourpage
Read diagram as text

Your server signs the customer data. The browser passes that signed payload through Universal Chat, and Salted CX verifies it before associating it with the session.

  1. Your server: Extract customer information from your systems. Sign the data with your private key. The private key stays on the server. Send timestamp, customer data, signature to Your web page.
  2. Your web page passes the same signed payload to Universal Chat in the browser.
  3. Universal Chat sends the payload to Salted CX: Check that the timestamp is recent. Verify the signature. Associate the data with the session.

Public key: Provided by you in Universal Chat brand settings.

Custom Data Format

You need to provide the data in a format supported by Universal Chat. The data is in JSON format.

Properties of the payload:

PropertyTypeDescription
conversationObjectStructured object containing information about the conversation.
customerObjectStructured object containing information about the customer.

Conversation Object

Properties in the conversation object:

PropertyTypeDescription
customJSONAny JSON object with your own data about the conversation.
urgencyNumberHow urgent the conversation is. Higher is more urgent. Salted CX rates urgency from 1 to 5 itself, so use the same scale. Setting it turns off automatic urgency updates for the conversation.
serviceSourceIdStringIdentifier of the service source the conversation belongs to.
serviceExternalIdStringThe ID of the service or product in your system, linking the conversation to the Untitled in reporting. Set it together with serviceSourceId.

Customer Object

Properties in the customer object.

PropertyTypeDescription
contactContact ObjectThe contact this chat session is associated with. This can be an internal customer ID or a global identifier such as an email address.
displayNameStringThe name agents see. It should not contain sensitive personal information. We recommend using the first name.

The length of the value is limited to 100 characters.
firstNameStringFirst name of the customer.

The length of the value is limited to 100 characters.
lastNameStringLast name of the customer.

The length of the value is limited to 100 characters.
languageStringLanguage of the customer as a two-letter code, for example en.
relatedContactsArray of ContactsOther contacts of the same customer. They link the customer to their conversations in other channels, which then appear in the customer journey alongside the current chat.

Learn more about Customer Profile

Contact Object

Properties in the contact object:

PropertyTypeDescription
typeStringType of the contact. Use Email for email addresses and Phone for phone numbers. You can use other values to distinguish the contact type, for example Customer ID for internal customer IDs.
externalIdStringThe contact value itself, such as the ID, phone number or email address.

The length of the value is limited to 100 characters.

Contacts Across Brands

Contacts belong to your account, not to a brand. A customer identified by the same contact on several brands is one contact. Their details, such as the display name and language, are shared by all brands. Each brand's chat still shows only the conversations started on that brand.

Email addresses and phone numbers identify the same contact across your whole account, including conversations in other channels such as email. If you want a separate contact for each brand, identify the customer by your own ID, for example with the type Customer ID, and pass the email address in relatedContacts. Related contacts still connect the customer's conversations in the customer journey. Your IDs must be unique across brands. If two brands can give the same ID to different people, prefix it with the brand, for example eu-shop:12345.

{
	 "conversation": {
		  "custom": {
		  }
	  },

	"customer": {
		"contact": {
			"type": "Customer ID",
			"externalId": "9e065dd3-14e2-4c67-832c-03b320be65c1"
		},
		"displayName": "Carmen",
    "firstName": "Carmen",
    "lastName": "Sanchez",
    "language": "en",
		"relatedContacts": [
			{
				"type": "Email",
				"externalId": "carmen.sanchez@email.com"
			},
			{
				"type": "Phone",
				"externalId": "+420123456789"
			}
		]
	}
}
Example customer data payload

Do NOT include any data that you do not want your customers to see. Customers can read the token's payload, but they cannot change it because it is signed.

Create a JWT token

To pass data to Salted CX, you need to create a JWT token that contains the customer data, an expiration time (exp), and a signature. Salted CX rejects tokens without exp.

  • Generate an RSA key pair. Salted CX only accepts tokens signed with RS256.
  • Store your private key in your secrets manager where your server code can access it.
  • In Universal Chat settings, paste your public key into Context Token Public Key. Salted CX uses it to verify the signature.

To rotate keys, click Add new key in the settings and paste the new public key. The current key becomes the previous key, and tokens signed by either key are accepted. Once your server signs all tokens with the new key, remove the previous one.

Once your signing keys are set up, create a JWT whose payload is the data described above, plus the standard iat and exp claims:

{
  "customer": {
    "contact": {
      "type": "Customer ID",
      "externalId": "9e065dd3-14e2-4c67-832c-03b320be65c1"
    },
    "displayName": "Carmen"
  },
  "iat": 1730314320,
  "exp": 1730314620
}
Example JavaScript code for generating a JWT token
import fs from "node:fs";
import path from "node:path";

import { importPKCS8, SignJWT } from "jose";

async function generateSaltedCXToken(customerData) {
	const privateKeyPEM = fs.readFileSync(path.join("private.key"), "utf8");
	const privateKey = await importPKCS8(privateKeyPEM, "RS256");

	return new SignJWT(customerData)
		.setProtectedHeader({ alg: "RS256" })
		.setIssuedAt()
		.setExpirationTime("5m")
		.sign(privateKey);
}

const jwtToken = await generateSaltedCXToken(
		{
			customer: {
				contact: {
					type: "Customer ID",
					externalId: "<your customer's ID>",
				},
				displayName: "Display Name",
				relatedContacts: [
					{
						type: "Email",
						externalId: "customer@email.com",
					},
					{
						type: "Phone",
						externalId: "+420123456789",
					},
				],
			},
		});

Always create the JWT token with customer data in a secure, controlled environment that the customer cannot access (e.g., a server). Do NOT generate it in the browser on the customer side.

Token Lifetime

Keep tokens short-lived. Anyone who copies a token from your page can act as that customer until it expires. We recommend an expiration of a few minutes and creating a new token for each page load.

A token only has to be valid when Universal Chat receives it. The customer then stays signed in, and the token's data stays available for new conversations, for 24 hours or until the token's expiration, whichever is later. A page that stays open longer must pass a fresh token before that time runs out, otherwise the customer is logged out of chat.

If you accept the risk, you can issue tokens that expire later than 24 hours, and the customer stays signed in until they expire.

Salted CX ignores a token that is expired, has no exp, or is not signed with a key from the settings. Your page gets no error, and the visitor chats anonymously. If the chat does not recognize a customer, check these first.

Pass Customer Data via JavaScript

You need to have the JWT token available on the client side (browser) to pass to Salted CX. The exact way to make it available depends on the tech stack that you are using. Your JavaScript can fetch it from your server, read it from a cookie, or get it any other way that suits your setup.

Once the JWT token is available in the browser, pass it to Universal Chat by setting the contextToken property:

customElements.whenDefined("universal-chat").then(() => {
	document.querySelector("universal-chat").contextToken = jwtToken;
});
Example code to pass the customer data to Salted CX

Prefer setting the property over the contextToken attribute, so the token does not end up in your page's HTML. If you render the token on the server, the attribute works too.

Setting a token for a different customer switches the chat to that customer. A customer who chatted anonymously and then logs in does not see the anonymous conversation.

When the customer logs out of your site, clear the token so the chat drops their identity too:

document.querySelector("universal-chat").contextToken = "";

Control the Chat

Set the open property to open or close the chat window.

The chat has to load before it can receive actions. Call whenReady(), which returns a promise that resolves once the chat is ready, or listen for the ready event. The ready property tells you whether it is ready now.

  • startNewConversation() leaves the current conversation and opens a fresh one, for example when the customer asks about a different order. The conversation is created when the customer sends their first message.
  • goToConversationList() shows the customer's conversation list.
  • insertMessage(text, { replace }) puts text into the message box, for example from a "chat about this" button next to a product or an article. The customer can edit it and sends it themselves. Pass { replace: true } to overwrite what the customer already typed. Otherwise, if the customer has an unsent message in the message box, the returned promise rejects with an error whose code is messageBoxNotEmpty.
await customElements.whenDefined("universal-chat");
const chat = document.querySelector("universal-chat");

async function askAboutOrder() {
	await chat.whenReady();
	chat.startNewConversation();
	chat.open = true;
}

async function chatAbout(product) {
	await chat.whenReady();
	chat.startNewConversation();
	await chat.insertMessage(`I have a question about ${product.name}`);
	chat.open = true;
}

Anonymous Visitors

Visitors without a token chat anonymously, if the brand allows it. Their conversations stay available in that browser until they have been inactive for longer than the brand's anonymous session timeout, 30 days by default. If anonymous chat is disabled for the brand, the chat stays hidden until you set a token.

Content Security Policy

If your website uses a Content Security Policy, allow Universal Chat in it:

  • script-src https://cdn.salted.cx for the script
  • frame-src, connect-src and img-src https://<account>.<region>.salted.cx for the chat window, its configuration and the brand logo, with your account name and region filled in

Embedding in iOS

The webView in the iOS app must handle links with target="_blank" to support downloading documents from Universal Chat. To achieve that, the web view's coordinator should implement the following method:

// Handle target="_blank" links by opening them in Safari
func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
    if let url = navigationAction.request.url {
        print("Opening link in Safari: \(url.absoluteString)")
        UIApplication.shared.open(url)
    }
    return nil
}

Embedding in Android

To give customers all the features of Universal Chat, make sure the Android app has the required permissions.

Ensure the AndroidManifest.xml contains the following permissions:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />

When using WebView ensure that these settings are set:

// Enable JavaScript
webView.settings.javaScriptEnabled = true
webView.settings.domStorageEnabled = true
webView.settings.databaseEnabled = true
webView.settings.cacheMode = WebSettings.LOAD_DEFAULT

// Enable file access
webView.settings.allowFileAccess = true
webView.settings.allowContentAccess = true

// Set DownloadListener to handle file downloads
webView.setDownloadListener { url, userAgent, contentDisposition, mimetype, contentLength ->
	val intent = Intent(Intent.ACTION_VIEW)
	intent.data = Uri.parse(url)
  startActivity(intent)
}

Copy section link

Your browser couldn’t copy automatically. Copy the link below.