# Build a resident app

Sign residents in with OAuth 2.0 and PKCE, show the accounts and invoices each one may see through the Consumer API, and open an M-Pesa payment.


## What you will build

A web or mobile app where a resident signs in with their own account, sees the service accounts linked to them, reads their invoices and pays one. The app never holds an API key: it gets an access token on the resident's behalf through the Authorization Code flow with PKCE (`S256`) and calls the Consumer API (`$CONSUMER_API`) with that token. Every response contains only what belongs to that resident.

The `examples/resident-pkce` sample covers steps 1 to 4 in a static HTML page with no build step.

## Prerequisites

- A sandbox and a resident user with at least one linked service account (the `account.linked` event marks the moment a resident gains access to an account).
- An OAuth client registered by the server operator under `security.oauth.clients`, with `kind` set to `mobile` (or `desktop`) and your app's `redirect_uris`:

```yaml
security:
  oauth:
    clients:
      - id: resident-app
        name: Resident app
        kind: mobile
        redirect_uris:
          - http://localhost:3000/callback
```

The token endpoint accepts public clients only (`token_endpoint_auth_methods_supported` is `none`), so there is no client secret: PKCE is what proves that whoever redeems the code is whoever asked for it.

## 1. Read the authorization server's settings

```bash
curl -sS "https://api.gota.umbeluzi.com/.well-known/oauth-authorization-server"
```

✓ Checkpoint: the response carries `authorization_endpoint`, `token_endpoint` and `"code_challenge_methods_supported": ["S256"]`. Take the URLs from here rather than hard-coding them.

## 2. Send the resident to the sign-in screen

Generate a random `code_verifier`, keep it in the browser session, and send only its hash in the authorization request. The helpers come from `examples/resident-pkce/pkce.js`.

```javascript
import { generateCodeVerifier, generateCodeChallenge, buildAuthorizeURL } from "./pkce.js";

const verifier = generateCodeVerifier();
sessionStorage.setItem("pkce_verifier", verifier);
const state = crypto.randomUUID();
sessionStorage.setItem("pkce_state", state);

window.location.assign(buildAuthorizeURL({
  authorizationEndpoint: discovery.authorization_endpoint,
  clientId: "resident-app",
  redirectUri: "http://localhost:3000/callback",
  scope: "openid profile offline_access",
  state,
  codeChallenge: await generateCodeChallenge(verifier),
}));
```

✓ Checkpoint: after signing in, the browser comes back to `redirect_uri` with `code` and `state` in the query string; check that `state` matches the value you stored.

## 3. Exchange the code for tokens

```bash
curl -sS -X POST "https://api.gota.umbeluzi.com/oauth/token" \
  -d grant_type=authorization_code \
  -d client_id=resident-app \
  -d redirect_uri=http://localhost:3000/callback \
  -d code="$AUTH_CODE" \
  -d code_verifier="$CODE_VERIFIER"
```

✓ Checkpoint: the response holds `access_token`, `"token_type": "Bearer"`, `expires_in` (900 seconds by default, which the operator can change with `security.token_ttl`), `refresh_token`, `id_token` and a `user` object. When access expires, ask for a new token with `grant_type=refresh_token`; every refresh returns a fresh `refresh_token`, and the old one then fails with `invalid_grant`.

## 4. Show the resident's accounts

```bash
curl -sS "$CONSUMER_API/accounts" \
  -H "Authorization: Bearer $CONSUMER_ACCESS_TOKEN"
```

Response, abridged:

```json
{
  "data": [
    {
      "id": "act_3eQrF3JmTj2ZXpkFlbdO36UPXGP",
      "tenant_id": "ten_3HclVhrn01Vsbj8CEBWAUk6h4MV",
      "customer_id": "cus_3Byj2A4oNoD4aVDMGLeWCWY5CWP",
      "property_id": "prp_35XwcW0AgJucy3jX5j2mk9J1XgP",
      "property_address": "Rua da Resistência 1187, Bairro Central",
      "account_number": "CTA-000044",
      "billing_entity_id": "ten_3HclVhrn01Vsbj8CEBWAUk6h4MV",
      "status": "active",
      "permissions": ["account.read", "invoice.read", "payment.create", "reading.create"]
    }
  ],
  "has_more": false
}
```

✓ Checkpoint: only accounts with an active link to this resident appear, across every utility they deal with. Let `permissions` decide which buttons to show: without `payment.create` do not offer payment, and without `reading.create` hide the meter-reading form.

## 5. List invoices and open a payment

```bash
curl -sS "$CONSUMER_API/invoices?account_id=act_3eQrF3JmTj2ZXpkFlbdO36UPXGP" \
  -H "Authorization: Bearer $CONSUMER_ACCESS_TOKEN"

curl -sS -X POST "$CONSUMER_API/payment-sessions" \
  -H "Authorization: Bearer $CONSUMER_ACCESS_TOKEN" \
  -H "Idempotency-Key: 6f1d2c9a-3b47-4e1f-9a0c-5d8e7b2a4c61" \
  -H "Content-Type: application/json" \
  -d '{"invoice_id":"inv_3z9cS8ItYBqz0D66bvqNC7QSn8E","method":"mpesa","phone":"+258841234567"}'
```

✓ Checkpoint: the session comes back with an `id` starting with `pss_`, `"status": "pending"`, an `amount` equal to the outstanding balance, and a `next_action`. For `mpesa`, `next_action.type` is `mobile_money_approval` and `instructions` tells the resident what to approve on their phone; display that text as it arrives. The server works out the amount from the invoice, so the app never sends it.

## Test it

Poll `GET $CONSUMER_API/payment-sessions/pss_3SUDQUDOqwxJDioVEQHBzy13wYD` until `status` changes. The sandbox has no real approval, so `POST $CONSUMER_API/payment-sessions/pss_3SUDQUDOqwxJDioVEQHBzy13wYD/sandbox/confirm` plays the provider: it records the payment and receipt and returns the session as `confirmed`. On the utility's side, `payment.received` arrives and, when the balance has reached zero, `invoice.paid` follows.

An invoice with nothing left to pay is refused with `invoice.no_balance`, and while the utility's payments are not active the answer is `403` with `capability.inactive`.

## Next steps

- [Authentication: API keys, OAuth and the device grant](/docs/getting-started/authentication)
- [Receive payments and confirm them by webhook](/docs/guides/receive-payments)
- [Pagination with limit, after and next_cursor](/docs/getting-started/pagination)
- [Full Consumer API reference](/docs/api/consumer)

