Custom GatewayGateway BuilderConfigurationAdvancedTutorial

Mastering the Custom USSD Gateway Builder: Complete Guide

USSD Playground Team
15 min read

Introduction to Custom Gateway Configuration

The Custom USSD Gateway Builder is a powerful tool that lets you configure USSD integration with any provider, regardless of their API format. Whether you're working with a non-standard provider or need advanced customization, the custom builder gives you complete control.

Why Use the Custom Builder?

Your USSD provider isn't in the standard templates
You need specific field transformations
Your provider uses a unique request/response format
You require advanced authentication methods
You want to test multiple providers without code changes
You need to handle complex response formats (XML, CSV, arrays)

When to Use Custom Builder vs Templates

📋 Use Templates When

  • • Your provider is Africa's Talking, Arkesel, Nalo, or Wigal
  • • Standard configuration meets your needs
  • • You want quick setup (1-2 minutes)
  • • You don't need custom transformations

🔧 Use Custom Builder When

  • • Your provider has a unique API format
  • • You need field transformations (e.g., phone number formatting)
  • • You require custom authentication
  • • Your responses come in non-standard formats
  • • You need advanced features like retry logic or array handling

Understanding Field Mappings

Field mappings define how data from your USSD session maps to your API request.

Source Variables Available:

sessionId

Unique session identifier

phoneNumber

User's phone number (e.g., +233540000000)

userInput

Last input from user

fullText

Complete accumulated input (e.g., "1*2*3")

serviceCode

USSD code dialed (e.g., *123#)

networkCode

Network operator (mtn, vodafone, etc.)

isNewSession

Boolean indicating new session

  • stepNumber: Current step in the session
  • Target Paths:

    Use dot notation to specify where data should go in your request:

    // Simple path
    payload.sessionId → { "payload": { "sessionId": "xxx" } }
    
    // Nested path
    data.user.phone → { "data": { "user": { "phone": "xxx" } } }
    
    // Root level
    phone → { "phone": "xxx" }

    5 Types of Field Transforms

    1. Conditional Transform

    Map boolean or truthy values to specific strings.

    Use Case: Convert isNewSession to "start" or "continue"

    Source: isNewSession
    Type: Conditional
    True Value: "start"
    False Value: "continue"
    
    Result: true → "start", false → "continue"

    2. Template Transform

    Insert values into a template string.

    Use Case: Format phone numbers or create custom strings

    Source: phoneNumber
    Type: Template
    Template: "User: {{value}} on {{networkCode}}"
    
    Result: "User: +233540000000 on mtn"

    You can use any source variable in templates:

    • {{value}} - The source field value
    • {{sessionId}} - Session ID
    • {{phoneNumber}} - Phone number
    • {{networkCode}} - Network code
    • And all other source variables

    3. Regex Transform

    Use regular expressions to extract or modify values.

    Use Case: Extract country code or format phone numbers

    Source: phoneNumber
    Type: Regex
    Pattern: ^\+233(\d+)$
    Replacement: 0$1
    
    Result: "+233540000000" → "0540000000"

    Common Patterns:

    • Remove spaces: \s+""
    • Extract digits: [^\d]""
    • Format phone: ^\+(\d{3})(\d+)$"$1-$2"

    4. Lookup Transform

    Map values using a lookup table.

    Use Case: Convert user selections to API codes

    Source: userInput
    Type: Lookup
    Lookup Map:
    {
      "1": "check_balance",
      "2": "transfer_money",
      "3": "buy_airtime"
    }
    Default Value: "unknown"
    
    Result: "1" → "check_balance", "5" → "unknown"

    5. Concat Transform

    Combine multiple source fields.

    Use Case: Create composite identifiers

    Type: Concat
    Sources: [sessionId, phoneNumber, networkCode]
    Separator: "_"
    
    Result: "sess123_+233540000000_mtn"

    Configuring Request Formats

    JSON Requests (Most Common)

    Method: POST
    Content-Type: application/json
    
    Payload:
    {
      "session": "{{sessionId}}",
      "phone": "{{phoneNumber}}",
      "input": "{{userInput}}"
    }

    URL-Encoded Requests

    Method: POST
    Content-Type: application/x-www-form-urlencoded
    
    Payload:
    session={{sessionId}}&phone={{phoneNumber}}&input={{userInput}}

    GET Requests with Query Parameters

    Method: GET
    
    URL: /endpoint?session={{sessionId}}&phone={{phoneNumber}}

    Setting Up Response Parsing

    Message Path Configuration

    Tell the builder where to find the message in your response:

    // Simple path
    Response: { "message": "Welcome" }
    Message Path: message
    
    // Nested path
    Response: { "data": { "text": "Welcome" } }
    Message Path: data.text
    
    // Array access
    Response: { "messages": ["Welcome"] }
    Message Path: messages[0]

    Session Control

    Prefix-based:

    Type: Prefix
    End Prefix: "END"
    
    Response: "CON Welcome" → Continue
    Response: "END Goodbye" → End

    Field-based:

    Type: Field
    Field Path: status
    End Value: "complete"
    
    Response: { "status": "complete" } → End
    Response: { "status": "pending" } → Continue

    Authentication Options

    1. Bearer Token

    Type: Bearer
    Token: your-bearer-token-here
    
    Header: Authorization: Bearer your-bearer-token-here

    2. API Key

    Type: API Key
    Header Name: X-API-Key
    API Key Value: your-api-key-here
    
    Header: X-API-Key: your-api-key-here

    3. Basic Authentication

    Type: Basic
    Username: your-username
    Password: your-password
    
    Header: Authorization: Basic BASE64(username:password)

    Advanced Features

    Array Response Handling

    When your API returns an array of items (e.g., menu options):

    Enable Array Handling: ✓
    Item Template: "{{index}}. {{name}} - {{price}}"
    Join Separator: "\n"
    Max Items: 10
    
    Response: [{"name": "Item 1", "price": "$10"}, {"name": "Item 2", "price": "$20"}]
    Result:
    1. Item 1 - $10
    2. Item 2 - $20

    Response Transformations

    Clean and format response messages:

    1. Trim: Remove leading/trailing whitespace
    2. Uppercase: Convert to uppercase
    3. Lowercase: Convert to lowercase
    4. Replace: Find and replace text using regex
    5. Truncate: Limit message length with ellipsis
    6. Remove Prefix: Strip specific prefix
    7. Remove Suffix: Strip specific suffix

    Example Pipeline:

    1. Trim (remove whitespace)
    2. Replace: "\s+" → " " (normalize spaces)
    3. Truncate: 160 characters with "..."

    Multi-Format Response Parsing

    Handle non-JSON responses:

    XML:

    Format: XML
    Message Tag: message
    Session End Tag: status
    Session End Value: complete

    CSV:

    Format: CSV
    Delimiter: ,
    Message Column: 0

    Pipe-Delimited (Wigal):

    Format: Pipe-Delimited
    Message Index: 4
    Session Control Index: 1

    Retry Logic and Timeout

    Timeout Configuration:

    Request Timeout: 30000ms (30 seconds)

    Retry Configuration:

    Enable Retry: ✓
    Max Attempts: 3
    Backoff: 1000ms
    Retry on Status Codes: 500, 502, 503, 504

    Conditional Field Mappings

    Include fields only when conditions are met:

    Field: networkCode
    Condition: isNewSession equals true
    
    Result: Only includes networkCode on first request

    Available Operators:

    • equals
    • notEquals
    • contains
    • greaterThan
    • lessThan
    • exists

    Testing Your Custom Gateway

    Using the Test Harness

    1. Navigate to the "Test" tab
    2. Enter your endpoint URL
    3. Provide a mock response
    4. Click "Run Test"
    5. Review request/response/parsed output

    Quick Test Scenarios

    The test harness provides pre-built scenarios:

    • Menu Response (CON with options)
    • End Response (END with message)
    • Array Response (list of items)
    • Error Response (error handling)

    Import/Export Gateway Configs

    Export Configuration

    1. Click "Export" button
    2. Download as JSON file
    3. Or copy to clipboard

    Import Configuration

    1. Click "Import" button
    2. Paste JSON or upload file
    3. Configuration loads instantly

    This is perfect for:

    • Sharing configs with team members
    • Backing up configurations
    • Moving between environments
    • Version control

    Real-World Examples

    Example 1: Custom Banking API

    Request:
    - Method: POST
    - Content-Type: application/json
    - Field Mappings:
      - sessionId → transaction.id
      - phoneNumber → customer.msisdn (with regex: remove +233)
      - userInput → transaction.data
      - isNewSession → transaction.type (conditional: "init" / "continue")
    
    Response:
    - Format: JSON
    - Message Path: response.displayText
    - Session Control: Field-based (response.status === "END")
    
    Authentication:
    - Type: Bearer
    - Token: {{API_TOKEN}}

    Example 2: Legacy XML System

    Request:
    - Method: POST
    - Content-Type: application/xml
    - Custom XML template with field mappings
    
    Response:
    - Format: XML
    - Message Tag: DisplayText
    - Session End Tag: SessionStatus
    - Session End Value: TERMINATED
    
    Authentication:
    - Type: Basic
    - Username: api_user
    - Password: {{PASSWORD}}

    Example 3: Microservice with Array Response

    Request:
    - Method: GET
    - Query parameters with field mappings
    
    Response:
    - Format: JSON
    - Message Path: products
    - Array Handling:
      - Template: "{{index}}. {{name}} - GHS {{price}}"
      - Separator: "\n"
      - Max Items: 5
    - Transforms:
      - Trim
      - Truncate: 160 chars

    Troubleshooting Common Issues

    Issue: Request Not Reaching Endpoint

    Solutions:

    • Verify endpoint URL is correct and accessible
    • Check authentication credentials
    • Ensure firewall allows incoming requests
    • Test endpoint with cURL first

    Issue: Response Not Parsing Correctly

    Solutions:

    • Verify message path matches response structure
    • Check response format (JSON/XML/CSV)
    • Use test harness to debug
    • Review response in logs

    Issue: Session Ending Unexpectedly

    Solutions:

    • Check session end indicator configuration
    • Verify prefix or field value matches
    • Review response logs
    • Test with different session control methods

    Issue: Field Transform Not Working

    Solutions:

    • Verify regex pattern syntax
    • Check lookup map keys match exactly
    • Ensure template variables are correct
    • Test transform in isolation

    Best Practices

    1. Start Simple: Begin with basic configuration, add complexity gradually
    2. Test Thoroughly: Use test harness before live testing
    3. Document Your Config: Add comments in your exported JSON
    4. Version Control: Keep configs in git for tracking changes
    5. Use Validation: Check validation tab for errors
    6. Monitor Logs: Review session logs regularly
    7. Handle Errors: Configure error handling and fallback messages
    8. Optimize Performance: Use appropriate timeout and retry settings

    Validation and Error Prevention

    The custom builder includes comprehensive validation:

    • ✅ Required fields check
    • ✅ Duplicate target path detection
    • ✅ Transform configuration validation
    • ✅ Regex pattern syntax check
    • ✅ Response path validation
    • ✅ Authentication settings check

    Always check the Validation tab before deploying!

    Conclusion

    The Custom USSD Gateway Builder gives you complete control over USSD integration with any provider. With support for:

    • 5 transform types for data manipulation
    • 3 authentication methods
    • Multiple response formats (JSON, XML, CSV, pipe-delimited)
    • Advanced features (arrays, transforms, retry logic)
    • Comprehensive validation
    • Import/export capabilities

    You can integrate with any USSD provider without writing custom code.

    Ready to build your custom gateway? Get started with USSD Playground and configure your integration in minutes.

    Share this article

    Help others discover this content

    🚀 Ready to Start?

    Build Your USSD App Today

    Start testing with our free USSD simulator. No credit card required. Get started in minutes.

    Get Started Free

    Join hundreds of developers building USSD applications