Configure Web Messaging Deployment Colors and Launcher Position via API

Configure Web Messaging Deployment Colors and Launcher Position via API

What You Will Build

  • One sentence: This script programmatically creates or updates a Genesys Cloud Web Messaging deployment with custom CSS variables for colors and specific coordinates for the launcher button.
  • One sentence: This uses the Genesys Cloud PureCloud Platform Client V2 SDK (Python) and the REST API directly.
  • One sentence: The primary programming language covered is Python, with JavaScript equivalents provided for browser-side integration contexts.

Prerequisites

  • OAuth Client Type: Machine-to-Machine (M2M) or User-to-Machine (U2M) client.
  • Required Scopes:
    • webmessaging:deployment:write (To create or update deployments)
    • webmessaging:deployment:read (To verify creation)
  • SDK Version: genesys-cloud-purecloud-platform-client >= 170.0.0
  • Language/Runtime: Python 3.9+
  • External Dependencies:
    • genesys-cloud-purecloud-platform-client
    • python-dotenv (for credential management)

Authentication Setup

Genesys Cloud uses OAuth 2.0 for API authentication. For server-side scripts that configure deployments, the Machine-to-Machine (M2M) flow is the standard approach. This requires a registered application with a Client ID and Client Secret.

The following code initializes the SDK client with M2M authentication. The SDK handles the token exchange and caching automatically.

import os
from dotenv import load_dotenv
from purecloud_platform_client import Configuration, ApiClient, WebMessagingApi

# Load environment variables from .env file
load_dotenv()

def get_web_messaging_api_client() -> WebMessagingApi:
    """
    Initializes and returns an authenticated WebMessagingApi client.
    """
    # Construct the configuration object with M2M credentials
    config = Configuration(
        client_id=os.getenv("GENESYS_CLIENT_ID"),
        client_secret=os.getenv("GENESYS_CLIENT_SECRET"),
        environment=os.getenv("GENESYS_ENVIRONMENT", "mypurecloud.com") # e.g., usw2.pure.cloud
    )
    
    # Create the API client
    api_client = ApiClient(configuration=config)
    
    # Initialize the Web Messaging API instance
    web_messaging_api = WebMessagingApi(api_client=api_client)
    
    return web_messaging_api

Ensure your .env file contains:

GENESYS_CLIENT_ID=your_client_id_here
GENESYS_CLIENT_SECRET=your_client_secret_here
GENESYS_ENVIRONMENT=mypurecloud.com

Implementation

Step 1: Define the Deployment Configuration Payload

The core of customizing the Web Messaging UI lies in the properties object within the deployment definition. Genesys Cloud exposes specific CSS variables that map to the visual elements of the widget.

Key properties for customization:

  • launcherPosition: Defines where the button appears (e.g., bottom-right, bottom-left).
  • launcherOffsetX / launcherOffsetY: Pixel offsets from the edge.
  • primaryColor: The main color of the launcher and header.
  • secondaryColor: The background color of the chat window.
  • textColor: The color of text within the chat.

We construct the payload using the SDK models to ensure type safety.

from purecloud_platform_client.models import (
    WebMessagingDeployment,
    WebMessagingDeploymentProperties,
    WebMessagingDeploymentLauncher
)

def build_custom_deployment_payload() -> WebMessagingDeployment:
    """
    Constructs a WebMessagingDeployment object with custom UI settings.
    """
    # Define the launcher behavior and position
    launcher = WebMessagingDeploymentLauncher(
        position="bottom-right",  # Options: bottom-right, bottom-left
        offset_x=20,              # Pixels from the right edge
        offset_y=20,              # Pixels from the bottom edge
        image_url="https://example.com/custom-icon.png" # Optional custom icon
    )

    # Define the visual properties using CSS variable names
    # These map directly to CSS variables in the embedded widget
    properties = WebMessagingDeploymentProperties(
        primary_color="#0056b3",      # Brand blue for launcher/header
        secondary_color="#ffffff",    # White background for chat
        text_color="#333333",         # Dark gray text
        primary_button_color="#0056b3",
        secondary_button_color="#f0f0f0",
        header_text_color="#ffffff",
        user_text_color="#0056b3",
        bot_text_color="#333333"
    )

    # Construct the main deployment object
    deployment = WebMessagingDeployment(
        name="Custom Branded Deployment",
        description="Deployment with custom colors and launcher position",
        enabled=True,
        launcher=launcher,
        properties=properties,
        # Optional: Link to a specific flow
        # flow_id="your-flow-id-here" 
    )

    return deployment

Step 2: Create or Update the Deployment

Genesys Cloud deployments are identified by a unique ID. To update an existing deployment, you must first retrieve it, modify the properties, and then send a PUT request. To create a new one, you send a POST request.

The following function attempts to create a new deployment. If you are updating an existing one, use the put_web_messaging_deployment method instead.

Scope Required: webmessaging:deployment:write

import logging

# Configure basic logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def create_deployment(api_client: WebMessagingApi, deployment: WebMessagingDeployment) -> str:
    """
    Creates a new web messaging deployment.
    Returns the deployment ID.
    """
    try:
        logger.info("Creating web messaging deployment...")
        
        # Call the API to create the deployment
        response = api_client.post_web_messaging_deployments(
            body=deployment
        )
        
        if response is None:
            raise Exception("API returned None response. Check logs for details.")
            
        logger.info(f"Deployment created successfully with ID: {response.id}")
        return response.id

    except Exception as e:
        logger.error(f"Failed to create deployment: {e}")
        raise

def update_deployment(api_client: WebMessagingApi, deployment_id: str, deployment: WebMessagingDeployment) -> None:
    """
    Updates an existing web messaging deployment.
    """
    try:
        logger.info(f"Updating web messaging deployment: {deployment_id}")
        
        # Call the API to update the deployment
        api_client.put_web_messaging_deployment(
            deployment_id=deployment_id,
            body=deployment
        )
        
        logger.info(f"Deployment updated successfully: {deployment_id}")

    except Exception as e:
        logger.error(f"Failed to update deployment: {e}")
        raise

Step 3: Verify the Configuration

After creation, it is critical to verify that the properties were persisted correctly. This step also demonstrates how to read the deployment back.

Scope Required: webmessaging:deployment:read

def verify_deployment(api_client: WebMessagingApi, deployment_id: str) -> WebMessagingDeployment:
    """
    Retrieves a deployment by ID and logs its key properties.
    """
    try:
        response = api_client.get_web_messaging_deployment(
            deployment_id=deployment_id
        )
        
        logger.info(f"Verified Deployment ID: {response.id}")
        logger.info(f"Name: {response.name}")
        logger.info(f"Enabled: {response.enabled}")
        
        if response.launcher:
            logger.info(f"Launcher Position: {response.launcher.position}")
            logger.info(f"Launcher Offset X: {response.launcher.offset_x}")
            logger.info(f"Launcher Offset Y: {response.launcher.offset_y}")
            
        if response.properties:
            logger.info(f"Primary Color: {response.properties.primary_color}")
            logger.info(f"Secondary Color: {response.properties.secondary_color}")
            
        return response

    except Exception as e:
        logger.error(f"Failed to verify deployment: {e}")
        raise

Complete Working Example

This script combines authentication, payload construction, creation, and verification into a single runnable module.

#!/usr/bin/env python3
"""
Genesys Cloud Web Messaging Deployment Configurator
--------------------------------------------------
Configures a Web Messaging deployment with custom colors and launcher position.
"""

import os
import sys
import logging
from dotenv import load_dotenv

from purecloud_platform_client import Configuration, ApiClient, WebMessagingApi
from purecloud_platform_client.models import (
    WebMessagingDeployment,
    WebMessagingDeploymentProperties,
    WebMessagingDeploymentLauncher
)

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

def get_api_client() -> WebMessagingApi:
    """Initializes the Genesys Cloud API client."""
    load_dotenv()
    
    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 in environment variables.")

    config = Configuration(
        client_id=client_id,
        client_secret=client_secret,
        environment=environment
    )
    
    api_client = ApiClient(configuration=config)
    return WebMessagingApi(api_client=api_client)

def create_custom_deployment() -> str:
    """Main function to orchestrate deployment creation."""
    
    # 1. Initialize Client
    web_messaging_api = get_api_client()
    
    # 2. Build Payload
    # Custom Launcher Settings
    launcher = WebMessagingDeploymentLauncher(
        position="bottom-right",
        offset_x=24,
        offset_y=24,
        image_url="https://example.com/assets/support-icon.png"
    )
    
    # Custom Color Palette
    properties = WebMessagingDeploymentProperties(
        primary_color="#2C3E50",       # Dark Blue-Gray
        secondary_color="#ECF0F1",     # Light Gray
        text_color="#333333",          # Dark Text
        primary_button_color="#2C3E50",
        secondary_button_color="#BDC3C7",
        header_text_color="#FFFFFF",   # White Header Text
        user_text_color="#2C3E50",     # User Bubble Color
        bot_text_color="#FFFFFF"       # Bot Bubble Text
    )
    
    deployment = WebMessagingDeployment(
        name="DevTest Custom UI Deployment",
        description="Automated deployment for testing color and position customization.",
        enabled=True,
        launcher=launcher,
        properties=properties
    )
    
    # 3. Create Deployment
    try:
        logger.info("Attempting to create deployment...")
        response = web_messaging_api.post_web_messaging_deployments(body=deployment)
        
        if not response or not response.id:
            raise Exception("Deployment creation failed: No ID returned.")
            
        deployment_id = response.id
        logger.info(f"Deployment created successfully. ID: {deployment_id}")
        
        # 4. Verify Configuration
        logger.info("Verifying configuration...")
        verified = web_messaging_api.get_web_messaging_deployment(deployment_id=deployment_id)
        
        logger.info("--- Verification Details ---")
        logger.info(f"Position: {verified.launcher.position}")
        logger.info(f"Primary Color: {verified.properties.primary_color}")
        logger.info(f"Secondary Color: {verified.properties.secondary_color}")
        
        return deployment_id

    except Exception as e:
        logger.error(f"Error during deployment process: {e}")
        sys.exit(1)

if __name__ == "__main__":
    deployment_id = create_custom_deployment()
    print(f"\nSuccess. Deployment ID: {deployment_id}")
    print("You can now embed this deployment using the Web Messaging SDK.")

Common Errors & Debugging

Error: 401 Unauthorized

  • Cause: The OAuth token is invalid, expired, or the Client ID/Secret is incorrect.
  • Fix: Verify your .env file credentials. Ensure the client application in Genesys Cloud Admin is active and has the webmessaging:deployment:write scope assigned.
  • Code Check:
    # Ensure environment variables are loaded before initialization
    load_dotenv()
    

Error: 403 Forbidden

  • Cause: The OAuth client lacks the required scope.
  • Fix: Go to Admin > Security > Applications > Your Application > Scopes. Add webmessaging:deployment:write and webmessaging:deployment:read. Save and restart your script to force a token refresh.

Error: 400 Bad Request - “Invalid property value”

  • Cause: The color codes are not in valid HEX format (e.g., missing # or using RGB strings).
  • Fix: Ensure all color fields use standard 6-digit HEX codes prefixed with # (e.g., #FF5733).
  • Code Check:
    # Correct
    properties = WebMessagingDeploymentProperties(primary_color="#FF5733")
    
    # Incorrect
    properties = WebMessagingDeploymentProperties(primary_color="red")
    

Error: Launcher Position Not Changing

  • Cause: The launcher object is not properly nested in the WebMessagingDeployment model, or the position value is invalid.
  • Fix: Valid positions are bottom-right and bottom-left. Ensure the WebMessagingDeploymentLauncher object is explicitly passed to the launcher argument of the deployment.
  • Code Check:
    # Ensure the launcher object is instantiated and passed
    launcher = WebMessagingDeploymentLauncher(position="bottom-right")
    deployment = WebMessagingDeployment(launcher=launcher, ...)
    

Official References