codewithkarani

Daraja C2B vs STK Push vs Till: Choosing the Right M-Pesa Flow for an ERPNext Shop

Karani GeoffreyKarani Geoffrey13 min read
On this page
  1. Three ways the same money arrives
  2. The decision table
  3. STK push: what goes out and what comes back
  4. What ERPNext's built-in "Mpesa Settings" actually does
  5. Paybill with the invoice number: the C2B path you build
  6. Reconciliation: each flow leaves a different trail
  7. In short
  8. Sources

Ask a Kenyan shop owner how customers pay and the answer is usually "M-Pesa", as if that settles it. It does not. A customer can pay your Till number with Buy Goods, pay your Paybill with an account number they type in, or approve a PIN prompt that your system sends to their phone. All three put money in your M-Pesa account. They differ in who starts the payment, what reference comes with it, and how ERPNext finds out it happened.

This article explains the three flows in plain terms, then what Daraja sends for each and what Frappe's built-in M-Pesa integration actually does when you read its source. The goal is a simple decision: which flow belongs at the counter, which belongs on an invoice you send, and what each means at month end.

Use a Till with an STK push from the POS for counter sales: the cashier sees the payment land before the sale closes. Use STK push for remote invoices when you know the customer's phone number and they are ready to pay now. Use a Paybill with the invoice number as the account number when customers pay later, on their own time. ERPNext's built-in "Mpesa Settings" covers only the first case: STK push from a POS Invoice to a Till. Paybill payments with an invoice reference need a C2B confirmation endpoint you build yourself.

Three ways the same money arrives

Separate two ideas that are often mixed up: the kind of account you hold, and the way a payment is started.

  • Till number (Buy Goods). The customer chooses Buy Goods, enters your Till number and the amount. There is no account number, so the payment carries no reference. In Daraja this is the CustomerBuyGoodsOnline transaction type.
  • Paybill (business number plus account number). The customer enters your business number, then an account number, then the amount. Whatever they type as the account number comes to you with the payment. In Daraja this is CustomerPayBillOnline, and the account number arrives as BillRefNumber.
  • STK push (M-Pesa Express, or Lipa Na M-Pesa Online). Not a third kind of account, but a way of starting a payment into a Paybill or Till: your system asks Safaricom to show a PIN prompt on the customer's phone with the amount filled in. The request uses the same two transaction types.

So: which account do you hold, and for each kind of sale, should the customer start the payment or should your system?

The decision table

SituationBest fitWhyWhat ERPNext matches on
Customer standing at the counterSTK push to your Till, started from the POSThe cashier sees the result before closing the sale. No typing errors in amounts.The CheckoutRequestID your system got back when it sent the prompt
Counter sale, customer pays the Till themselvesPlain Till (Buy Goods)Works with no integration at all. Good as a fallback when the prompt fails.Nothing automatic. The cashier records the M-Pesa receipt code by hand.
Remote invoice, customer ready to pay nowSTK pushOne tap for the customer. Amount and reference come from your system, not their typing.CheckoutRequestID, then the MpesaReceiptNumber in the callback
Remote invoice, customer pays laterPaybill, invoice number as the account numberThe customer pays when it suits them, and the invoice number travels with the money.BillRefNumber (what the customer typed) and TransID
Regular customers on credit or statementsPaybill, customer code as the account numberOne stable reference per customer is easier to remember than a new invoice number each time.BillRefNumber mapped to the Customer, then allocated to open invoices

The pattern: when your system starts the payment, it knows the invoice. When the customer starts it, you learn only what they typed, and sometimes they type it wrong.

Who starts each M-Pesa flow and how ERPNext hears about it STK push: ERPNext starts the payment and gets a callback. Paybill: the customer types an account number and a C2B confirmation follows. Till paid by hand: the cashier records the receipt code. Who starts it What carries the reference How ERPNext hears STK push ERPNext sends the prompt CheckoutRequestID returned to you when you send it Callback to the URL in the request Paybill customer starts, types account BillRefNumber whatever the customer typed C2B confirmation to a URL registered once Till, paid by hand customer starts, no account field Nothing of yours only amount, time and receipt Cashier types it or a statement match later The further down the table, the less your system knows about which invoice the money is for.
When ERPNext starts the payment it owns the reference. When the customer starts it, ERPNext gets only what the customer typed, or nothing.

STK push: what goes out and what comes back

An STK push is a POST to /mpesa/stkpush/v1/processrequest on sandbox.safaricom.co.ke or api.safaricom.co.ke, authorised with a bearer token from /oauth/v1/generate?grant_type=client_credentials (HTTP Basic auth with your consumer key and secret). The body carries BusinessShortCode, a Password built by base64-encoding the shortcode, your passkey and a timestamp joined together, the Timestamp, TransactionType, Amount, PartyA (the payer's phone), PartyB, PhoneNumber, CallBackURL, AccountReference and TransactionDesc. If the prompt never reaches the phone, the 1025/9999 "unable to send STK prompt" article covers the usual causes.

The immediate response, with a MerchantRequestID and CheckoutRequestID, only means the prompt was accepted for sending. The money is confirmed when Safaricom posts to your CallBackURL. This example is shaped like the samples in Safaricom's PHP SDK and the Frappe payments tests, with placeholder values:

{
  "Body": {
    "stkCallback": {
      "MerchantRequestID": "...",
      "CheckoutRequestID": "ws_CO_...",
      "ResultCode": 0,
      "ResultDesc": "The service request is processed successfully.",
      "CallbackMetadata": {
        "Item": [
          { "Name": "Amount", "Value": 500 },
          { "Name": "MpesaReceiptNumber", "Value": "..." },
          { "Name": "TransactionDate", "Value": 20201006113336 },
          { "Name": "PhoneNumber", "Value": 2547XXXXXXXX }
        ]
      }
    }
  }
}

Read CallbackMetadata.Item by Name, not by position (the Frappe test payload includes a Balance item with no value), and treat a non-zero ResultCode as "this attempt did not pay". The piece on 1019, 1037 and 1032 goes through the common ones. If the callback never arrives, Daraja has a query endpoint, /mpesa/stkpushquery/v1/query, that takes the same shortcode, password and timestamp plus the CheckoutRequestID; this article on reconciling missing callbacks covers that path.

What ERPNext's built-in "Mpesa Settings" actually does

ERPNext's M-Pesa support lives in Frappe's separate payments app, in the Mpesa Settings doctype under payments/payment_gateways/doctype/mpesa_settings/. Here is what it does on the develop branch, with the ERPNext develop code that calls it.

Setting it up

The doctype stores the consumer key and secret, a Till Number (required), a Business Shortcode (required when Sandbox is off), the online passkey, initiator credentials for the account balance button, and a Transaction Limit defaulting to 150000. It accepts only KES. Saving it creates a Payment Gateway Mpesa-<your name>, a Mode of Payment of type Phone, a "Request for Payment" button and a read-only "Mpesa Receipt Number" field on POS Invoice, and adds "Mobile No" to the POS invoice fields.

The flow at the till

  1. The cashier enters the customer's mobile number and presses Request for Payment. The form saves the POS Invoice, freezes the screen with "Waiting for payment...", and asks the server to create a payment request.
  2. POSInvoice.create_payment_request creates (or reuses) an Inward Payment Request against the POS Invoice, with the mobile number in its email_to field and the gateway's Phone channel.
  3. On submit, a Phone-channel Payment Request calls request_phone_payment, which hands over to MpesaSettings.request_for_payment.
  4. If the amount is above the Transaction Limit, the controller splits it into several STK pushes. Each request gets a random token in its callback URL; only a SHA-256 hash of the token is stored, in an Integration Request named after the CheckoutRequestID. The code comments say why: M-Pesa callbacks are unsigned, so the secret in the URL is what authenticates them.
  5. The callback, verify_transaction, checks the token, ignores any callback for a request that is no longer Queued (so a replay cannot change a settled payment), reads Amount and MpesaReceiptNumber, adds up all completed requests for the same Payment Request, and once the total reaches the request's grand total marks it Paid. It writes the receipt numbers into the POS Invoice's mpesa_receipt_number and pushes a realtime event that tells the POS screen to submit the invoice.
  6. The screen also checks on its own after 60 seconds. If the Payment Request is still not Paid by then, it unfreezes and shows "Request Timeout", asking the cashier to request payment again.

Which flow it really implements

Look at the request it sends and the answer is clear. In production, the connector sends TransactionType: "CustomerBuyGoodsOnline" with BusinessShortCode set to your Business Shortcode and PartyB set to your Till Number. In sandbox it sends CustomerPayBillOnline and uses the till number as the shortcode. So out of the box this is STK push to a Till, started from a POS Invoice. A few consequences worth knowing:

  • No Paybill in production. The transaction type is fixed by environment, not by a setting, so a Paybill-only business cannot use it as written.
  • The account reference is your till number, not the invoice. TransactionDesc is "POS Payment". The invoice link is the Integration Request, keyed by CheckoutRequestID.
  • No C2B. There is no Register URL call and no confirmation or validation endpoint. A customer who pays your Till or Paybill directly is invisible to it.
  • No status query. It does not call the STK query or Transaction Status APIs. If a callback is lost, the Integration Request stays Queued.
  • No Payment Entry for Phone requests. For a Phone-channel Payment Request, set_as_paid only sets the status to Paid and the outstanding amount to zero. That fits the POS, where the invoice's own payment rows carry the money. If you point this gateway at an ordinary Sales Invoice sent to a remote customer, you would need to create the Payment Entry yourself.
  • Phone numbers are normalised simply: "254" + number.lstrip("0"). A number entered as +2547... would not come out right.
  • A new access token per request. The connector calls the OAuth endpoint every time it is created; caching the token is the usual fix.

Paybill with the invoice number: the C2B path you build

For invoices that customers pay later, the Paybill is the natural fit, and it needs Daraja's Customer to Business (C2B) API. You call Register URL once for your shortcode, with four fields: ShortCode, ResponseType, ConfirmationURL and ValidationURL. Safaricom's Node library describes ResponseType as what M-Pesa does by default if a transaction times out: Completed or Cancelled.

The validation URL is where you could say "no" before money moves. Safaricom's sample validation script answers {"ResultCode": 0, ...} to accept and a non-zero ResultCode to reject. The confirmation URL is told after the payment is complete. Safaricom's SDK reads these fields from it: TransactionType, TransID, TransTime, TransAmount, BusinessShortCode, BillRefNumber, InvoiceNumber, OrgAccountBalance, ThirdPartyTransID, MSISDN and the payer's name fields. A confirmation shaped like those field lists looks like this (placeholder values):

{
  "TransactionType": "...",
  "TransID": "...",
  "TransTime": "...",
  "TransAmount": "...",
  "BusinessShortCode": "...",
  "BillRefNumber": "SINV-...",
  "InvoiceNumber": "",
  "OrgAccountBalance": "...",
  "ThirdPartyTransID": "",
  "MSISDN": "...",
  "FirstName": "..."
}

Here is how you would wire that into ERPNext:

  1. Print the Paybill number on the Sales Invoice and ask customers to use the invoice name as the account number.
  2. Expose a whitelisted, guest-accessible method for the confirmation. Unlike the STK flow, Register URL is a one-time setup, so there is no per-payment token in the URL. Protect the endpoint another way, and do not trust the payload on its own.
  3. Store every confirmation first, keyed by TransID, and ignore a TransID you have already seen (more in duplicate callbacks).
  4. Normalise BillRefNumber (trim, upper-case) and look for an open Sales Invoice with that name. If it matches, create a Payment Entry against it with TransID as the reference number; ERPNext insists on a reference number and date for bank-type accounts anyway.
  5. If it does not match, record the payment anyway (against the customer if you can identify them, otherwise unallocated) and queue it for a person. Customers mistype; never drop the payment.

If you use Safaricom's C2B sandbox while building this, read why sandbox C2B callbacks are unreliable before you spend a day debugging your own endpoint.

Reconciliation: each flow leaves a different trail

Your M-Pesa statement records what happened; your ERPNext ledger records what you believe happened. The flows differ in how easily you can join the two.

  • STK push gives the cleanest trail: you created the request, you know the invoice, and the callback carries the MpesaReceiptNumber that also appears on the statement. In the built-in integration that receipt lands on the POS Invoice's mpesa_receipt_number field.
  • Paybill C2B gives you TransID and BillRefNumber. Matching by TransID is exact; matching to the invoice depends on what the customer typed.
  • Till paid by hand gives your system nothing unless the cashier records the receipt code. Check those sales against the statement daily.

For all three, run a daily job that compares the statement with what ERPNext recorded, and use the Transaction Status API (/mpesa/transactionstatus/v1/query, with CommandID set to TransactionStatusQuery and a ResultURL for the asynchronous answer) for anything that does not line up. See the guides on nightly reconciliation and statement-to-ledger matching. New to Daraja? Start with the production guide to STK push, C2B and B2C, and see one counter sale, end to end for where the callback sits.

In short

  • At the counter: Till plus STK push from the POS. ERPNext's built-in Mpesa Settings does exactly this. Keep "customer pays the Till by hand" as the fallback, and record the receipt code.
  • Remote invoice, paying now: STK push. The built-in integration is written around the POS Invoice, so plan to create the Payment Entry yourself.
  • Remote invoice, paying later: Paybill with the invoice number as the account number, plus a C2B confirmation endpoint you build. ERPNext does not provide one.
  • Everywhere: store every callback, ignore repeats, reconcile daily.

Sources

Frequently asked questions

Should an ERPNext shop use a Till or a Paybill for M-Pesa?
Use a Till for counter sales, ideally with an STK push sent from the ERPNext POS so the cashier sees the payment confirmed before closing the sale. Use a Paybill when customers pay invoices later on their own, because a Paybill payment carries the account number the customer types, which can be the invoice number. A business can hold both.
Does ERPNext support M-Pesa out of the box?
Yes, through the Mpesa Settings doctype in Frappe's payments app. Reading its source on the develop branch, it sends an STK push from a POS Invoice, in production as a Buy Goods (Till) payment, and marks the Payment Request paid when Safaricom's callback confirms the amount. It does not register C2B URLs, so payments a customer makes directly to a Till or Paybill are not picked up automatically.
Is STK push a different kind of M-Pesa account?
No. STK push (M-Pesa Express, or Lipa Na M-Pesa Online) is a way of starting a payment, not an account type. Your system asks Safaricom to show a PIN prompt on the customer's phone, and the request says whether the money goes to a Paybill (CustomerPayBillOnline) or a Till (CustomerBuyGoodsOnline).
How do I match a Paybill payment to an ERPNext invoice?
Ask customers to enter the invoice name as the account number, register a C2B confirmation URL with Daraja, and when a confirmation arrives read its BillRefNumber and TransID. Store it keyed by TransID so repeats are ignored, look up an open Sales Invoice with that name, and create a Payment Entry using the TransID as the reference number. Payments whose account number does not match should be recorded anyway and queued for a person to allocate.
What happens in ERPNext if the STK push callback never arrives?
In the built-in integration the Integration Request stays Queued and the POS screen gives up after 60 seconds with a Request Timeout message. The integration does not call Daraja's STK query or Transaction Status APIs, so recovering a lost callback means checking the payment yourself, for example with a daily reconciliation against the M-Pesa statement.
#M-Pesa#Daraja#STK Push#C2B#Point of Sale#ERPNext#Reconciliation

Written by

Karani Geoffrey

Software engineer in Nairobi and founder of Upeosoft. I build ERPNext, AI and web systems that businesses run on, and write down what I learn along the way. More about me

Keep reading