feat(payments): M-Pesa STK push, callback and reconciliation (#31) #98
No reviewers
Labels
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
primatekuntech/kws!98
Loading…
Reference in a new issue
No description provided.
Delete branch "feat/31-mpesa"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Closes #31.
What
POST /v1/me/transactions/{id}/pay/mpesa(202, Idempotency-Key required). One transaction: lock sale, checks,MarkProcessing, apayment_attemptsrow (migration 0019, one active attempt per sale) and thepayments.mpesa.stkjob (newjobs.EnqueueTx). Daraja is never called inside a transaction.ErrMaybeSentmarks the attempt failed; the customer restarts).POST /v1/payments/mpesa/callback/{token}(public). Secret path token (constant time) plus attempt lookup; sale, currency come from the attempt, never the request. Settles throughService.Settle, reference =CheckoutRequestID. The token is redacted from access logs and probleminstance.sentattempts after 2 min (20 per run);created>10 min andsent>30 min are failed; a processing sale past expiry with no active attempt is cancelled (payment was not completed). A late callback still settles a failed attempt.KWS_MPESA_*are set (start route answers 503, no job, no callback route).Rulings (author's call, no design round)
Origin check without signatures; reference =
CheckoutRequestID; one active attempt per sale; cents or non-KES totals refused (422, plain problem); phone normalised to2547../2541..; M-Pesa disabled by default. Full list indocs/superpowers/plans/2026-10-26-mpesa.mdand ADR 0013.Known limits
CheckoutRequestIDcould forge a paid callback. No IP allowlist; success callbacks are not re-verified with an STK Query.KWS_MPESA_SANDBOX=1) has not been run against Safaricom.mpesafor totals with cents (start returns 422)././,//), one redaction test asserts absence only.Deploy notes
KWS_MODE=migrate); the worker (KWS_MODE=worker) must be running.KWS_MPESA_ENV(sandbox|production),CONSUMER_KEY,CONSUMER_SECRET,SHORTCODE,PASSKEY,CALLBACK_BASE_URL(https),CALLBACK_TOKEN(>=32 chars ofA-Za-z0-9_-); all or none.{CALLBACK_BASE_URL}/v1/payments/mpesa/callback/{CALLBACK_TOKEN}with Safaricom.Verification
make cover: 90.3% total (minimum 80%)make lint: 0 issues;make contract: okgo test -race ./...: all packages pass (DB tests ran; only the opt-in sandbox test skips); new concurrency tests also pass with-count=3🤖 Generated with Claude Code
POST /v1/me/transactions/{id}/pay/mpesa locks the sale, checks it is the caller's open KES mpesa sale in whole shillings, marks it processing, records the attempt and enqueues payments.mpesa.stk in the same transaction (new jobs pgstore EnqueueTx). An active attempt is returned as is, so a double click is one push. The STK job calls Daraja with no transaction open: sent -> MarkSent, 4xx -> attempt failed + Permanent, 5xx/network -> retry. The callback route and the worker job are wired only when KWS_MPESA_* is set; otherwise the start route answers 503. Both operations are in the OpenAPI spec and the live contract test. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>Every minute (worker, only when M-Pesa is configured): created attempts older than 10 minutes fail; processing M-Pesa sales past expires_at with no active attempt and no succeeded payment are cancelled ("payment was not completed"), re-checked under the sale lock, one transaction each; sent attempts older than 2 minutes are queried (20 per run): 0 settles with the attempt's amount in one transaction with Finish(settled), a final code fails the attempt, pending is left, ErrUnavailable stops the run for a retry, ErrRejected is logged. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>- StartSTK returns ErrMaybeSent for any failure after the push request went out (timeout, dropped connection, 5xx, unreadable reply); the STK job fails the attempt and does not retry. Token fetch failures stay ErrUnavailable. - A callback with the right token and an unknown CheckoutRequestID is logged at Error with the id, amount and receipt (no phone, token or body); 404. - STK query ResultCode 4999 is pending [verify against sandbox]. - KWS_MPESA_CALLBACK_TOKEN must be 32+ characters of [A-Za-z0-9_-]. - Paths under /v1/payments/mpesa/callback/ are always logged and returned as .../{token}, also on the mux's 404/405 fallback. - ADR 0013 and CLAUDE.md: state when money can still be orphaned. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>- Remove Provider.Start, payments.StartRequest/StartResult and the provider's Daraja client (the STK job pushes); STKClient now belongs to the job. - settleAttempt (Settle + Finish(settled) + refund warning) shared by the callback and reconciliation; failAttempt replaces the pasted closures. - config.Config holds mpesa.Config directly (mpesa does not import config). - NormalizePhone uses one regexp; Config.Enabled is c != Config{}. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>- STK job: once the push may be out, the attempt write runs with context.WithoutCancel and a 5 s budget (also MarkSent); a write that still fails is logged at Error and returned Permanent, so nothing re-pushes. - An unknown-id callback with a non-zero ResultCode is a plain warning (no money moved); only a paid one logs the refund-by-hand Error. - Any path containing /mpesa/callback/ is logged as .../{token}. - ADR 0013 and CLAUDE.md: ErrMaybeSent after a real accept is an orphan source; only the OAuth token fetch retries. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>