Dynamic QR
By the end of this track you can charge a phone and confirm the result.
0/4 finished
Step 1
The idea
A QR code that encodes your till and an amount. The customer scans it in the M-Pesa app.
Step 2
How it works
What the QR holds
A Dynamic QR encodes who to pay, how much and a reference. The customer scans it with the M-Pesa app, sees the details filled in, and enters their PIN. It is a C2B payment with no typing, so fewer wrong account numbers.
The request
POST to /mpesa/qrcode/v1/generate. It needs only your Bearer token: no passkey, no initiator. TrxCode sets the payment type: BG for Buy Goods (a Till), PB for Paybill, and also WA, SM and SB for agent withdrawals, send money and send to business. CPI is the number being paid, and must match the TrxCode. Amounts are whole shillings.
{ "MerchantName": "Mama Mboga Stores", "RefNo": "ORDER1042", "Amount": 250, "TrxCode": "BG", "CPI": "373132", "Size": "300"}The response
QRCode is a base64 PNG. Show it as an image: <img src="data:image/png;base64,…">.
{ "ResponseCode": "AG_20191219_000043fdf61864fe9ff5", "RequestID": "16738-27456357-1", "ResponseDescription": "QR Code Successfully Generated.", "QRCode": "iVBORw0KGgoAAAANSUhEUgAAASwAAAEs…"}Knowing it was paid
Generating a QR creates no pending transaction and no callback. The payment arrives like any C2B payment, on your confirmation URL from lesson C3. Match it by amount, shortcode and time window, plus the account number for a Paybill. If you need a strict one-to-one match between order and payment, use STK Push instead.
Step 3
Try it
With the MCP server, ask your agent to use mpesa_generate_dynamic_qr
Step 4
Common mistakes
- Treating the generated QR as proof of payment.
- Generating a new QR on every page view. Make one per order and keep it.
- Using
BGwith a Paybill number, orPBwith a Till.
Go deeper
How do you learn that the QR was paid?
Answer in your own words first.
Show the answerHide the answer
The same way as C2B: the confirmation, or a status query.