DEV Community

Cover image for A $1 QR code that lets Kisumu shops take bitcoin and get M-Pesa
Stanley Chege Thuita
Stanley Chege Thuita

Posted on Edited on AI-assisted

A $1 QR code that lets Kisumu shops take bitcoin and get M-Pesa

The short version, for everyone: On 8 November 2026 two small shops in Kisumu started accepting bitcoin. A customer scans a printed QR code with any Lightning wallet and pays in sats; the shop receives Kenyan shillings on M-Pesa. The shopkeeper needs no wallet, no exchange account and no knowledge of bitcoin. This post explains how one $1 QR code makes that work, and why kTown never holds anyone's money, with the code and tests behind it.

On 8 November 2026 two small shops in Kisumu started accepting bitcoin.

The customer scans a QR code with any Lightning wallet and pays in sats. The shop receives Kenyan shillings in M-Pesa. The till works the way it always has.

The product is called kTown: https://altradits.com/ktown/. Its code is open source, in lib/ktown.js (686 lines) in the altradits repo, pinned here to commit 05a129d:

GitHub logo altradits / altradits

YeBente is a free Bitcoin Lightning wallet for everyday people. Its AI agency now thinks with Meta Muse.

Altradits

Tests and security checks License: MIT

The code behind altradits.com: free Bitcoin tools and learning for people new to Bitcoin, including Ye₿ente, a custodial Bitcoin Lightning wallet for everyday amounts, and the admin dashboard that runs the Lightning node behind it.

What lives here

  • server.mjs, api/: the website and its API (Node.js, no framework).
  • lib/: shared code: wallets, Lightning, receipts, mail, security.
  • yebente/: the Ye₿ente wallet app (React + Vite). The shipped build in yebente/app is committed with the source that produced it.
  • assets/admin.js, admin.html: the node operator dashboard.
  • test/: the test suite, including the build-stage security guard.
  • docs/: manuals and guides (setup, Lightning, review process).
  • deploy/, .github/: signed-merge tooling, deploy and CI.

Quick start

Requirements: Node.js 20 or newer (CI runs 24).

npm ci --ignore-scripts
cp .env.example .env
npm run dev
Enter fullscreen mode Exit fullscreen mode

Open http://localhost:3000 (admin: /admin, token dev on a local machine only)…

Contents

  1. How onboarding works
  2. What's actually in the QR code
  3. The flow, end to end
  4. kTown is a thin front, not a wallet
  5. Two ways to price a payment
  6. Never trust the partner's invoice blindly
  7. One record per payment
  8. The receipt: when has the shop really been paid?
  9. Phone numbers, PINs and the takeover rule
  10. Failing closed
  11. What kTown stores, and what it never asks
  12. Tests
  13. What it costs, and who pays
  14. How you can help

How onboarding works

  1. Meet the merchant. I walk the shops, explain how it works and answer questions.
  2. Set up the QR. The shop registers with its M-Pesa number and gets its own QR code.
  3. Scan and pay in sats. Any Lightning wallet works.
  4. It lands in M-Pesa. Shillings go straight to the merchant's phone.

What's actually in the QR code

The QR on the counter is not an invoice. A Lightning invoice (BOLT11) is for one amount and expires, so it can't be printed and laminated. Instead the QR holds an LNURL: a bech32-encoded URL that a wallet decodes and visits. For kTown it points at:

https://altradits.com/.well-known/lnurlp/k-<shop id>
Enter fullscreen mode Exit fullscreen mode

That makes it a static, reusable "pay this shop" code, the same mechanism behind Lightning addresses (LUD-06 and LUD-16). The shop id is random (crypto.randomBytes(9).toString("base64url")), so ids can't be guessed or enumerated.

The flow, end to end

 1. Wallet scans the QR      GET altradits.com/.well-known/lnurlp/k-<id>
 2. kTown asks Tando         GET bitcoin.co.ke/.well-known/lnurlp/2547XXXXXXXX
                             <- limits, KES rate (LUD-21)
 3. kTown answers wallet     payRequest: shop name, limits, rate
 4. Customer types amount
 5. Wallet calls callback    GET altradits.com/api/ktown/lnurlp/<id>/cb?amount=...
 6. kTown asks Tando         GET <Tando callback>?amount=...[&currency=KES]
                             <- BOLT11 invoice
 7. kTown checks it          amount in range? hash recorded once
 8. kTown answers wallet     Tando's invoice, unchanged
 9. Wallet pays              sats go straight to Tando over Lightning
10. Tando pays out           KES to the shop's M-Pesa number
11. Receipt                  status, isPaid, M-Pesa code, per payment hash
Enter fullscreen mode Exit fullscreen mode

The sats in step 9 go directly to Tando, a Kenyan service that turns Lightning payments into M-Pesa transfers for a 1% fee. kTown is never in the money path.

kTown is a thin front, not a wallet

The file's opening comment states the design:

// kTown never holds money and is not a wallet: it is a thin LNURL-pay front
// for the merchant's Tando address ([email protected]). The sats go
// straight to Tando, Tando pays KES to the M-Pesa number for a 1% fee.
Enter fullscreen mode Exit fullscreen mode

Why put anything in front of Tando at all? A shop could print its Tando address directly. kTown adds the things a shop actually needs:

  • The shop's name on the payer's screen. The LNURL metadata says "Mall Café", not a phone number.
  • A phone number that isn't printed on the counter. The QR holds a random id, not the owner's M-Pesa number.
  • A history and receipts for the shopkeeper, in English or Swahili.
  • Checks on every invoice the partner returns (below).

The payRequest kTown returns is built from the merchant's record and Tando's live limits:

export function payRequestJson(site, merchant, quote) {
  const domain = String(site || "").replace(/^https?:\/\//, "").replace(/\/.*$/, "");
  return {
    tag: "payRequest",
    callback: `${site}/api/ktown/lnurlp/${merchant.id}/cb`,
    minSendable: Math.floor(quote.minMsat),
    maxSendable: Math.floor(quote.maxMsat),
    metadata: JSON.stringify([["text/plain", `${merchant.mpesaName}\n${merchant.shop}`],
                              ["text/identifier", `k-${merchant.id}@${domain}`]]),
    commentAllowed: 0,
    currency: { code: "KES", minSendable: Math.floor(quote.kesMin), maxSendable: Math.floor(quote.kesMax), multiplier: quote.multiplier },
    verified: Boolean(merchant.verified),
  };
}
Enter fullscreen mode Exit fullscreen mode

commentAllowed: 0 is deliberate: no free-text field means nothing about the payer is ever collected.

Two ways to price a payment

Here is the subtle part. Tando speaks LUD-21, a draft extension that lets a wallet ask for an amount in a currency instead of millisats. So there are two paths, and kTown supports both:

KES mode (wallet speaks LUD-21) msat mode (every other wallet)
Wallet asks for amount=500&currency=KES amount=<millisats>
Invoice is 500 KES in sats plus the 1% on top Exactly the millisats asked
Shop receives Exactly 500 KES The KES value minus 1%, floored to whole shillings
Who pays the 1% The payer Comes out of the shop's amount

Why not "fix" msat mode by asking Tando for 1% more? Because LUD-06 requires the invoice amount to equal exactly the millisats the wallet asked for; any wallet would (correctly) reject a bigger invoice. The code comment explains the choice not to cheat around it:

// No grossing up anywhere: in KES mode Tando already delivers exactly, so
// asking for more would overcharge the payer; in msat mode LUD-06 requires
// the invoice to equal the millisats the wallet asked for, so the 1% cannot
// be added there either. What lands short is named honestly instead: the
// entry keeps which path priced it, and history shows quoted vs received.
Enter fullscreen mode Exit fullscreen mode

So every history entry records which mode priced it, the rate, the expected shillings and the received shillings, and the shopkeeper sees both. The payer's fee in KES mode is computed to two decimals and can never go negative:

// Never below zero: rate drift can only shrink the invoice's value, never bill the merchant.
export const kesFee = (msats, mult, kes) => Math.max(0, Math.round((msats / mult - kes) * 100) / 100);
Enter fullscreen mode Exit fullscreen mode

Never trust the partner's invoice blindly

Tando returns the invoice the customer will pay. If that invoice were for the wrong amount (a bug, or a compromised partner), the customer would be overcharged with kTown's name on the screen. So tandoInvoice checks every invoice before passing it on.

In msat mode the rule is simple: the invoice must be for exactly what was asked.

} else if (msats !== n) {
  substitution(`asked ${n} msat, got ${msats}`);
  throw err("The payout partner's invoice is for a different amount.", 502);
}
Enter fullscreen mode Exit fullscreen mode

In KES mode the exact sats can't be known in advance (Tando prices at its live rate, plus 1%), so the check is a band around the expected value, and Tando's own echo of the shillings must match:

// The invoice is the KES value in sats plus the 1% on top, at Tando's live
// rate. The band allows the 1%, rounding up to whole sats, and the rate
// moving in the seconds between our two calls.
msatLo = Math.floor(n * quote.multiplier * 0.97);
msatHi = Math.ceil(n * quote.multiplier * 1.05) + 1000;
...
if (inv.converted != null && Number(inv.converted) !== n) {
  substitution(`asked ${n} KES, converted says ${inv.converted}`);
  throw err("The payout partner's invoice is for a different amount.", 502);
}
if (msats < msatLo || msats > msatHi) { substitution(...); throw err(...); }
Enter fullscreen mode Exit fullscreen mode

Every mismatch is recorded as an invoice_substitution event in the site's security log, the same signal the Ye₿ente wallet uses for Lightning addresses that return the wrong invoice. The quote itself is always fetched fresh ({ fresh: true }) for the invoice, so a cached rate from a minute ago can't skew the band.

One record per payment

A wallet can retry a callback, or a customer can tap twice. Every invoice has a unique payment hash, so kTown keys its records by it:

// One record per payment hash: a repeated invoice reuses its first record.
const seen = await getJSON(`kt:pay:${hash}`);
const entry = (seen && (await getJSON(`kte:${seen}`))) || { id: newId(), merchantId: merchant.id, at: now(), status: "pending",
  hash, msats, sats: ..., kesExpected, mode: mode === "KES" ? "kes" : "msat", mult: quote.multiplier,
  feeKes: kesFee(msats, quote.multiplier, kesExpected), kesReceived: null, mpesaCode: null, ... };
Enter fullscreen mode Exit fullscreen mode

The hash is read straight out of the BOLT11 invoice (tagged field p), with a fallback to the hash in Tando's receipt URL.

The receipt: when has the shop really been paid?

A Lightning payment settling is not the same as shillings arriving on M-Pesa. Tando exposes a public status endpoint per payment hash, and kTown counts a payment as settled only when all three hold:

const settled = rc.status === "completed" && rc.isPaid && Boolean(rc.mpesaCode);
Enter fullscreen mode Exit fullscreen mode

The M-Pesa confirmation code is the proof the shopkeeper can check on their own phone. Three more rules keep the receipt endpoint from becoming a lookup service:

  • Only hashes kTown recorded are answered. A stranger's payment hash is refused without asking Tando at all.
  • A receipt for another number moves nothing. The payout must be to this merchant's own number (rc.payToAccount === merchant.phone).
  • The registered name is revealed only on a match. Tando returns the M-Pesa registered name of the recipient. kTown compares it with the name the shopkeeper typed, and only answers it when they match, so a wrong guess learns nothing. A match also marks the shop's name as verified, which the pay page shows to customers.

Payments made by scanning the printed QR straight from a wallet never pass through kTown's pay page, so the shop's own app asks for its newest pending payments (at most 5, only from the last 3 days, rate-limited per session) to confirm them.

Phone numbers, PINs and the takeover rule

Phone numbers arrive as 07…, +254 7… or 2547…. All become 254 plus 9 digits, and only Safaricom ranges are accepted, because only those resolve at Tando:

export function normalizePhone(input) {
  let d = String(input || "").replace(/\D/g, "");
  if (d.startsWith("254")) d = d.slice(3);
  d = d.replace(/^0+/, "");
  if (d.length !== 9 || !(d.startsWith("7") || d.startsWith("11") || d.startsWith("14"))) throw err(bad);
  return `254${d}`;
}
Enter fullscreen mode Exit fullscreen mode

Registration proves the number works: it asks Tando for that number's LNURL and refuses unless the answer is a KES payRequest. A number pointing at a bitcoin wallet rather than M-Pesa is rejected with "That number isn't set up for M-Pesa delivery."

PINs are 6 digits and refuse patterns: two or fewer distinct digits, straight runs up or down, repeated pairs or triples, and a list of common choices like 147258. They are stored as scrypt hashes (N = 16384, r = 8, p = 1) with a random salt, compared with timingSafeEqual, and five wrong tries lock logins for 15 minutes:

function pinHash(pin, salt = crypto.randomBytes(16).toString("hex")) {
  return { salt, hash: crypto.scryptSync(String(pin), salt, 32, { N: 16384, r: 8, p: 1 }).toString("hex") };
}
Enter fullscreen mode Exit fullscreen mode

Two sign-ups racing for one number can't both win: registration takes a per-number lock, re-checks inside it, and the pilot cap is re-counted after the record is written, so two strangers taking the last place in the same second never overshoot it.

The takeover rule handles a real problem: what if someone registers your M-Pesa number before you do? Payouts would still go to your phone (the number decides where money lands), but they would control the shop's name and history. So a number that is still unclaimed after 48 hours, with no paid receipt, can be taken over by a new sign-up. A number becomes claimed when a real payment's receipt shows the M-Pesa registered name matching the shop's. Claimed numbers, or any with a paid receipt, can never be taken.

Failing closed

Every call to Tando goes through one guard, and anything unexpected is treated as "unreachable", never as data:

async function tandoJson(url) {
  const r = await tandoFetch(url, { signal: AbortSignal.timeout(8000), headers: { Accept: "application/json" }, maxBytes: 65536 })
    .catch(() => { throw err(UNREACHABLE, 502); });
  if (r.status >= 300 && r.status < 400) throw err(UNREACHABLE, 502);      // no redirects
  const type = String(r.headers.get("content-type") || "").split(";")[0].trim().toLowerCase();
  if (type !== "application/json") throw err(UNREACHABLE, 502);            // no HTML error pages
  const d = await r.json().catch(() => null);
  if (!d || typeof d !== "object" || Array.isArray(d)) throw err(UNREACHABLE, 502);
  return { status: r.status, ok: r.ok, body: d };
}
Enter fullscreen mode Exit fullscreen mode

publicFetch underneath refuses private and loopback IP addresses, checked on the address actually connected to (an SSRF guard). And the callback Tando names must stay on Tando:

// The callback must stay on Tando: a reply pointing elsewhere is not followed.
if (!cb || cb.protocol !== "https:" || cb.username || cb.password || cb.hostname.toLowerCase() !== TANDO) throw err(UNREACHABLE, 502);
Enter fullscreen mode Exit fullscreen mode

Without that check, a compromised or spoofed partner response could point kTown's server at any URL on the internet.

What kTown stores, and what it never asks

From the data model at the top of the file:

// A history entry carries only the merchant's own payment facts: the amount,
// the shillings expected and received, which path priced it (KES, or the
// wallet's own sats), the rate, the payer's fee, the payment hash, the M-Pesa
// code and the time. Nothing about who paid is ever stored, because it is
// never asked for and never read.
Enter fullscreen mode Exit fullscreen mode

No payer names, no payer phone numbers, no comments, no IP addresses in the history. The admin list shows each shop's phone number with only its last three digits.

Tests

The kTown tests run against a fake Tando, scripted per test, and cover each rule above by name:

phone numbers: local, plus and full forms become 254 plus 9 Safaricom digits
register: activation proves the number's Tando address works; then login, me, settings
five wrong PINs lock logins for 15 minutes
callback in KES mode: Tando's invoice unchanged, merchant receives exactly the KES
callback in msat mode: the invoice must match the millisats exactly
callback in KES mode refuses a wrong converted figure or sats outside the band
a KES shortfall is recorded honestly: quoted vs received, never hidden
receipt: only hashes kTown recorded are answered, and Tando is never asked otherwise
receipt: a receipt for another number moves nothing and names no name
Tando's odd answers fail closed: off-host callback, redirect, HTML, no KES terms
SSRF: the default Tando path refuses private addresses before connecting
a repeated invoice reuses its first record; history carries the payment hash
two sign-ups racing for one number: one wins, the other hears it is taken
takeover: a claimed number, or one with a paid receipt, cannot be taken
pilot cap: two strangers racing for the last place never overshoot it
Enter fullscreen mode Exit fullscreen mode
git clone https://github.com/altradits/altradits
cd altradits && npm install
node --test test/ktown.test.mjs test/ktown-fit.test.mjs
Enter fullscreen mode Exit fullscreen mode
ℹ tests 53
ℹ pass 53
ℹ fail 0
Enter fullscreen mode Exit fullscreen mode

What it costs, and who pays

Each QR poster costs me about $1 to produce: printed, hot-press laminated so it survives rain, flour and busy hands, and carried to the counter.

The merchants don't pay me anything. I have no sponsor. I pay for it myself. The only fee in the system is Tando's 1% for the M-Pesa payout, and the table above shows exactly who bears it on each path.

Why I'm doing it

Most people in Kisumu have only heard of bitcoin as a scam or a gamble. I want to change that story where it matters most: in the shops where people buy their bread and airtime.

The next group of bitcoin advocates in Kisumu should start with shops that already accept bitcoin. There should also be local developers trained to build bitcoin tools for local businesses and the community. That future isn't here yet. Until it is, I'll keep laying the foundation, one shop at a time.

How you can help

I'm open to help, sponsorship and collaboration:

  • Review the code. lib/ktown.js handles other people's money flows. A second pair of eyes on the invoice checks and the takeover rule is the most valuable help there is.
  • Wallet developers: LUD-21 support means Kenyan shops receive exactly what they asked for. It's worth implementing.
  • Sponsor QR codes for more shops. $1 puts one shop on bitcoin: https://altradits.com/donate.html
  • Collaborate if you're building on Lightning or work with merchants in East Africa.

Not sponsored. No paid posts.

Watch and follow

Top comments (0)