feat(payments): M-Pesa STK push, callback and reconciliation (#31) #98

Merged
amiryahaya merged 17 commits from feat/31-mpesa into main 2026-10-26 07:35:08 +01:00
Owner

Closes #31.

What

  • Start: POST /v1/me/transactions/{id}/pay/mpesa (202, Idempotency-Key required). One transaction: lock sale, checks, MarkProcessing, a payment_attempts row (migration 0019, one active attempt per sale) and the payments.mpesa.stk job (new jobs.EnqueueTx). Daraja is never called inside a transaction.
  • STK job: calls Daraja outside any lock. A 4xx fails the attempt (permanent). After Daraja may have received the request the job never pushes again (ErrMaybeSent marks the attempt failed; the customer restarts).
  • Callback: 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 through Service.Settle, reference = CheckoutRequestID. The token is redacted from access logs and problem instance.
  • Reconciliation (every minute): queries sent attempts after 2 min (20 per run); created >10 min and sent >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.
  • Disabled unless all KWS_MPESA_* are set (start route answers 503, no job, no callback route).
  • ADR 0013, CLAUDE.md Payments section, spec R-PAY-2/3, ADR 0012 follow-ups.

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 to 2547../2541..; M-Pesa disabled by default. Full list in docs/superpowers/plans/2026-10-26-mpesa.md and ADR 0013.

Known limits

  • If Daraja accepts a push but we time out or crash before the reference is stored, a paying customer's callback matches no attempt: it answers 404 and logs at Error with reference, amount and receipt for a manual refund.
  • A leaked callback token plus a known CheckoutRequestID could forge a paid callback. No IP allowlist; success callbacks are not re-verified with an STK Query.
  • Result code 4999 is treated as pending ([verify] against the sandbox). The sandbox smoke test (KWS_MPESA_SANDBOX=1) has not been run against Safaricom.
  • Checkout does not yet refuse mpesa for totals with cents (start returns 422).
  • Minor open: redaction of unclean path variants (/./, //), one redaction test asserts absence only.

Deploy notes

  • Run migration 0019 (KWS_MODE=migrate); the worker (KWS_MODE=worker) must be running.
  • Set KWS_MPESA_ENV (sandbox|production), CONSUMER_KEY, CONSUMER_SECRET, SHORTCODE, PASSKEY, CALLBACK_BASE_URL (https), CALLBACK_TOKEN (>=32 chars of A-Za-z0-9_-); all or none.
  • Register {CALLBACK_BASE_URL}/v1/payments/mpesa/callback/{CALLBACK_TOKEN} with Safaricom.
  • App DB role must be neither owner nor superuser.

Verification

  • make cover: 90.3% total (minimum 80%)
  • make lint: 0 issues; make contract: ok
  • go test -race ./...: all packages pass (DB tests ran; only the opt-in sandbox test skips); new concurrency tests also pass with -count=3
  • Dual-pass review (ponytail complexity, then correctness) per task and on the whole branch: no Must fix or Critical/Important left; fixes after Pass 2 re-checked by both passes.

🤖 Generated with Claude Code

Closes #31. ## What - **Start:** `POST /v1/me/transactions/{id}/pay/mpesa` (202, Idempotency-Key required). One transaction: lock sale, checks, `MarkProcessing`, a `payment_attempts` row (migration 0019, one active attempt per sale) and the `payments.mpesa.stk` job (new `jobs.EnqueueTx`). Daraja is never called inside a transaction. - **STK job:** calls Daraja outside any lock. A 4xx fails the attempt (permanent). After Daraja may have received the request the job never pushes again (`ErrMaybeSent` marks the attempt failed; the customer restarts). - **Callback:** `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 through `Service.Settle`, reference = `CheckoutRequestID`. The token is redacted from access logs and problem `instance`. - **Reconciliation** (every minute): queries `sent` attempts after 2 min (20 per run); `created` >10 min and `sent` >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. - Disabled unless all `KWS_MPESA_*` are set (start route answers 503, no job, no callback route). - ADR 0013, CLAUDE.md Payments section, spec R-PAY-2/3, ADR 0012 follow-ups. ## 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 to `2547..`/`2541..`; M-Pesa disabled by default. Full list in `docs/superpowers/plans/2026-10-26-mpesa.md` and ADR 0013. ## Known limits - If Daraja accepts a push but we time out or crash before the reference is stored, a paying customer's callback matches no attempt: it answers 404 and logs at Error with reference, amount and receipt for a manual refund. - A leaked callback token plus a known `CheckoutRequestID` could forge a paid callback. No IP allowlist; success callbacks are not re-verified with an STK Query. - Result code 4999 is treated as pending ([verify] against the sandbox). The sandbox smoke test (`KWS_MPESA_SANDBOX=1`) has not been run against Safaricom. - Checkout does not yet refuse `mpesa` for totals with cents (start returns 422). - Minor open: redaction of unclean path variants (`/./`, `//`), one redaction test asserts absence only. ## Deploy notes - Run migration 0019 (`KWS_MODE=migrate`); the worker (`KWS_MODE=worker`) must be running. - Set `KWS_MPESA_ENV` (sandbox|production), `CONSUMER_KEY`, `CONSUMER_SECRET`, `SHORTCODE`, `PASSKEY`, `CALLBACK_BASE_URL` (https), `CALLBACK_TOKEN` (>=32 chars of `A-Za-z0-9_-`); all or none. - Register `{CALLBACK_BASE_URL}/v1/payments/mpesa/callback/{CALLBACK_TOKEN}` with Safaricom. - App DB role must be neither owner nor superuser. ## Verification - `make cover`: **90.3%** total (minimum 80%) - `make lint`: 0 issues; `make contract`: ok - `go test -race ./...`: all packages pass (DB tests ran; only the opt-in sandbox test skips); new concurrency tests also pass with `-count=3` - Dual-pass review (ponytail complexity, then correctness) per task and on the whole branch: no Must fix or Critical/Important left; fixes after Pass 2 re-checked by both passes. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
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>
- STK job: once Daraja accepted, only the MarkSent write is retried
  (3 tries, 200 ms, ctx-aware; a duplicate checkout ref is not retried);
  a final failure is logged with the attempt and CheckoutRequestID and is
  Permanent, so the phone is never prompted twice by a job retry.
- Cents in the total: plain 422 problem with a fixed detail, no field.
- AccountReference: last 12 hex characters of the sale id (random part).
- Tests: released seats -> not payable; idempotent replay of the start
  route in the live contract test; OpenAPI notes a repeat ignores a
  different phone.

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>
- STK job: an attempt older than 5 minutes is failed, not pushed; a push whose
  attempt left 'created' meanwhile (MarkSent matched no row) is logged at Error
  with the CheckoutRequestID and returned as permanent, never re-pushed.
- Reconciliation: a sent attempt older than 30 minutes with no final result
  (pending, rejected query, unsettleable event) is failed, freeing the query
  slot and letting the abandoned-sale cancel apply; a late callback still settles.
- Tests: expiry extended before the lock, context cancelled inside each loop.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
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>
docs(payments): unmatched callback is an Error only when paid (#31)
All checks were successful
ci / changes (pull_request) Successful in 26s
ci / clients (pull_request) Successful in 1m25s
ci / api (pull_request) Successful in 21m44s
ci / ci-gate (pull_request) Successful in 7s
e3360eb09c
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
primatekuntech/kws!98
No description provided.