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

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

What You Will Build

  • One sentence: You will configure the Genesys Cloud Web Messaging SDK to attach a custom CRM customer ID to the chat session metadata upon initialization.
  • One sentence: This tutorial uses the Genesys Cloud Web Messaging SDK (v2) and the startChat method.
  • One sentence: The programming language covered is JavaScript (ES6+).

Prerequisites

  • OAuth Client: A Genesys Cloud Web Messaging application client with valid configuration.
  • SDK Version: @genesyscloud/web-messaging-sdk version 2.x or later.
  • Runtime: Modern browser environment (Chrome, Firefox, Safari, Edge) supporting ES6 modules or bundled builds.
  • Dependencies:
    • @genesyscloud/web-messaging-sdk
    • @genesyscloud/web-messaging-sdk-ui (optional, for UI components)

Authentication Setup

The Web Messaging SDK does not use standard OAuth 2.0 client credentials flow directly in the browser. Instead, it uses a configuration object containing your Genesys Cloud orgId, region, and a deploymentId (or applicationId depending on your setup). The SDK handles token retrieval internally via the configured deployment.

You must ensure your Web Messaging deployment in the Genesys Cloud Admin UI is configured to allow custom data attributes.

  1. Navigate to Admin > Messaging > Web Messaging.
  2. Select your deployment.
  3. Ensure that Custom Data is enabled or that you have defined the specific custom attribute key (e.g., crmCustomerId) in the deployment settings if your org uses strict schema validation for custom data.

Implementation

Step 1: Initialize the Web Messaging SDK

First, import the SDK and initialize the client. The initialization requires the Genesys Cloud organization ID, the region, and the specific deployment ID for your Web Messaging instance.

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

// Configuration constants
const GC_ORG_ID = 'your-org-id-here';
const GC_REGION = 'us-east-1'; // e.g., us-east-1, eu-west-1, ap-southeast-2
const DEPLOYMENT_ID = 'your-deployment-id-here';

// Initialize the client
const webMessagingClient = new WebMessagingClient({
  orgId: GC_ORG_ID,
  region: GC_REGION,
  deploymentId: DEPLOYMENT_ID,
});

// Optional: Log SDK events for debugging
webMessagingClient.on('error', (error) => {
  console.error('Web Messaging SDK Error:', error);
});

webMessagingClient.on('connected', () => {
  console.log('Web Messaging SDK connected successfully.');
});

Expected Response: No HTTP response is returned at this stage. The SDK establishes a WebSocket connection to the Genesys Cloud messaging infrastructure.

Error Handling:

  • If orgId or deploymentId is invalid, the SDK will emit an error event with a 401 or 404 status.
  • Ensure your region matches your Genesys Cloud instance. Using us-east-1 for an eu-west-1 instance will result in connection timeouts.

Step 2: Configure Custom Data for the Chat Session

The core requirement is to pass the CRM Customer ID. In Genesys Cloud Web Messaging, this is achieved by including a customData object in the startChat options. This data is attached to the conversation and can be accessed by routing rules, flow scripts, and post-conversation analytics.

Critical Parameter: The customData object must be a flat key-value pair structure. Nested objects are not supported in the initial startChat payload for custom data in all SDK versions.

// Define the CRM Customer ID
const crmCustomerId = 'CRM-USER-123456789';

// Prepare the custom data payload
const customDataPayload = {
  crmCustomerId: crmCustomerId,
  // You can include other context as needed
  source: 'website',
  campaignId: 'summer-promo-2023'
};

Why this works: Genesys Cloud stores this data in the conversation’s customData attribute. When the conversation is routed to a flow, the flow can read customData.crmCustomerId to look up the user in your CRM via an API integration.

Step 3: Start the Chat with Custom Data

Now, invoke the startChat method with the customData option. This method initiates the connection to the Genesys Cloud messaging service and registers the session with the provided metadata.

async function initiateChatWithCrmId() {
  try {
    // Define the start options
    const startOptions = {
      customData: customDataPayload,
      // Optional: Pre-filled message
      message: 'Hello, I need help with my order.',
      // Optional: Customer profile data (distinct from customData)
      customer: {
        id: 'sdk-generated-id', // The SDK can generate this, or you provide it
        name: 'John Doe',
        email: 'john.doe@example.com'
      }
    };

    // Start the chat
    const chatSession = await webMessagingClient.startChat(startOptions);

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

    // Verify custom data was attached (if supported by your SDK version)
    if (chatSession.customData) {
      console.log('Attached Custom Data:', chatSession.customData);
    }

    return chatSession;

  } catch (error) {
    if (error.status === 429) {
      console.error('Rate limit exceeded. Please retry later.');
    } else if (error.status === 401) {
      console.error('Authentication failed. Check deployment ID and org ID.');
    } else {
      console.error('Failed to start chat:', error);
    }
    throw error;
  }
}

Expected Response:
The startChat method returns a ChatSession object. A realistic response structure (simplified) looks like this:

{
  "sessionId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  "conversationId": "98765432-1234-5678-90ab-cdef12345678",
  "customData": {
    "crmCustomerId": "CRM-USER-123456789",
    "source": "website",
    "campaignId": "summer-promo-2023"
  },
  "customer": {
    "id": "sdk-generated-id",
    "name": "John Doe",
    "email": "john.doe@example.com"
  },
  "status": "connected"
}

Error Handling:

  • 429 Too Many Requests: If you call startChat too frequently from the same IP or user agent, Genesys Cloud will rate-limit the request. Implement exponential backoff.
  • 400 Bad Request: If the customData payload exceeds size limits (typically 1KB for custom data attributes) or contains invalid characters, the request will fail.

Step 4: Verify Data in Genesys Cloud Flow

To confirm the data is passed correctly, you must verify it in the Genesys Cloud Flow Builder.

  1. Open the Flow associated with your Web Messaging deployment.
  2. Add a Set Variable action or an API Request action.
  3. Reference the custom data using the syntax: {{customData.crmCustomerId}}.
  4. If you use an API Request to push this data to your CRM, the body might look like:
{
  "customerId": "{{customData.crmCustomerId}}",
  "conversationId": "{{conversation.id}}"
}

Complete Working Example

Below is a complete, self-contained HTML file that demonstrates the integration. This example uses the CDN build of the SDK for ease of testing. In production, bundle this with Webpack or Vite.

<!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: sans-serif; padding: 20px; }
    button { padding: 10px 20px; cursor: pointer; }
    #status { margin-top: 10px; color: #555; }
    #log { margin-top: 20px; background: #f4f4f4; padding: 10px; border-radius: 4px; max-height: 300px; overflow-y: auto; }
    .log-entry { font-size: 0.9em; margin-bottom: 5px; border-bottom: 1px solid #ddd; padding-bottom: 2px; }
  </style>
</head>
<body>

  <h1>Web Messaging CRM Integration</h1>
  <p>Click the button below to start a chat with your CRM Customer ID attached.</p>
  
  <button id="startChatBtn">Start Chat with CRM ID</button>
  <div id="status"></div>
  <div id="log"></div>

  <!-- Load Genesys Cloud Web Messaging SDK from CDN -->
  <script src="https://files.pure.cloud/purecloud/webchat/v2/purecloud-webchat-sdk.js"></script>

  <script>
    // Configuration
    const CONFIG = {
      orgId: 'YOUR_ORG_ID',
      region: 'us-east-1',
      deploymentId: 'YOUR_DEPLOYMENT_ID'
    };

    // CRM Customer ID to pass
    const CRM_CUSTOMER_ID = 'CRM-USER-123456789';

    // Logger helper
    function log(message) {
      const logDiv = document.getElementById('log');
      const entry = document.createElement('div');
      entry.className = 'log-entry';
      entry.textContent = new Date().toLocaleTimeString() + ': ' + message;
      logDiv.appendChild(entry);
      logDiv.scrollTop = logDiv.scrollHeight;
    }

    // Initialize SDK
    let webMessagingClient;

    function initSDK() {
      try {
        // Access the global SDK object from the CDN script
        const SDK = window.PureCloudWebChatSDK;
        
        webMessagingClient = new SDK.WebMessagingClient({
          orgId: CONFIG.orgId,
          region: CONFIG.region,
          deploymentId: CONFIG.deploymentId
        });

        // Event Listeners
        webMessagingClient.on('connected', () => {
          log('SDK Connected to Genesys Cloud.');
          document.getElementById('status').textContent = 'SDK Connected. Ready to chat.';
        });

        webMessagingClient.on('error', (error) => {
          log('SDK Error: ' + (error.message || JSON.stringify(error)));
          document.getElementById('status').textContent = 'SDK Error occurred.';
        });

        webMessagingClient.on('message', (message) => {
          log('Received Message: ' + message.text);
        });

        log('SDK Initialized.');
      } catch (e) {
        log('Initialization Failed: ' + e.message);
        document.getElementById('status').textContent = 'Initialization Failed.';
      }
    }

    // Start Chat Function
    async function startChat() {
      if (!webMessagingClient) {
        alert('SDK not initialized. Check console.');
        return;
      }

      try {
        document.getElementById('status').textContent = 'Starting chat...';
        
        const customData = {
          crmCustomerId: CRM_CUSTOMER_ID,
          timestamp: new Date().toISOString()
        };

        const startOptions = {
          customData: customData,
          message: 'Hi, this is a test with CRM ID: ' + CRM_CUSTOMER_ID,
          customer: {
            name: 'Test User',
            email: 'test@example.com'
          }
        };

        const chatSession = await webMessagingClient.startChat(startOptions);

        log('Chat Started Successfully.');
        log('Session ID: ' + chatSession.sessionId);
        log('Conversation ID: ' + chatSession.conversationId);
        
        if (chatSession.customData) {
          log('Custom Data Attached: ' + JSON.stringify(chatSession.customData));
        }

        document.getElementById('status').textContent = 'Chat Active. Session: ' + chatSession.sessionId;

      } catch (error) {
        log('Start Chat Failed: ' + (error.message || JSON.stringify(error)));
        document.getElementById('status').textContent = 'Start Chat Failed.';
      }
    }

    // Bind Events
    document.getElementById('startChatBtn').addEventListener('click', startChat);

    // Init on load
    window.addEventListener('load', initSDK);
  </script>

</body>
</html>

Common Errors & Debugging

Error: 401 Unauthorized

  • What causes it: The deploymentId or orgId is incorrect, or the deployment is disabled in the Genesys Cloud Admin UI.
  • How to fix it: Verify the IDs in the Genesys Cloud Admin UI under Admin > Messaging > Web Messaging. Ensure the deployment status is “Active”.
  • Code showing the fix:
    // Double check these values against your Admin UI
    const CONFIG = {
      orgId: 'correct-org-id',
      deploymentId: 'correct-deployment-id'
    };
    

Error: Custom Data Not Visible in Flow

  • What causes it: The custom data key name contains special characters, or the deployment does not allow custom data.
  • How to fix it: Use alphanumeric keys only (e.g., crmCustomerId instead of crm-customer-id). Check the deployment settings to ensure custom data is enabled.
  • Code showing the fix:
    // Use camelCase or snake_case, avoid hyphens
    const customData = {
      crmCustomerId: '12345' // Valid
      // 'crm-customer-id': '12345' // Potentially invalid depending on strict schema
    };
    

Error: 429 Too Many Requests

  • What causes it: Rapidly calling startChat or sending messages exceeds the rate limit.
  • How to fix it: Implement a retry mechanism with exponential backoff.
  • Code showing the fix:
    async function startChatWithRetry(startOptions, retries = 3) {
      for (let i = 0; i < retries; i++) {
        try {
          return await webMessagingClient.startChat(startOptions);
        } catch (error) {
          if (error.status === 429 && i < retries - 1) {
            const delay = Math.pow(2, i) * 1000; // Exponential backoff
            console.log(`Rate limited. Retrying in ${delay}ms...`);
            await new Promise(resolve => setTimeout(resolve, delay));
          } else {
            throw error;
          }
        }
      }
    }
    

Official References