USSD (Unstructured Supplementary Service Data) provides a powerful way to reach users without internet access. By maintaining session state on your server, you can build complex applications like banking menus, voting systems, or data collection forms.
How it works
When a user dials your shortcode (e.g., *203#), Moolre sends a POST request to your configured callback URL. The request contains a sessionid which persists across the interaction.
Your server must respond with a JSON object containing:
message: The text to display on the user's screen.reply: A boolean.truekeeps the session open for user input;falseends the session.
State machine pattern
Since HTTP is stateless, you need to track "where" the user is in your menu. You can use the sessionid as a key in a database (Redis, SQL) to store the user's current "stage".
Code example
Below is a Node.js implementation of a simple banking menu that allows users to check their balance or initiate a transfer.
const express = require('express');const app = express();app.use(express.json());// In-memory session store (Use Redis in production)const sessions = {}; app.post('/ussd/callback', (req, res) => { const { sessionid, msisdn, message, new: isNew } = req.body; // Initialize session if (isNew) { sessions[sessionid] = { stage: 'MENU' }; return res.json({ message: "Welcome to Moolre Bank\n1. Check Balance\n2. Transfer Money", reply: true }); } const userSession = sessions[sessionid] || { stage: 'MENU' }; // State Machine Logic switch (userSession.stage) { case 'MENU': if (message === '1') { // End session return res.json({ message: "Your balance is GHS 50.00", reply: false }); } else if (message === '2') { userSession.stage = 'TRANSFER_AMOUNT'; return res.json({ message: "Enter amount to transfer:", reply: true }); } else { return res.json({ message: "Invalid Option\n1. Balance\n2. Transfer", reply: true }); } break; case 'TRANSFER_AMOUNT': userSession.amount = message; userSession.stage = 'TRANSFER_RECIPIENT'; return res.json({ message: "Enter recipient phone number:", reply: true }); break; case 'TRANSFER_RECIPIENT': // Perform logic... return res.json({ message: `Transfer of GHS ${userSession.amount} to ${message} initiated.`, reply: false }); break; } // Save state back to store sessions[sessionid] = userSession;});Tips
- Timeout Handling: USSD sessions time out quickly (usually 30-60 seconds). Keep your API response times under 2 seconds.
- Character Limits: USSD screens vary by device. Keep your
messageconcise (under 160 chars) to ensure it displays correctly on all phones. - Pagination: For long lists, implement a "Press 9 for more" logic to handle pagination manually within your state machine.
