- Kotlin 99.2%
- Nix 0.6%
- Shell 0.2%
Feature: Stripe Payment Processor Integration See merge request bartdorsey/be-take-home!1 |
||
|---|---|---|
| api-requests | ||
| docs | ||
| gradle/wrapper | ||
| localstack-init | ||
| src | ||
| .editorconfig | ||
| .envrc | ||
| .gitignore | ||
| build.gradle.kts | ||
| docker-compose.yml | ||
| flake.lock | ||
| flake.nix | ||
| gradlew | ||
| gradlew.bat | ||
| README.md | ||
| settings.gradle.kts | ||
| TASK.md | ||
Property Management Platform: Credit Card Rent Payments
A property management API (Kotlin, Spring Boot, jOOQ, MySQL) extended so tenants can save credit cards and pay rent with them through Stripe, with a payment lifecycle that follows Stripe's asynchronous outcomes: 3-D Secure, webhooks, refunds, disputes, and a reconciliation job for anything a webhook misses.
The assignment is in TASK.md. The full design, with every decision and why, is in docs/design/stripe-payments.md, with a detailed design per implementation step in docs/design/steps/. How the work was done with AI is in docs/ai/ and at the end of this README.
Contents: Quick start · Try the payment flow · Run against Stripe · API · Data model and lifecycles · Assumptions and tradeoffs · Production and scale · How I used AI · Reference
Quick start
Prerequisites: JDK 17+, Docker, and jq for the examples below.
docker-compose up -d # MySQL + LocalStack (S3, SQS)
./gradlew bootRun --args='--worker.enabled=true' # API on :8080, plus the background worker
./gradlew test # unit and API tests
./gradlew integrationTest # integration tests (Docker: ElasticMQ via Testcontainers)
./gradlew test integrationTest jacocoTestReport # both, with a coverage report in build/reports/jacoco/test/html
- The worker runs inside the app when
worker.enabled=true. It processes rent generation, webhooks and reconciliation. Plain./gradlew bootRunruns the API only; a secondbootRunfor the worker would clash on port 8080. - No Stripe account is needed. The app uses an in-memory fake payment processor by default (
payments.processor=fake), which recognises Stripe's test card names. Running against Stripe's test mode is one setting away. - An existing LocalStack container created before this branch needs
docker-compose restart localstackonce, to connect the job queue to its dead-letter queue. - Formatting:
./gradlew spotlessApply(ktlint, 120 columns);./gradlew checkfails on unformatted files changed on this branch.
Every request below, and many more (errors, other roles, webhooks), is also in api-requests/api.http, which I used to exercise the API by hand.
Try the payment flow
With the app running on the fake processor:
login() { curl -s localhost:8080/api/auth/login -H 'Content-Type: application/json' \
-d "{\"email\":\"$1\",\"password\":\"password\"}" | jq -r .token; }
PM=$(login admin@greenfieldproperties.com)
ALICE=$(login alice.johnson@email.com)
1. Save a card. In a real frontend, Stripe.js collects the card and confirms the setup with Stripe directly, so card numbers never reach our servers. With the fake processor, a dev-only endpoint stands in for Stripe.js:
SETUP=$(curl -s -X POST localhost:8080/api/cards/setup -H "Authorization: Bearer $ALICE" | jq -r .setupId)
curl -s -X POST localhost:8080/api/dev/card-setups/$SETUP/confirm -H "Authorization: Bearer $ALICE" \
-H 'Content-Type: application/json' -d '{"testCard": "pm_card_visa"}'
CARD=$(curl -s -X POST localhost:8080/api/cards -H "Authorization: Bearer $ALICE" \
-H 'Content-Type: application/json' -d "{\"setupId\": \"$SETUP\"}" | jq -r .id)
Other test cards: pm_card_mastercard, pm_card_chargeDeclined, pm_card_chargeDeclinedInsufficientFunds, pm_card_authenticationRequired (3-D Secure).
The fake processor keeps its customers, cards and charges in memory, so a restart forgets them while the database remembers. The app recovers, as it would from a customer deleted in Stripe's dashboard: the tenant's next card setup gets a new customer, and cards saved before the restart are marked removed, so save them again.
2. Pay a rent charge. Charge 1 is Alice's unpaid June rent in the seed data. The amount is always the charge's outstanding balance; the client never sends one. The Idempotency-Key makes a retry safe:
curl -s -X POST localhost:8080/api/rent-charges/1/card-payments -H "Authorization: Bearer $ALICE" \
-H 'Content-Type: application/json' -H "Idempotency-Key: $(uuidgen)" -d "{\"cardId\": $CARD}" | tee payment.json
PAYMENT=$(jq -r .id payment.json)
It answers with the payment:
{
"id": 3,
"rentChargeId": 1,
"amount": 2500.00,
"paymentMethod": "CARD",
"status": "SUCCEEDED",
"refundedAmount": 0,
"card": { "brand": "visa", "last4": "4242" },
"createdAt": "2026-09-30T20:43:16Z"
}
The charge is now PAID: curl -s localhost:8080/api/rent-charges/1 -H "Authorization: Bearer $ALICE".
3. 3-D Secure. Paying with pm_card_authenticationRequired answers "status": "REQUIRES_ACTION" with a clientSecret for Stripe.js; the charge shows PROCESSING and can't be paid twice meanwhile. The dev endpoint POST /api/dev/payments/{id}/authenticate with {"approve": true} stands in for the tenant approving at their bank, and for the webhook that would report it.
4. Refund it (property managers only, with a reason):
curl -s -X POST localhost:8080/api/payments/$PAYMENT/refunds -H "Authorization: Bearer $PM" \
-H 'Content-Type: application/json' -d '{"reason": "Tenant moved out"}'
The payment and the charge become REFUNDED, and the PM's view of the payment lists the refund with its reason.
Run against Stripe's test mode
- Create a Stripe account (test mode is free) and install the Stripe CLI.
- Forward webhooks, and note the signing secret it prints:
stripe listen --forward-to localhost:8080/api/webhooks/stripe - Start the app with Stripe:
The app refuses to start if a key is missing or malformed. A restricted key (PAYMENTS_PROCESSOR=stripe STRIPE_SECRET_KEY=sk_test_… STRIPE_PUBLISHABLE_KEY=pk_test_… \ STRIPE_WEBHOOK_SECRET=whsec_… ./gradlew bootRun --args='--worker.enabled=true'rk_…) limited to customers, SetupIntents, PaymentIntents, PaymentMethods, refunds and disputes is recommended for production. - Save a card without a browser by confirming the setup with the CLI, then save and pay as above:
stripe setup_intents confirm seti_… --payment-method=pm_card_visa
3-D Secure in Stripe's test mode needs Stripe.js in a browser; the outcome then arrives by webhook.
API
All endpoints need a JWT (Authorization: Bearer <token> from POST /api/auth/login), except login and the signed webhook route. Tenants only ever see their own cards, charges, leases and payments: another tenant's id answers 404, as if it didn't exist, so ids can't be probed.
New endpoints
| Method | Path | Who | Purpose |
|---|---|---|---|
POST |
/api/cards/setup |
Tenant | Start saving a card; returns setupId and clientSecret for Stripe.js |
POST |
/api/cards |
Tenant | Save the card from a completed setup ({"setupId"}); 201, or 200 if already saved |
GET |
/api/cards |
Tenant | The tenant's cards, with isDefault |
PUT |
/api/cards/{id}/default |
Tenant | Make a card the default |
DELETE |
/api/cards/{id} |
Tenant | Remove a card (detached at Stripe; kept for payment history) |
POST |
/api/rent-charges/{id}/card-payments |
Tenant | Pay a charge with a saved card ({"cardId"}, Idempotency-Key header); 201 for every outcome, 200 for a retry |
GET |
/api/payments/{id} |
Tenant (own), PM | One payment, in the caller's view |
GET |
/api/payments |
Tenant | The tenant's payment history |
GET |
/api/payments?tenantId= |
PM | A tenant's payment history |
POST |
/api/payments/{id}/refunds |
PM | Refund what remains of a card payment ({"reason"}) |
POST |
/api/rent-charges/{id}/void |
PM | Void an unpaid charge the tenant doesn't owe ({"reason"}) |
GET |
/api/payments/config |
Anyone logged in | The processor and Stripe's publishable key, for loading Stripe.js |
POST |
/api/webhooks/stripe |
Stripe | Webhooks, authenticated by their signature |
POST |
/api/dev/card-setups/{id}/confirm, /api/dev/payments/{id}/authenticate |
Tenant | Dev only, fake processor: stand in for Stripe.js |
Existing endpoints changed too: charges show OVERDUE when unpaid past their due date, ?status= filters correctly, recording a manual payment requires exactly the outstanding amount, and responses no longer show tenants the PM's notes.
Tenant and PM views of a payment
Tenants see the card's brand and last 4, and a generic reason when a payment fails ("Your card was declined. Try another card."; reasons such as stolen_card are never shown to the payer). Property managers see Stripe's actual code and message, notes, who recorded a payment, and each refund with its reason, but only the card's brand. Neither sees Stripe's ids.
Errors
Every error has the same shape, with a stable, machine-readable code:
{ "status": 409, "error": "Conflict", "code": "CHARGE_NOT_PAYABLE",
"message": "Rent charge 1 can't be paid: it is already paid", "timestamp": "…" }
401 means no valid login (log in again), 403 a login without the right role. The codes, general and specific, are listed with what they mean in ErrorCode.
Data model and payment lifecycle
Migrations V4–V7 add five tables and extend two (ERD and every column):
| Table | Holds |
|---|---|
processor_customers |
Each tenant's Stripe customer (cus_…) |
processor_cards |
Saved cards: Stripe's reference (pm_…), brand, last 4, and a fingerprint to reject duplicates. Never a card number |
tenant_default_cards |
Each tenant's default card; a composite foreign key keeps it the tenant's own |
payment_refunds |
One row per refund: amount, Stripe's reference, and for refunds through our API the PM and reason |
processor_events |
Webhooks received, deduplicated by event id; no payload (it holds personal data) |
payment_status_history |
Every payment status change, with what caused it |
payments (extended) |
Card and manual payments in one table: status, processor, card, idempotency key, failure details, version |
rent_charges (extended) |
A status for every state the money can be in, and void details |
Provider-neutral names (processor, processor_reference) keep Stripe behind one interface: switching providers means a new adapter, not renamed columns.
Payment statuses
A card payment starts PENDING (saved before Stripe is called, so a crash leaves something to reconcile) and moves through Stripe's outcomes. Manual payments are SUCCEEDED from the start.
stateDiagram-v2
direction LR
state "In flight" as InFlight {
[*] --> PENDING
PENDING --> REQUIRES_ACTION : bank requires 3-D Secure
PENDING --> PROCESSING
REQUIRES_ACTION --> PROCESSING : tenant confirms
}
[*] --> InFlight
InFlight --> SUCCEEDED
InFlight --> FAILED
InFlight --> CANCELED : not from PROCESSING
FAILED --> [*]
CANCELED --> [*]
stateDiagram-v2
direction LR
[*] --> SUCCEEDED
SUCCEEDED --> PARTIALLY_REFUNDED : partial refund
SUCCEEDED --> REFUNDED : full refund
PARTIALLY_REFUNDED --> REFUNDED : remainder refunded
SUCCEEDED --> DISPUTED : chargeback opened
PARTIALLY_REFUNDED --> DISPUTED : chargeback opened
DISPUTED --> DISPUTE_LOST : dispute lost
note right of DISPUTED : Won - back to its previous status
REFUNDED --> [*]
DISPUTE_LOST --> [*]
The allowed transitions are one exhaustive when in code (PaymentStatus.canTransitionTo); a change it doesn't allow is never applied.
Rent charge statuses
A charge's status is derived from its payments after every change, and every state the money can be in is a status of its own. Only PENDING charges can be paid. OVERDUE is shown, never stored: a PENDING charge past its due date.
stateDiagram-v2
direction LR
[*] --> PENDING
PENDING --> PROCESSING : card payment started
PROCESSING --> PENDING : payment failed or canceled
PENDING --> PAID : paid (manual or instant card success)
PROCESSING --> PAID : payment succeeded
PAID --> PARTIALLY_REFUNDED : partial refund
PAID --> REFUNDED : full refund
PARTIALLY_REFUNDED --> REFUNDED : rest refunded
PAID --> DISPUTED : dispute opened
PARTIALLY_REFUNDED --> DISPUTED : dispute opened
DISPUTED --> PAID : won
DISPUTED --> PARTIALLY_REFUNDED : won, after a partial refund
DISPUTED --> PENDING : lost
PENDING --> VOID : PM voids an unpaid charge
REFUNDED --> [*]
VOID --> [*]
A refund doesn't make rent owed again: refunding is the PM's decision to give money back. A lost dispute does, because the bank took the money back.
How a status stays correct
- One change at a time per charge: every payment change locks the rent charge row (
SELECT … FOR UPDATE), so a card payment and a check recorded at the same moment can't both pay the rent. No lock is ever held during a Stripe call. - Stripe is the source of truth: the pay response, webhooks and the reconciler all fetch the charge's current state from Stripe and apply it through one function, so late or repeated webhooks are harmless.
- Webhooks are acknowledged in milliseconds and processed by the worker through SQS, with a dead-letter queue after five failed attempts.
- The reconciler runs every five minutes: payments whose Stripe answer was lost are retried with the same idempotency key, lost webhooks are made up for, and 3-D Secure abandoned for an hour is canceled so the charge can be paid again. All thresholds are settings (
payments.reconciler.*).
Assumptions and tradeoffs
- Full payments only. A card payment charges the whole outstanding balance, and a manual payment must equal it; overpayments and partial payments are rejected with their own error codes. The starter code marked a charge paid whatever the amount; that was a bug, not partial-payment support.
- Full refunds only through the API (what remains of a payment). Partial refunds made in Stripe's dashboard are recorded from their webhooks.
- Refunds Stripe reports as pending are counted as made, which keeps the PM's reason. One that fails later isn't followed yet (future work).
- USD only, converted to cents exactly; an amount with a third decimal place is rejected rather than rounded.
- Cards are for the tenant who is present (
usage=on_session); autopay would need the tenant's consent and re-saved cards. - No surcharge: tenants pay exactly the charge; card fees are absorbed.
- Duplicate cards are rejected by Stripe's card fingerprint; a removed card can be added back.
- Removing a card while a payment with it is in progress is refused (
409) rather than finishing the payment first. - Webhooks are thin: we store the event id and the object it concerns, not the payload, and fetch current state from Stripe. That costs one Stripe call per event but keeps personal data out of our database and makes event order irrelevant.
- The fake processor is the default, so reviewers and CI need no Stripe account. It speaks Stripe's test card names and has its own signed webhooks for tests.
- Integration tests run on H2 in MySQL mode, as the starter's did. The charge lock was also checked by hand on MySQL: 11 simultaneous payment pairs, exactly one payment each (step 10).
- The app runs in UTC; business dates such as "overdue" use
app.timezone(defaultAmerica/Los_Angeles).
Production and scale
What I'd do next, roughly in order of value (details):
- Rate limits against card testing (fraudsters check stolen cards through card-saving endpoints): per tenant on card setups, per IP at the gateway. Stripe Radar screens setups meanwhile.
- One scheduler across instances (e.g. ShedLock): today each worker instance queues reconciliation, which is safe but duplicates Stripe calls.
- Auth hardening: short-lived access tokens with refresh and revocation; property managers scoped to their own properties.
- Refunds that fail after being accepted: a refund status, Stripe's
refund.failedevents, and a way back fromREFUNDED. - Autopay and scheduled payments, with explicit consent and off-session card setups.
- Partial payments and partial refunds through the API; the model already represents them.
- An append-only ledger of money movements, with balances derived from entries.
- A replay tool for the dead-letter queue, and alerts on it.
- Multi-currency, per-property timezones, late fees and reminders for overdue rent, tenant data export and erasure.
For scale: contention is per rent charge, never global, so tenants paying at once don't wait on each other; no lock is held during a network call; webhooks are cheap to accept and processed by a horizontally scalable worker; the reconciler works in bounded batches within Stripe's rate limits; and every Stripe write carries an idempotency key derived from our own records, so any retry is safe.
How I used AI
I built this with Claude Code as a pair, and kept its notes: docs/ai/ records each stage, including where I pushed back and where it was wrong.
How we worked. Claude read the starter code first and proposed a plan; I turned it into a design document and had it write a detailed design for every step before any code. We settled each open question one at a time, with Claude recommending an option and me deciding. It wrote the code; I reviewed it piece by piece, asked about anything I didn't understand (I was new to Kotlin, jOOQ and H2), and every commit went in only after my approval.
Where I changed the design. Some of the decisions that came from my review rather than the AI's first proposal:
- A provider-neutral processor interface, after I pointed out its first layout would get messy if we ever switched payment providers.
- Storing only card references, brand and last 4 (no expiry), treated as personal data.
- Thin webhooks with no stored payload, after I asked why we needed JSON columns at all.
- Full payments everywhere, once I saw the starter's "partial payments" were a bug.
- "Model every state the money can be in, or the system isn't internally consistent": refunds became charge statuses instead of reopening the rent, which also produced the
PROCESSINGandDISPUTE_LOSTstates. - Compile-time guarantees over conventions: new payments, refunds and the derived
OVERDUEgot types of their own. - Rejecting duplicate cards by fingerprint, where the AI had called duplicates cosmetic.
- Using 401 and 403 correctly, and tunable reconciliation thresholds.
What testing by hand found. Calling the running API myself turned up bugs the test suite couldn't see: the app ignored its own JSON settings (dates as arrays, unknown fields rejected), every kind of error came back as a bare 403, and the LocalStack setup script wasn't executable.
How I checked the AI's work. Every concurrency test was made to fail by removing the guard it tests, to prove it tests something. Some mistakes I caught in review: it started coding before the design was reviewed, proposed storing refund amounts in two places, and recommended keeping an old convention over a compile-time guarantee. It caught others itself: a bug that would have recorded a false "dispute won", tests that clashed in the shared test database, and an overstated claim in one step's design. It also found latent bugs in the starter setup: jOOQ queries ran outside Spring's transactions (so neither rollbacks nor row locks worked), and stored timestamps were read back five hours off on a machine outside UTC.
Reference
Authentication
curl -X POST http://localhost:8080/api/auth/login -H 'Content-Type: application/json' \
-d '{"email": "admin@greenfieldproperties.com", "password": "password"}'
{ "token": "eyJhbGciOiJIUzI1NiJ9...", "userId": 1, "email": "admin@greenfieldproperties.com", "role": "PROPERTY_MANAGER" }
| Password | Role | |
|---|---|---|
| admin@greenfieldproperties.com | password | PROPERTY_MANAGER |
| alice.johnson@email.com | password | TENANT |
| bob.smith@email.com | password | TENANT |
| carol.williams@email.com | password | TENANT |
Property managers manage properties, units, tenants, leases and payments. Tenants read their own leases, charges and payments, and manage their own cards.
Pagination
List endpoints are cursor-based: pass the last item's id as startAfterId, and limit (default 20, at most 100). Responses are {"content": [...], "hasMore": true}.
Existing endpoints
- Auth:
POST /api/auth/login - Tenants:
GET /api/tenants(PM),GET /api/tenants/{id},POST /api/tenants(PM),PUT /api/tenants/{id}(PM) - Properties and units (PM):
GET /api/properties,GET /api/properties/{id},POST /api/properties,GET /api/properties/{id}/units,POST /api/properties/{id}/units - Leases:
GET /api/leases(tenants: their own),GET /api/leases/{id},GET /api/leases?tenantId=(PM),POST /api/leases(PM) - Rent charges:
GET /api/rent-charges/{id},GET /api/rent-charges?leaseId=(optionally&status=, includingOVERDUE),POST /api/rent-charges/generate(PM; queued for the worker) - Manual payments (PM):
POST /api/payments,GET /api/payments?rentChargeId=
Architecture
src/main/kotlin/com/ender/takehome/
├── auth/ # Login
├── cards/ # Saved cards
├── leasing/ # Leases
├── ledger/ # Rent charges, payments, refunds, settlement and the charge lock
├── payments/ # Card payments, payment reads, refunds, ChargeSync
│ ├── processor/ # PaymentProcessor interface; stripe/ and fake/ adapters
│ ├── webhooks/ # Webhook route, event storage, the worker job
│ └── reconciliation/# The reconciler, its job and schedule
├── property/ # Properties and units
├── tenant/ # Tenants
├── model/ # Domain models
├── dto/ # Request and response types
├── config/ # Security, JWT, jOOQ, clock, AWS
├── service/ # S3 file storage
├── worker/ # SQS background worker
└── exception/ # Error codes and handling
Code conventions
- One package per domain, layered
*Api(HTTP, auth checks) →*Module(business logic, transactions) →*DataAccess(jOOQ). Domains call each other through their*Module;paymentsdepends onledger, never the reverse. - New rows that must start in a fixed state have their own types:
NewPayment,NewRefundandNewCardhave no id or status, so the compiler decides the starting state. Older entities useid = 0for "not yet saved". - jOOQ code is generated from the Flyway migrations at build time. Schema changes go in a new migration, which must run on MySQL 8 and on H2 in MySQL mode.
- Invariants live in the database where possible (unique and check constraints), and the charge lock serializes changes to a charge's payments.
- The Stripe SDK is imported only in
payments/processor/stripe/.
Infrastructure and seed data
MySQL 8 (port 3306) and LocalStack (port 4566: S3, SQS) run in Docker. The first migration seeds 1 property manager, 2 properties, 4 units, 3 tenants, 2 active leases, rent charges with manual payments, and 4 user accounts.