Pass CRM Customer ID via Genesys Cloud Web Messaging SDK

Pass CRM Customer ID via Genesys Cloud Web Messaging SDK

What You Will Build

  • You will configure the Genesys Cloud Web Messaging SDK to attach a specific CRM customer identifier to every outgoing chat message and to the initial session start event.
  • You will use the startChat() method with the attributes payload to inject custom data that Genesys Cloud stores as custom_attributes.
  • You will verify that these attributes persist in the conversation logs and are accessible via the Analytics API.

Prerequisites

  • OAuth Client: A Genesys Cloud OAuth client with view:interaction and view:conversation scopes (for verification).
  • SDK Version: Genesys Cloud Web Messaging SDK @genesyscloud/web-messaging-sdk version 2.0.0 or later.
  • Runtime: A modern web browser environment (Chrome, Firefox, Edge) with Node.js for local development if using a bundler.
  • Dependencies:
    • @genesyscloud/web-messaging-sdk: The core SDK library.
    • react or vue: Optional, but recommended for managing state in a real application. This tutorial uses vanilla JavaScript for maximum compatibility.

Authentication Setup

The Web Messaging SDK does not use standard OAuth 2.0 client credentials flow for the end-user chat session. Instead, it relies on a Site ID and Organization ID provided by your Genesys Cloud instance configuration. The SDK handles the handshake with the Genesys Cloud Edge services.

You must obtain the following from your Genesys Cloud Admin Console under Integrations > Messaging > Web Messaging:

  1. Site ID: A unique identifier for your web messaging configuration.
  2. Organization ID: Your Genesys Cloud Organization ID.

Note: Do not expose API keys or OAuth secrets in the frontend code. The Web Messaging SDK is designed to run in the browser without server-side authentication tokens for the chat session itself. The security boundary is established via the Site ID configuration in the Genesys Cloud backend.

Implementation

Step 1: Initialize the Web Messaging SDK

First, you must install the SDK package and initialize the client. The initialization process connects the browser to the Genesys Cloud messaging edge.

Install the SDK:

npm install @genesyscloud/web-messaging-sdk

Initialize the Client:

import { WebMessagingClient } from '@genesyscloud/web-messaging-sdk';

// Configuration constants
const SITE_ID = 'YOUR_SITE_ID'; // Replace with your actual Site ID
const ORG_ID = 'YOUR_ORG_ID';   // Replace with your actual Organization ID

// Initialize the client
const webMessagingClient = new WebMessagingClient({
  siteId: SITE_ID,
  orgId: ORG_ID,
});

// Optional: Configure logging for debugging
webMessagingClient.setLogLevel('debug');

The WebMessagingClient establishes a WebSocket connection to the Genesys Cloud messaging infrastructure. It does not immediately start a conversation. It prepares the client to accept commands to start, send, and receive messages.

Step 2: Define the CRM Customer ID Attribute

Genesys Cloud Web Messaging supports custom attributes that are attached to the conversation context. These attributes are stored in the custom_attributes field of the conversation object. You must define the key-value pair for your CRM ID.

Critical Constraint: The key name must be unique within your organization’s attribute schema. If you have already defined a schema for crm_customer_id, use that exact string. If not, Genesys Cloud will accept it dynamically, but it is best practice to define it in the Messaging > Web Messaging > Attributes section of the Admin Console to ensure type consistency (e.g., string).

// Define the CRM ID payload
const CRM_CUSTOMER_ID_KEY = 'crm_customer_id';
const CRM_CUSTOMER_ID_VALUE = 'CUST-987654321'; // Example CRM ID

// Construct the attributes object
const conversationAttributes = {
  [CRM_CUSTOMER_ID_KEY]: CRM_CUSTOMER_ID_VALUE,
};

Step 3: Start the Chat with Attributes

The core requirement is to pass these attributes during the startChat() call. The startChat() method accepts a configuration object. Within this object, you specify the attributes field.

Working Code:

async function initiateChatWithCRMId() {
  try {
    // Start the chat session with custom attributes
    const chatSession = await webMessagingClient.startChat({
      // Optional: Specify a specific queue or skill if needed
      // queueId: 'YOUR_QUEUE_ID',
      
      // Pass the custom attributes
      attributes: conversationAttributes,
    });

    console.log('Chat started successfully. Session ID:', chatSession.sessionId);
    console.log('Attributes attached:', chatSession.attributes);
    
    return chatSession;
  } catch (error) {
    console.error('Failed to start chat:', error);
    throw error;
  }
}

Why this works:
When you call startChat() with the attributes parameter, the SDK sends a JSON payload to the Genesys Cloud Edge service. The Edge service validates the attribute keys against your organization’s schema. If valid, it attaches them to the newly created Conversation resource. These attributes persist for the lifetime of the conversation and are included in all subsequent message events.

Step 4: Verify Attribute Persistence

To confirm that the CRM ID was successfully passed, you can listen for the onMessage event or check the conversation context. However, the most robust verification is to inspect the conversation data via the Genesys Cloud API.

Listen for Messages:

// Subscribe to incoming messages
webMessagingClient.onMessage((message) => {
  console.log('Received message:', message);
  // The message object will contain the conversation ID
  // You can use this ID to fetch full conversation details via API
});

// Subscribe to conversation updates
webMessagingClient.onConversationUpdate((update) => {
  console.log('Conversation updated:', update);
  // Check if attributes are present in the update payload
  if (update.attributes) {
    console.log('CRM ID in conversation:', update.attributes[CRM_CUSTOMER_ID_KEY]);
  }
});

Complete Working Example

This example provides a complete, runnable module that initializes the SDK, starts a chat with a CRM ID, and handles basic error states.

import { WebMessagingClient } from '@genesyscloud/web-messaging-sdk';

/**
 * Configuration constants.
 * Replace these with your actual Genesys Cloud credentials.
 */
const CONFIG = {
  siteId: 'YOUR_SITE_ID',
  orgId: 'YOUR_ORG_ID',
  crmCustomerId: 'CUST-123456789',
};

class GenesysChatManager {
  constructor() {
    this.client = null;
    this.isInitialized = false;
  }

  /**
   * Initializes the Web Messaging SDK client.
   */
  async initialize() {
    if (this.isInitialized) {
      return;
    }

    try {
      this.client = new WebMessagingClient({
        siteId: CONFIG.siteId,
        orgId: CONFIG.orgId,
      });

      // Set up event listeners for debugging
      this.client.onMessage((message) => {
        console.log('[GenesysChat] Message received:', message);
      });

      this.client.onError((error) => {
        console.error('[GenesysChat] SDK Error:', error);
      });

      this.isInitialized = true;
      console.log('[GenesysChat] Client initialized successfully.');
    } catch (error) {
      console.error('[GenesysChat] Initialization failed:', error);
      throw error;
    }
  }

  /**
   * Starts a new chat session with the CRM Customer ID attached.
   * @param {string} [overrideCrmId] - Optional override for the CRM ID.
   * @returns {Promise<Object>} The chat session object.
   */
  async startChat(overrideCrmId = null) {
    if (!this.isInitialized) {
      await this.initialize();
    }

    const crmId = overrideCrmId || CONFIG.crmCustomerId;

    // Define the custom attributes payload
    const attributes = {
      crm_customer_id: crmId,
      // You can add more attributes here, e.g., customer tier, location, etc.
      source: 'web-sdk-tutorial',
    };

    try {
      // Call startChat with the attributes
      const session = await this.client.startChat({
        attributes: attributes,
      });

      console.log('[GenesysChat] Chat started. Session ID:', session.sessionId);
      console.log('[GenesysChat] Attached CRM ID:', attributes.crm_customer_id);
      
      return session;
    } catch (error) {
      if (error.code === 'ALREADY_IN_CHAT') {
        console.warn('[GenesysChat] User is already in an active chat session.');
        return null;
      }
      throw error;
    }
  }

  /**
   * Sends a message to the active chat session.
   * @param {string} text - The message text.
   */
  async sendMessage(text) {
    if (!this.isInitialized) {
      throw new Error('Client not initialized.');
    }

    try {
      await this.client.sendTextMessage(text);
      console.log('[GenesysChat] Message sent:', text);
    } catch (error) {
      console.error('[GenesysChat] Failed to send message:', error);
      throw error;
    }
  }

  /**
   * Ends the current chat session.
   */
  async endChat() {
    if (!this.isInitialized) {
      throw new Error('Client not initialized.');
    }

    try {
      await this.client.endChat();
      console.log('[GenesysChat] Chat ended.');
    } catch (error) {
      console.error('[GenesysChat] Failed to end chat:', error);
      throw error;
    }
  }
}

// Export for use in other modules
export default GenesysChatManager;

Usage Example:

import GenesysChatManager from './GenesysChatManager';

const chatManager = new GenesysChatManager();

async function runDemo() {
  try {
    // Initialize the SDK
    await chatManager.initialize();

    // Start chat with CRM ID
    const session = await chatManager.startChat();

    if (session) {
      // Send a test message
      await chatManager.sendMessage('Hello, this is a test message with CRM ID attached.');
      
      // Wait a few seconds for response (optional)
      await new Promise(resolve => setTimeout(resolve, 5000));
      
      // End chat
      await chatManager.endChat();
    }
  } catch (error) {
    console.error('Demo failed:', error);
  }
}

runDemo();

Common Errors & Debugging

Error: 400 Bad Request on startChat()

  • Cause: The attributes object contains keys that are not defined in your Genesys Cloud Messaging Schema, or the value types do not match the schema definition (e.g., sending a number where a string is expected).
  • Fix: Verify the attribute key crm_customer_id exists in Admin Console > Messaging > Web Messaging > Attributes. Ensure the type is String. If the key does not exist, create it before running the code.
  • Code Check:
    // Ensure the value is a string
    const attributes = {
      crm_customer_id: String(CONFIG.crmCustomerId), // Explicit conversion
    };
    

Error: 401 Unauthorized or 403 Forbidden

  • Cause: The siteId or orgId is incorrect, or the Web Messaging integration is not enabled for your organization.
  • Fix: Double-check the siteId and orgId from the Admin Console. Ensure that the Web Messaging channel is active and not paused.
  • Debugging: Enable SDK logging to see the raw HTTP response.
    webMessagingClient.setLogLevel('debug');
    

Error: Attributes Not Visible in Analytics

  • Cause: The attributes were passed correctly, but they are not selected in the Analytics report.
  • Fix: In Genesys Cloud Analytics, when building a report for Conversations or Messages, you must explicitly select the custom_attributes.crm_customer_id field as a dimension or metric. Custom attributes are not included in the default view.
  • Verification: Use the API to fetch the conversation directly.
    curl -X GET "https://api.us.genesyscloud.com/api/v2/conversations/{conversationId}" \
      -H "Authorization: Bearer YOUR_ACCESS_TOKEN"
    
    Inspect the custom_attributes field in the JSON response.

Error: TypeError: webMessagingClient.startChat is not a function

  • Cause: You are using an outdated version of the SDK or have imported the wrong module.
  • Fix: Ensure you are importing WebMessagingClient from @genesyscloud/web-messaging-sdk. Check your package.json to confirm the version is 2.0.0 or higher.
    npm list @genesyscloud/web-messaging-sdk
    

Official References