Passing CRM Customer ID via Genesys Cloud Web Messaging SDK
What You Will Build
- You will implement a JavaScript function that passes a specific CRM Customer ID into the Genesys Cloud Web Messaging SDK
startChatmethod. - This implementation uses the
genesyscloud-webrtclibrary to inject custom attributes into the session metadata before the chat session is established. - The tutorial uses vanilla JavaScript and the modern Web Messaging SDK v3, ensuring compatibility with current frontend frameworks.
Prerequisites
- Genesys Cloud Account: An active account with Web Messaging enabled.
- Organization ID: Your Genesys Cloud organization ID (found in Admin → Settings → Organization).
- Deployment ID: The Deployment ID for your Web Messaging deployment (found in Admin → Messaging → Deployments).
- SDK Version:
genesyscloud-webrtcv3.x or higher. - Runtime Environment: A modern web browser or Node.js environment with a DOM simulation if testing headlessly.
- Dependencies: None beyond the Genesys Cloud Web Messaging SDK.
Authentication Setup
Web Messaging SDK authentication is handled differently from the REST API. The SDK uses a Deployment ID and Organization ID to establish a WebSocket connection. No OAuth tokens are required for the client-side chat session itself, as the security context is managed by the deployment configuration. However, the attributes you pass (like the CRM ID) must be validated by the deployment rules or downstream flows.
Ensure your deployment is configured to accept custom attributes. In the Genesys Cloud Admin console, navigate to Messaging > Deployments > [Your Deployment] > Attributes. Ensure that the attribute key you intend to use (e.g., crmCustomerId) is whitelisted or allowed by the deployment’s attribute policy.
Implementation
Step 1: Initialize the Web Messaging SDK
First, you must import and initialize the SDK. The initialization object requires the orgID and deploymentID. You will also configure the onSessionStatus callback to monitor the lifecycle of the chat session.
import { WebMessaging } from '@genesyscloud/webrtc';
// Configuration constants
const ORG_ID = 'your-organization-id';
const DEPLOYMENT_ID = 'your-deployment-id';
// Initialize the WebMessaging instance
const webMessaging = new WebMessaging({
orgID: ORG_ID,
deploymentID: DEPLOYMENT_ID,
// Optional: Configure logging for debugging
logLevel: 'debug'
});
// Monitor session status for debugging and UI updates
webMessaging.onSessionStatus((status) => {
console.log('Session Status:', status);
if (status === 'connected') {
console.log('Chat session established successfully.');
} else if (status === 'error') {
console.error('Chat session error occurred.');
}
});
Expected Response:
The initialization does not return a response. It sets up the internal state. The onSessionStatus callback will fire when the WebSocket connects to the Genesys Cloud infrastructure.
Error Handling:
If the ORG_ID or DEPLOYMENT_ID is invalid, the SDK will not throw an immediate error during initialization. The error will manifest when startChat is called, returning a status of error or unauthorized in the onSessionStatus callback.
Step 2: Construct the startChat Payload with CRM ID
The core of this tutorial is passing the CRM Customer ID. In the Genesys Cloud Web Messaging SDK, custom data is passed via the attributes object within the startChat method. These attributes become part of the conversation metadata and are accessible in Genesys Cloud flows, analytics, and integrations.
You must define the structure of the attributes. Genesys Cloud supports nested JSON objects, but for simple key-value pairs like a CRM ID, a flat structure is often sufficient.
/**
* Starts a chat session with a specific CRM Customer ID.
*
* @param {string} crmCustomerId - The unique identifier from the external CRM system.
* @param {string} customerName - Optional: The name of the customer for context.
* @returns {Promise<void>}
*/
async function startChatWithCrmId(crmCustomerId, customerName) {
if (!crmCustomerId) {
throw new Error('CRM Customer ID is required to start the chat.');
}
// Define the attributes payload
// Note: Attribute keys should be camelCase to match Genesys Cloud conventions
const sessionAttributes = {
// Custom attribute for CRM ID
crmCustomerId: crmCustomerId,
// Optional: Additional context
customerName: customerName || 'Anonymous User',
// Optional: Source of the request (e.g., Web, Mobile, Portal)
sourceChannel: 'WebPortal'
};
try {
// Call startChat with the attributes
// The 'attributes' property is part of the session configuration
await webMessaging.startChat({
attributes: sessionAttributes
});
console.log('Chat started with CRM ID:', crmCustomerId);
} catch (error) {
console.error('Failed to start chat:', error);
throw error;
}
}
Explanation of Non-Obvious Parameters:
attributes: This is a JSON object. Keys must be strings. Values can be strings, numbers, booleans, or nested objects.- Key Naming: Use camelCase for attribute keys (e.g.,
crmCustomerId). Genesys Cloud flows and data actions reference these keys exactly as defined. If you useCRM_Customer_IDin the SDK, you must useCRM_Customer_IDin the flow. - Data Validation: The SDK does not validate the content of the attributes. It only validates the structure. Ensure
crmCustomerIdis a valid string or number before passing it.
Edge Cases:
- Large Attributes: If the
attributesobject exceeds the WebSocket message limit, thestartChatcall may fail. Keep attributes concise. - Reserved Keys: Avoid using keys that conflict with internal Genesys Cloud attributes (e.g.,
conversationId,participantId). Using reserved keys may cause unexpected behavior or be ignored by the platform.
Step 3: Verify Attribute Persistence in the Flow
Passing the attribute is only half the battle. You must ensure the attribute is available in the Genesys Cloud routing flow. This step demonstrates how to verify that the attribute is correctly received and can be used for routing or data actions.
While this step is not code executed in the browser, it is critical for the integration to work. In your Genesys Cloud Flow, add a Data Action to log or set a variable from the incoming attributes.
- Open your Flow in the Flow Builder.
- Add a Data Action block after the Start block.
- Set the Action Type to
Set. - Set the Variable to
crmId. - Set the Value to
{{attributes.crmCustomerId}}.
If the attribute is passed correctly, this variable will be populated. If it is null or undefined, the attribute was not passed or was blocked by deployment policies.
You can also verify this by checking the conversation transcript in the Admin console. Navigate to Messaging > Transcripts, find the conversation, and inspect the Metadata or Attributes section. The crmCustomerId should be listed there.
Complete Working Example
Below is a complete, copy-pasteable HTML file that demonstrates the integration. This example includes the SDK initialization, the function to start the chat with the CRM ID, and a simple UI to trigger the action.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Genesys Cloud Web Messaging with CRM ID</title>
<style>
body { font-family: Arial, sans-serif; padding: 20px; }
button { padding: 10px 20px; cursor: pointer; }
#status { margin-top: 20px; color: blue; }
#error { margin-top: 20px; color: red; }
</style>
</head>
<body>
<h1>Web Messaging CRM Integration</h1>
<div>
<label for="crmId">CRM Customer ID:</label>
<input type="text" id="crmId" placeholder="Enter CRM ID (e.g., CUST-12345)">
</div>
<div>
<button id="startChatBtn">Start Chat with CRM ID</button>
</div>
<div id="status"></div>
<div id="error"></div>
<!-- Load the Genesys Cloud Web Messaging SDK from CDN -->
<script src="https://cdn.genesiscloud.com/webrtc/v3/genesyscloud-webrtc.min.js"></script>
<script>
// Configuration
const ORG_ID = 'your-organization-id'; // Replace with your Org ID
const DEPLOYMENT_ID = 'your-deployment-id'; // Replace with your Deployment ID
// Initialize Web Messaging
const webMessaging = new GenesysCloudWebRTC.WebMessaging({
orgID: ORG_ID,
deploymentID: DEPLOYMENT_ID,
logLevel: 'debug'
});
// UI Elements
const startChatBtn = document.getElementById('startChatBtn');
const crmIdInput = document.getElementById('crmId');
const statusDiv = document.getElementById('status');
const errorDiv = document.getElementById('error');
// Session Status Handler
webMessaging.onSessionStatus((status) => {
statusDiv.textContent = `Session Status: ${status}`;
if (status === 'connected') {
startChatBtn.textContent = 'Chat Active';
startChatBtn.disabled = true;
} else if (status === 'error') {
errorDiv.textContent = 'An error occurred during chat initialization.';
startChatBtn.disabled = false;
}
});
// Start Chat Function
startChatBtn.addEventListener('click', async () => {
const crmCustomerId = crmIdInput.value.trim();
if (!crmCustomerId) {
errorDiv.textContent = 'Please enter a CRM Customer ID.';
return;
}
errorDiv.textContent = '';
statusDiv.textContent = 'Starting chat...';
startChatBtn.disabled = true;
try {
// Prepare attributes
const sessionAttributes = {
crmCustomerId: crmCustomerId,
timestamp: new Date().toISOString(),
userAgent: navigator.userAgent
};
// Start the chat session
await webMessaging.startChat({
attributes: sessionAttributes
});
statusDiv.textContent = 'Chat started successfully. CRM ID passed.';
// Note: The SDK may take a moment to connect fully.
// The onSessionStatus callback will update the UI when connected.
} catch (error) {
console.error('Chat start failed:', error);
errorDiv.textContent = `Failed to start chat: ${error.message}`;
startChatBtn.disabled = false;
}
});
</script>
</body>
</html>
Ready to Run:
Replace your-organization-id and your-deployment-id with your actual Genesys Cloud credentials. Open the HTML file in a browser. Enter a CRM ID and click “Start Chat”. Check the browser console for detailed logs and the Genesys Cloud Admin console for the conversation transcript to verify the attribute.
Common Errors & Debugging
Error: 403 Forbidden or Unauthorized
- Cause: The Deployment ID is incorrect, or the deployment is disabled.
- Fix: Verify the Deployment ID in the Genesys Cloud Admin console. Ensure the deployment is enabled and active.
- Code Fix: Check the
ORG_IDandDEPLOYMENT_IDconstants in your code.
Error: Attribute Not Found in Flow
- Cause: The attribute key name in the SDK does not match the key name in the Flow.
- Fix: Ensure exact case-sensitive matching. If you pass
crmCustomerIdin the SDK, you must reference{{attributes.crmCustomerId}}in the Flow. - Debugging: Add a Log block in your Flow to print the entire
attributesobject to the conversation log.
Error: WebSocket Connection Failed
- Cause: Network issues, firewall blocking WebSocket connections, or incorrect Org ID.
- Fix: Ensure your browser can connect to
wss://webmessaging.genesiscloud.com. Check browser console for CORS or network errors. - Code Fix: Verify the
ORG_IDis correct. Ensure the SDK version is compatible with your Genesys Cloud environment.
Error: 429 Too Many Requests
- Cause: Excessive chat initiation requests from the same client.
- Fix: Implement rate limiting on the client side. Do not call
startChatrepeatedly in quick succession. - Code Fix: Add a debounce mechanism to the start button.
let isStarting = false;
startChatBtn.addEventListener('click', async () => {
if (isStarting) return;
isStarting = true;
try {
// ... startChat logic ...
} finally {
isStarting = false;
}
});