Mastering the Custom USSD Gateway Builder: Complete Guide
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?
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:
sessionIdUnique session identifier
phoneNumberUser's phone number (e.g., +233540000000)
userInputLast input from user
fullTextComplete accumulated input (e.g., "1*2*3")
serviceCodeUSSD code dialed (e.g., *123#)
networkCodeNetwork operator (mtn, vodafone, etc.)
isNewSessionBoolean indicating new 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" → EndField-based:
Type: Field
Field Path: status
End Value: "complete"
Response: { "status": "complete" } → End
Response: { "status": "pending" } → ContinueAuthentication Options
1. Bearer Token
Type: Bearer
Token: your-bearer-token-here
Header: Authorization: Bearer your-bearer-token-here2. API Key
Type: API Key
Header Name: X-API-Key
API Key Value: your-api-key-here
Header: X-API-Key: your-api-key-here3. 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 - $20Response Transformations
Clean and format response messages:
- Trim: Remove leading/trailing whitespace
- Uppercase: Convert to uppercase
- Lowercase: Convert to lowercase
- Replace: Find and replace text using regex
- Truncate: Limit message length with ellipsis
- Remove Prefix: Strip specific prefix
- 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: completeCSV:
Format: CSV
Delimiter: ,
Message Column: 0Pipe-Delimited (Wigal):
Format: Pipe-Delimited
Message Index: 4
Session Control Index: 1Retry 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, 504Conditional Field Mappings
Include fields only when conditions are met:
Field: networkCode
Condition: isNewSession equals true
Result: Only includes networkCode on first requestAvailable Operators:
- equals
- notEquals
- contains
- greaterThan
- lessThan
- exists
Testing Your Custom Gateway
Using the Test Harness
- Navigate to the "Test" tab
- Enter your endpoint URL
- Provide a mock response
- Click "Run Test"
- 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
- Click "Export" button
- Download as JSON file
- Or copy to clipboard
Import Configuration
- Click "Import" button
- Paste JSON or upload file
- 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 charsTroubleshooting 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
- Start Simple: Begin with basic configuration, add complexity gradually
- Test Thoroughly: Use test harness before live testing
- Document Your Config: Add comments in your exported JSON
- Version Control: Keep configs in git for tracking changes
- Use Validation: Check validation tab for errors
- Monitor Logs: Review session logs regularly
- Handle Errors: Configure error handling and fallback messages
- 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.
Build Your USSD App Today
Start testing with our free USSD simulator. No credit card required. Get started in minutes.
Get Started FreeJoin hundreds of developers building USSD applications