Passing CRM Customer ID via Genesys Cloud Web Messaging SDK startChat()

Passing CRM Customer ID via Genesys Cloud Web Messaging SDK startChat()

What You Will Build

  • You will configure the Genesys Cloud Web Messaging SDK to inject a unique CRM customer identifier into the startChat() method payload.
  • This tutorial uses the Genesys Cloud Web Messaging SDK (v2) and the Genesys Cloud REST API for verification.
  • The implementation is demonstrated in JavaScript (Browser/Node.js) for the SDK client and Python for API validation.

Prerequisites

  • Genesys Cloud Organization: A Genesys Cloud account with Web Messaging enabled.
  • Web Messaging Configuration: A Web Messaging channel configured in the Genesys Cloud Admin console with a valid Deployment ID.
  • OAuth 2.0 Credentials: Client ID and Client Secret for a service account or user credentials for an integration account to verify data via API.
  • Required Scopes:
    • For API verification: view:webchat and view:conversation.
  • Runtime:
    • Node.js v18+ or a modern browser environment supporting ES6 modules.
    • Python 3.9+ with requests library for the verification script.
  • Dependencies:
    • No external npm packages are required for the SDK client; it is loaded via CDN or local bundle.
    • pip install requests for the Python verification script.

Authentication Setup

The Web Messaging SDK itself does not require OAuth tokens for the client-side startChat() execution because it relies on the Deployment ID for authentication. However, to verify that the CRM ID was successfully passed and stored, you must authenticate against the Genesys Cloud REST API.

The following Python script demonstrates how to obtain an OAuth token using a Service Account. This token will be used in the “Complete Working Example” section to query the conversation history.

import requests
import json
import os

def get_genesys_oauth_token():
    """
    Authenticates with Genesys Cloud using Service Account credentials.
    Returns the access token and expiration time.
    """
    # Load credentials from environment variables
    client_id = os.getenv("GENESYS_CLIENT_ID")
    client_secret = os.getenv("GENESYS_CLIENT_SECRET")
    environment = os.getenv("GENESYS_ENVIRONMENT", "mypurecloud.com")

    if not client_id or not client_secret:
        raise ValueError("GENESYS_CLIENT_ID and GENESYS_CLIENT_SECRET must be set.")

    url = f"https://api.{environment}/v2/oauth/token"
    headers = {
        "Content-Type": "application/x-www-form-urlencoded"
    }
    data = {
        "grant_type": "client_credentials",
        "client_id": client_id,
        "client_secret": client_secret
    }

    response = requests.post(url, headers=headers, data=data)

    if response.status_code != 200:
        print(f"Authentication failed: {response.status_code}")
        print(response.text)
        return None

    token_data = response.json()
    return token_data["access_token"]

if __name__ == "__main__":
    token = get_genesys_oauth_token()
    if token:
        print(f"Token acquired successfully. Expiry: {token_data['expires_in']} seconds")

Note: Store GENESYS_CLIENT_ID and GENESYS_CLIENT_SECRET in your environment. Never hardcode these values.

Implementation

Step 1: Initialize the Web Messaging SDK

Before passing custom data, you must initialize the Web Messaging SDK with your Deployment ID. The Deployment ID is found in the Genesys Cloud Admin Console under Engagement > Web Messaging > Deployments.

Create a file named webmessaging.html (or use a React/Vue component) to host the SDK.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Genesys Web Messaging CRM ID Pass</title>
    <!-- Load the Genesys Cloud Web Messaging SDK -->
    <script src="https://web-messaging-sdk.pure.cloud/sdk/2.0/genesys-cloud-web-messaging-sdk.min.js"></script>
</head>
<body>
    <div id="genesys-webmessaging-container"></div>

    <script>
        // Configuration
        const CONFIG = {
            deploymentId: "YOUR_DEPLOYMENT_ID_HERE", // Replace with your actual Deployment ID
            environment: "mypurecloud.com", // Or your specific environment (e.g., usw2.pure.cloud)
            locale: "en-us"
        };

        // Initialize the SDK
        async function initializeWebMessaging() {
            try {
                // Check if the SDK is loaded
                if (typeof window.GenesysCloudWebMessaging === 'undefined') {
                    throw new Error("Web Messaging SDK failed to load.");
                }

                const sdk = window.GenesysCloudWebMessaging;

                // Initialize the client
                await sdk.initialize({
                    deploymentId: CONFIG.deploymentId,
                    environment: CONFIG.environment,
                    locale: CONFIG.locale
                });

                console.log("Web Messaging SDK initialized successfully.");
                return sdk;

            } catch (error) {
                console.error("Failed to initialize Web Messaging SDK:", error);
                throw error;
            }
        }

        // Start the initialization process
        initializeWebMessaging().then((sdk) => {
            // SDK is ready. We will attach event listeners and start chat in subsequent steps.
            window.genesysSdk = sdk;
        });
    </script>
</body>
</html>

Key Parameters:

  • deploymentId: The unique identifier for your Web Messaging deployment. This is required for all SDK calls.
  • environment: The Genesys Cloud environment domain. Defaults to mypurecloud.com for most customers.
  • locale: Sets the default language for the chat interface.

Step 2: Configure Custom Attributes for CRM ID

The startChat() method accepts a customAttributes object. This object allows you to pass key-value pairs that are attached to the conversation. These attributes are visible in the Genesys Cloud Admin Console, in conversation transcripts, and can be used for routing or scripting.

To pass a CRM Customer ID, you must define the attribute key in the customAttributes object. It is best practice to use a clear, camelCase key name, such as crmCustomerId.

Important: The Web Messaging SDK does not validate the structure of customAttributes on the client side. However, Genesys Cloud imposes limits on the size and number of custom attributes. Ensure your CRM ID is a string or number and does not exceed reasonable length limits (e.g., 255 characters).

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

// Prepare the startChat configuration
const startChatConfig = {
    // Optional: Pre-fill the first message
    message: "Hello, I need help with my order.",

    // Optional: Set the customer's name
    firstName: "John",
    lastName: "Doe",
    email: "john.doe@example.com",

    // Pass the CRM ID via customAttributes
    customAttributes: {
        crmCustomerId: crmCustomerId,
        sourceSystem: "Website",
        segment: "Premium"
    }
};

Edge Cases:

  • Null or Undefined IDs: If the CRM ID is not available, do not pass an empty string. Instead, omit the attribute or pass null if your backend logic handles it gracefully. Passing empty strings can clutter your data model.
  • Sensitive Data: Do not pass PII (Personally Identifiable Information) like credit card numbers or SSNs in customAttributes unless you have explicitly configured Web Messaging to handle sensitive data and comply with GDPR/CCPA. CRM IDs are generally safe if they are opaque identifiers.

Step 3: Execute startChat() and Handle Response

Use the startChat() method from the initialized SDK instance. This method returns a Promise that resolves when the chat session is established.

async function startChatWithCrmId(sdk, config) {
    try {
        // Call the startChat method with the configuration
        const chatSession = await sdk.startChat(config);

        console.log("Chat started successfully.");
        console.log("Chat Session ID:", chatSession.id);
        console.log("Custom Attributes Sent:", config.customAttributes);

        // Optional: Listen for chat events
        sdk.on("chat:message:received", (event) => {
            console.log("Received message:", event.message);
        });

        return chatSession;

    } catch (error) {
        // Handle specific errors
        if (error.code === "CHAT_START_FAILED") {
            console.error("Failed to start chat:", error.message);
            // Implement retry logic or fallback UI
        } else if (error.code === "INVALID_DEPLOYMENT_ID") {
            console.error("Invalid Deployment ID. Check configuration.");
        } else {
            console.error("Unexpected error during chat start:", error);
        }
        throw error;
    }
}

// Usage example (assuming sdk is initialized in Step 1)
// startChatWithCrmId(window.genesysSdk, startChatConfig);

Expected Response:
The startChat() method returns a ChatSession object containing:

  • id: The unique identifier for the chat session.
  • status: The current status of the chat (e.g., “connected”, “queued”).
  • customAttributes: Echoes back the attributes passed (if supported by the SDK version).

Error Handling:

  • 401 Unauthorized: Usually indicates an invalid Deployment ID or expired session.
  • 429 Too Many Requests: Genesys Cloud enforces rate limits. Implement exponential backoff if you are programmatically starting multiple chats.
  • 5xx Server Error: Transient server issues. Retry after a short delay.

Step 4: Verify Data Propagation via REST API

To confirm that the crmCustomerId was successfully passed and stored, you can query the Genesys Cloud Conversation API. This step requires the OAuth token obtained in the Authentication Setup.

The following Python script queries the conversation details for the chat session ID returned by startChat().

import requests
import json
import os

def verify_crm_id_in_conversation(access_token, environment, conversation_id):
    """
    Verifies that the CRM Customer ID is present in the conversation's custom attributes.
    """
    url = f"https://api.{environment}/v2/conversations/details/query"
    headers = {
        "Authorization": f"Bearer {access_token}",
        "Content-Type": "application/json"
    }

    # Query for the specific conversation
    body = {
        "pageSize": 1,
        "filter": {
            "type": "webchat",
            "id": conversation_id
        }
    }

    response = requests.post(url, headers=headers, json=body)

    if response.status_code != 200:
        print(f"API request failed: {response.status_code}")
        print(response.text)
        return

    data = response.json()

    if "entities" not in data or len(data["entities"]) == 0:
        print("No conversations found with the given ID.")
        return

    conversation = data["entities"][0]

    # Extract custom attributes
    custom_attributes = conversation.get("customAttributes", {})
    crm_id = custom_attributes.get("crmCustomerId")

    if crm_id:
        print(f"SUCCESS: CRM Customer ID found: {crm_id}")
    else:
        print("FAILURE: CRM Customer ID not found in conversation custom attributes.")
        print("Available custom attributes:", json.dumps(custom_attributes, indent=2))

if __name__ == "__main__":
    # Replace with your actual values
    access_token = os.getenv("GENESYS_ACCESS_TOKEN")
    environment = os.getenv("GENESYS_ENVIRONMENT", "mypurecloud.com")
    conversation_id = "YOUR_CONVERSATION_ID_HERE" # Replace with the ID from startChat()

    if access_token and conversation_id != "YOUR_CONVERSATION_ID_HERE":
        verify_crm_id_in_conversation(access_token, environment, conversation_id)
    else:
        print("Please set GENESYS_ACCESS_TOKEN and provide a valid Conversation ID.")

API Endpoint Details:

  • Method: POST
  • Path: /v2/conversations/details/query
  • Scope: view:conversation
  • Request Body: A filter object specifying the conversation ID and type (webchat).
  • Response: A JSON object containing an array of entities. Each entity represents a conversation with its metadata, including customAttributes.

Complete Working Example

Below is a complete, self-contained HTML file that initializes the Web Messaging SDK, starts a chat with a CRM Customer ID, and logs the session ID. You must replace YOUR_DEPLOYMENT_ID_HERE with your actual Deployment ID.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Genesys Web Messaging CRM ID Integration</title>
    <script src="https://web-messaging-sdk.pure.cloud/sdk/2.0/genesys-cloud-web-messaging-sdk.min.js"></script>
    <style>
        body { font-family: sans-serif; padding: 20px; }
        #status { margin-top: 20px; padding: 10px; background: #f0f0f0; border-radius: 5px; }
        .error { color: red; }
        .success { color: green; }
    </style>
</head>
<body>
    <h1>Genesys Web Messaging CRM ID Pass</h1>
    <button id="startChatBtn">Start Chat with CRM ID</button>
    <div id="status"></div>

    <script>
        const CONFIG = {
            deploymentId: "YOUR_DEPLOYMENT_ID_HERE",
            environment: "mypurecloud.com",
            locale: "en-us"
        };

        let sdk = null;

        async function initializeSDK() {
            try {
                if (typeof window.GenesysCloudWebMessaging === 'undefined') {
                    throw new Error("SDK not loaded.");
                }
                sdk = window.GenesysCloudWebMessaging;
                await sdk.initialize({
                    deploymentId: CONFIG.deploymentId,
                    environment: CONFIG.environment,
                    locale: CONFIG.locale
                });
                updateStatus("SDK Initialized.", "success");
            } catch (error) {
                updateStatus("SDK Initialization Failed: " + error.message, "error");
            }
        }

        async function startChatWithCrm() {
            if (!sdk) {
                updateStatus("SDK not initialized.", "error");
                return;
            }

            const crmCustomerId = "CRM-987654321";
            const statusDiv = document.getElementById("status");
            statusDiv.innerHTML = "Starting chat...";

            const config = {
                firstName: "Jane",
                lastName: "Doe",
                email: "jane.doe@example.com",
                customAttributes: {
                    crmCustomerId: crmCustomerId,
                    sourceSystem: "WebPortal"
                }
            };

            try {
                const session = await sdk.startChat(config);
                updateStatus(`Chat Started. Session ID: ${session.id}`, "success");
                console.log("Session ID:", session.id);
                console.log("Custom Attributes:", config.customAttributes);
            } catch (error) {
                updateStatus("Chat Start Failed: " + error.message, "error");
                console.error(error);
            }
        }

        function updateStatus(message, type) {
            const statusDiv = document.getElementById("status");
            statusDiv.textContent = message;
            statusDiv.className = type;
        }

        document.getElementById("startChatBtn").addEventListener("click", startChatWithCrm);

        // Initialize on load
        window.addEventListener("load", initializeSDK);
    </script>
</body>
</html>

Common Errors & Debugging

Error: INVALID_DEPLOYMENT_ID

  • Cause: The Deployment ID provided in the initialize() method is incorrect or the deployment is inactive.
  • Fix: Verify the Deployment ID in the Genesys Cloud Admin Console. Ensure the deployment status is “Active”.
  • Code Check:
    // Ensure deploymentId is a non-empty string
    if (!CONFIG.deploymentId || CONFIG.deploymentId.trim() === "") {
        throw new Error("Deployment ID is missing.");
    }
    

Error: CHAT_START_FAILED with 429 Status

  • Cause: Rate limiting due to excessive chat initiation requests.
  • Fix: Implement exponential backoff in your retry logic.
  • Code Check:
    async function startChatWithRetry(config, maxRetries = 3) {
        for (let i = 0; i < maxRetries; i++) {
            try {
                return await sdk.startChat(config);
            } catch (error) {
                if (error.response && error.response.status === 429) {
                    const delay = Math.pow(2, i) * 1000;
                    console.log(`Rate limited. Retrying in ${delay}ms...`);
                    await new Promise(resolve => setTimeout(resolve, delay));
                } else {
                    throw error;
                }
            }
        }
        throw new Error("Max retries exceeded.");
    }
    

Error: Custom Attributes Not Appearing in API Response

  • Cause: The attributes may not be indexed or visible in the default query response.
  • Fix: Use the POST /v2/conversations/details/query endpoint with the specific conversation ID. Ensure you have the view:conversation scope.
  • Debugging: Log the full response from the API to check if customAttributes are present but empty.
    print("Full Response:", json.dumps(data, indent=2))
    

Error: SDK Not Loaded (TypeError: Cannot read property 'initialize' of undefined)

  • Cause: The SDK script failed to load due to network issues or CSP (Content Security Policy) restrictions.
  • Fix: Check the browser console for 404 errors on the SDK script URL. Ensure your CSP allows loading scripts from *.pure.cloud.
  • Code Check:
    if (typeof window.GenesysCloudWebMessaging === 'undefined') {
        console.error("SDK script failed to load.");
    }
    

Official References