Skip to content

USSD-Driven Voting System

Enable millions of users to cast votes instantly via mobile money by dialing a simple shortcode.

In markets with high mobile money penetration but variable internet connectivity, USSD is the king of accessibility. This guide demonstrates how to build a voting system where users dial a shortcode (e.g., *203*101#), select a contestant, and receive an instant payment prompt to cast their vote.

Concept

The interaction combines two distinct Moolre APIs: the USSD API for the menu interface and the Payment API for the transaction.

1

User dials USSD

User dials *203*101# and sees the list of contestants.

2

Trigger payment

Your backend receives the selection and triggers Mobile Money Collection.

3

Confirm vote

User enters their PIN. The callback confirms payment and counts the vote.

USSD voting workflow

Crucially, the USSD session must end before or immediately as the user receives the payment prompt. Mobile networks often block payment prompts if a USSD session is still active on the screen.

  1. The user enters a selection in the USSD menu.
  2. Your server captures the msisdn (phone number) and the selection.
  3. Your server calls the Mobile Money Collection API for that msisdn.
  4. Your server responds with reply: false to close the session and show a "Please approve payment" message.

Implementation code

The following code shows how to handle the USSD callback and trigger the payment.

const express = require('express');const axios = require('axios');const app = express();​// Mock Databaseconst contestants = { '1': { name: 'Kwame', id: 'C_001' }, '2': { name: 'Ama', id: 'C_002' } };​// 1. Handle USSD Requestapp.post('/ussd/callback', async (req, res) => {    const { sessionid, msisdn, message, new: isNew } = req.body;​    if (isNew) {        // Render Main Menu        return res.json({            message: "Reality Star 2025\n1. Vote for Kwame\n2. Vote for Ama",            reply: true        });    }​    // Handle User Selection    const selectedOption = message.trim();    const contestant = contestants[selectedOption];​    if (contestant) {        // 2. Trigger Payment Prompt (Background Process)        initiateVotePayment(msisdn, contestant);​        // End USSD Session immediately so user can see Payment Prompt        return res.json({            message: `You selected ${contestant.name}. Please authorize the GHS 2.00 payment prompt sent to your phone to cast your vote.`,            reply: false        });    } else {        return res.json({ message: "Invalid Option. Try again.", reply: false });    }});​// Helper: Trigger Mobile Money Promptasync function initiateVotePayment(phoneNumber, contestant) {    try {        await axios.post('https://api.moolre.com/open/transact/payment', {            type: 1,            channel: '13', // MTN (Dynamically detect network in prod)            currency: 'GHS',            amount: 2.00, // Cost per vote            payer: phoneNumber,            externalref: `VOTE_${contestant.id}_${Date.now()}`, // Embed contestant ID in ref            reference: `Vote for ${contestant.name}`,            accountnumber: process.env.ACCOUNT_ID        }, {            headers: {                 'X-API-PUBKEY': process.env.PUB_KEY,                 'X-API-USER': process.env.USER             }        });    } catch (error) {        console.error("Payment trigger failed", error);    }}

Vote confirmation

Since the payment happens asynchronously (the user might take 10-30 seconds to enter their PIN), you cannot count the vote inside the USSD logic. You must rely on the payment callback.

Use the externalref field to pass metadata (like the Contestant ID) through the payment process so you can retrieve it in the callback.

// 3. Handle the Payment Confirmation Callbackapp.post('/webhook/moolre', (req, res) => {    const { txstatus, externalref, amount } = req.body.data;​    // Only count successful transactions    if (txstatus === 1) {        // Extract Contestant ID from the reference we set earlier        // Format: VOTE_{CONTESTANT_ID}_{TIMESTAMP}        const parts = externalref.split('_');        if (parts.length >= 2 && parts[0] === 'VOTE') {            const contestantId = parts[1];                        // Calculate weight (e.g., higher amount = more votes)            const votes = Math.floor(amount / 2.00); ​            console.log(`Recorded ${votes} votes for Contestant ${contestantId}`);            // TODO: Update Database: db.votes.increment(contestantId, votes);        }    }        res.sendStatus(200);});