How to Pass CRM Customer ID Through the Web Messaging SDK startChat() Method

How to Pass CRM Customer ID Through the Web Messaging SDK startChat() Method

What You Will Build

  • You will build a web interface that initiates a Genesys Cloud Pure Engage chat session while injecting a specific CRM Customer ID into the session metadata.
  • You will use the Genesys Cloud Web Messaging SDK (genesyscloud-webmessaging-web-sdk) and the startChat method with a custom attributes object.
  • You will implement this in JavaScript (ES6+) for a standard HTML5 web page.

Prerequisites

  • OAuth Client Type: A Public Client (Confidential clients are for server-to-server; web SDKs typically use public clients with PKCE or direct token exchange if using an embedded flow, but for simple Web Messaging, you primarily need the Deployment ID and Site Name. Authentication is handled by the widget if configured for user auth, or anonymously if configured for public access).
  • Required Scopes: If the chat requires user authentication via the widget, you need webmessaging:read and webmessaging:write. For anonymous chats with custom attributes, no explicit OAuth scope is required on the client side, but the Deployment must be configured to allow custom attributes.
  • SDK Version: Genesys Cloud Web Messaging SDK v2.x or later.
  • Runtime: Any modern web browser supporting ES6 modules or a bundler (Webpack/Vite).
  • Dependencies:
    • @genesyscloud/web-messaging-web-sdk (npm) or via CDN.

Authentication Setup

The Web Messaging SDK handles authentication internally if you have configured your Deployment to require user authentication. If your Deployment is set to “Public” (anonymous), no OAuth tokens are needed from your code.

For this tutorial, we assume a standard Public Deployment where the user is identified by the CRM ID you pass in. This is the most common pattern for passing external identifiers. If you are using a logged-in user flow, the SDK requires a valid access_token in the init options.

Below is the setup for a Public Deployment (Anonymous) which is the standard use case for passing a CRM ID without complex token management.

// No OAuth token required for Public Deployments.
// If using Authenticated Deployments, you must obtain a token via the Genesys Cloud OAuth API
// and pass it to the init method: { token: 'YOUR_ACCESS_TOKEN' }

Implementation

Step 1: Initialize the Web Messaging SDK

You must initialize the SDK before calling startChat. The initialization requires your deploymentId and siteName. These values are found in the Genesys Cloud Admin Console under Engagement > Chat > Deployments.

OAuth Scopes: None (handled by widget configuration).

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

const DEPLOYMENT_ID = 'your-deployment-id-here';
const SITE_NAME = 'your-site-name-here';

// Initialize the SDK
const sdk = new WebMessagingSDK({
  deploymentId: DEPLOYMENT_ID,
  siteName: SITE_NAME,
  // Optional: Configure locale, theme, or authentication token here
});

// Wait for the SDK to be ready
sdk.ready().then(() => {
  console.log('Web Messaging SDK is ready.');
});

Expected Response:
The ready() promise resolves when the SDK has loaded its configuration from the Genesys Cloud servers. If the deployment ID is invalid, the promise will reject with an error.

Error Handling:

sdk.ready().catch((error) => {
  console.error('Failed to initialize SDK:', error);
  // Common errors: 404 (Invalid Deployment ID), 401 (Invalid Token if auth required)
});

Step 2: Construct the startChat Payload with CRM ID

The core of this tutorial is passing the CRM Customer ID. You do this by including an attributes object in the startChat method call. The Genesys Cloud platform maps these attributes to the conversation metadata.

Critical Parameter: attributes
This object allows you to pass key-value pairs. The key should be descriptive (e.g., crmCustomerId), and the value is the actual ID from your CRM.

OAuth Scopes: None (Public) or webmessaging:write (Authenticated).

const CRM_CUSTOMER_ID = 'CRM-12345-XYZ'; // Retrieve this from your CRM context

const startChatPayload = {
  // Optional: Pre-chat form answers if your deployment requires them
  // preChatFormAnswers: { name: 'John Doe', email: 'john@example.com' },

  // The critical part: Custom Attributes
  attributes: {
    // The key 'crmCustomerId' is arbitrary but must be consistent
    // with your routing rules or analytics filters.
    crmCustomerId: CRM_CUSTOMER_ID,
    
    // You can pass additional context
    source: 'web-portal',
    userId: 'internal-user-id-99'
  }
};

Non-Obvious Parameters:

  • attributes vs preChatFormAnswers: Do not put the CRM ID in preChatFormAnswers unless you have a specific pre-chat field named exactly that. attributes are hidden metadata that do not appear in the pre-chat form UI but are available to routing rules, analytics, and the agent desktop.
  • Key Naming: Use camelCase or snake_case consistently. Genesys Cloud is case-sensitive for attribute keys. If you use crmCustomerId in one call and crmCustomerid in another, they are treated as different attributes.

Step 3: Execute startChat and Handle the Session

Call the startChat method with the payload. This returns a promise that resolves with a ChatSession object. You must handle the session lifecycle to ensure the chat remains active and to listen for events.

async function initiateChatWithCRMId() {
  try {
    // Ensure SDK is ready
    await sdk.ready();

    // Start the chat with the CRM ID in attributes
    const chatSession = await sdk.startChat(startChatPayload);

    console.log('Chat started successfully.');
    console.log('Conversation ID:', chatSession.conversationId);
    console.log('Session ID:', chatSession.sessionId);

    // Optional: Listen for messages from the agent
    chatSession.on('messageReceived', (message) => {
      console.log('Agent said:', message.text);
      // Render message in your UI
    });

    return chatSession;

  } catch (error) {
    console.error('Failed to start chat:', error);
    
    // Specific error handling for common SDK errors
    if (error.code === '429') {
      console.error('Rate limited. Wait before retrying.');
    } else if (error.code === '400') {
      console.error('Bad Request. Check pre-chat form answers or attribute limits.');
    } else if (error.code === '403') {
      console.error('Forbidden. Deployment may be inactive or requires auth.');
    }
  }
}

Expected Response:
The startChat method resolves with a ChatSession object containing:

  • conversationId: The unique ID for the conversation in Genesys Cloud.
  • sessionId: The unique ID for this specific client session.
  • status: The current status (e.g., ‘connected’, ‘waiting’).

Error Handling:

  • 400 Bad Request: Often caused by missing required pre-chat fields if your deployment enforces them. Ensure your startChatPayload includes all required fields if configured.
  • 403 Forbidden: The deployment is inactive, or the site name is incorrect.
  • 429 Too Many Requests: You have exceeded the rate limit for starting chats. Implement exponential backoff if retrying.

Step 4: Verify Attribute Propagation in Genesys Cloud

To confirm the CRM ID is passed correctly, you can use the Genesys Cloud Analytics API to query the conversation details. This step is for verification and debugging.

Endpoint: GET /api/v2/analytics/conversations/details/query
OAuth Scopes: analytics:read

// This is a separate server-side or secure client-side call using the Genesys Cloud REST API
// You need an access token with analytics:read scope

async function verifyCRMAttribute(conversationId, accessToken) {
  const url = `https://api.mypurecloud.com/api/v2/analytics/conversations/details/query`;
  
  const body = {
    "interval": "PT1H", // Last 1 hour
    "groupBy": ["conversationId"],
    "filter": [
      {
        "type": "conversation",
        "name": "conversationId",
        "value": [conversationId]
      }
    ],
    "metrics": ["conversation.customerId"] // Note: customerId is internal Genesys ID, not CRM ID
  };

  // Note: Custom attributes are not directly in the standard analytics metrics.
  // You must use the Conversation API to see custom attributes.
  
  const convUrl = `https://api.mypurecloud.com/api/v2/conversations/chats/${conversationId}`;
  
  const response = await fetch(convUrl, {
    method: 'GET',
    headers: {
      'Authorization': `Bearer ${accessToken}`,
      'Content-Type': 'application/json'
    }
  });

  if (!response.ok) {
    throw new Error(`API Error: ${response.status}`);
  }

  const data = await response.json();
  
  // The custom attributes are stored in the 'attributes' field of the participant or the conversation
  // Depending on how the SDK sent it, it may be in the participant's attributes.
  console.log('Conversation Details:', data);
  
  // Check for the CRM ID in the participant attributes
  if (data.participants && data.participants.length > 0) {
    const customerParticipant = data.participants.find(p => p.type === 'customer');
    if (customerParticipant && customerParticipant.attributes) {
      console.log('CRM Customer ID found:', customerParticipant.attributes.crmCustomerId);
    }
  }
}

Complete Working Example

This is a complete, self-contained HTML file with embedded JavaScript. It assumes you have installed the SDK via CDN for simplicity. Replace DEPLOYMENT_ID and SITE_NAME with your actual values.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Genesys Web Chat with CRM ID</title>
    <style>
        body { font-family: sans-serif; padding: 20px; }
        button { padding: 10px 20px; cursor: pointer; }
        #chat-container { margin-top: 20px; border: 1px solid #ccc; padding: 10px; height: 300px; overflow-y: auto; }
        .message { margin: 5px 0; padding: 5px; background: #f0f0f0; }
        .agent { background: #d1e7dd; }
        .system { font-style: italic; color: #666; }
    </style>
</head>
<body>

    <h1>Start Chat with CRM ID</h1>
    <input type="text" id="crm-id" placeholder="Enter CRM Customer ID" value="CRM-12345">
    <button id="start-chat-btn">Start Chat</button>
    <div id="chat-container"></div>

    <!-- Load SDK from CDN -->
    <script src="https://unpkg.com/@genesyscloud/web-messaging-web-sdk/dist/index.umd.js"></script>

    <script>
        // Configuration
        const DEPLOYMENT_ID = 'your-deployment-id-here';
        const SITE_NAME = 'your-site-name-here';

        // Initialize SDK
        const { WebMessagingSDK } = window.GenesysCloudWebMessaging;
        const sdk = new WebMessagingSDK({
            deploymentId: DEPLOYMENT_ID,
            siteName: SITE_NAME
        });

        const chatContainer = document.getElementById('chat-container');
        const startBtn = document.getElementById('start-chat-btn');
        const crmIdInput = document.getElementById('crm-id');

        let currentSession = null;

        startBtn.addEventListener('click', async () => {
            const crmCustomerId = crmIdInput.value.trim();
            
            if (!crmCustomerId) {
                alert('Please enter a CRM Customer ID');
                return;
            }

            try {
                addSystemMessage('Initializing SDK...');
                await sdk.ready();
                addSystemMessage('SDK Ready. Starting chat...');

                // Define the payload with CRM ID
                const payload = {
                    attributes: {
                        crmCustomerId: crmCustomerId,
                        source: 'web-page'
                    }
                };

                // Start the chat
                currentSession = await sdk.startChat(payload);
                addSystemMessage(`Chat started. Conversation ID: ${currentSession.conversationId}`);

                // Listen for incoming messages
                currentSession.on('messageReceived', (message) => {
                    addMessage(message.text, 'agent');
                });

                // Listen for status changes
                currentSession.on('statusChanged', (status) => {
                    addSystemMessage(`Status changed to: ${status}`);
                });

            } catch (error) {
                console.error('Error:', error);
                addSystemMessage(`Error: ${error.message || error}`);
            }
        });

        function addMessage(text, type) {
            const div = document.createElement('div');
            div.className = `message ${type}`;
            div.textContent = text;
            chatContainer.appendChild(div);
            chatContainer.scrollTop = chatContainer.scrollHeight;
        }

        function addSystemMessage(text) {
            const div = document.createElement('div');
            div.className = 'message system';
            div.textContent = text;
            chatContainer.appendChild(div);
            chatContainer.scrollTop = chatContainer.scrollHeight;
        }
    </script>
</body>
</html>

Common Errors & Debugging

Error: 400 Bad Request - “Pre-chat form answers are required”

  • What causes it: Your Deployment is configured to require pre-chat form fields (e.g., Name, Email), but you did not include them in the startChat payload.
  • How to fix it: Add the required fields to the preChatFormAnswers object in your payload.
  • Code Fix:
    const payload = {
      preChatFormAnswers: {
        name: 'John Doe',
        email: 'john@example.com'
      },
      attributes: {
        crmCustomerId: 'CRM-12345'
      }
    };
    

Error: 403 Forbidden - “Deployment not found” or “Site name mismatch”

  • What causes it: The deploymentId or siteName is incorrect, or the Deployment is inactive.
  • How to fix it: Verify the values in the Genesys Cloud Admin Console. Ensure the Deployment status is “Active”.

Error: Attributes not visible in Analytics

  • What causes it: Custom attributes are not automatically included in standard analytics reports. You must create a custom attribute in Genesys Cloud Analytics and map it to the attributes.crmCustomerId field.
  • How to fix it: Go to Analytics > Custom Attributes and create a new attribute for Chats. Map the source to the attributes object from the conversation.

Error: SDK not defined

  • What causes it: The SDK script failed to load.
  • How to fix it: Check the browser console for network errors. Ensure the CDN URL is correct and accessible from your domain.

Official References