---
name: mikrodius
description: "Build or change an app that uses the Mikrodius Cloud RADIUS API (mikrodius.com/api/v1): ISP, RT/RW net or hotspot billing, plugins for existing billing software, customer portals and chat bots, PPPoE and hotspot subscriber management, renewals on payment, vouchers, router (NAS) onboarding, MikroTik RADIUS without running a RADIUS server, Connect with Mikrodius (OAuth) for apps used by many operators, and Mikrodius webhooks. Use it whenever code calls the Mikrodius API or handles its webhooks."
---

# Mikrodius API

Mikrodius authenticates PPPoE and hotspot logins for ISPs, RT/RW nets and hotspot operators. Your billing app keeps the customers and payments and calls this API to make the network enforce them: one subscriber per customer, a renew per payment, and webhooks for what happened on the network.

- Version: 1.0.0-draft.11
- Base URL: https://mikrodius.com/api/v1
- Authentication: apiKey — An API key sent as `Authorization: Bearer mk_live_...`.

## How to use this skill

- Follow the rules below in every change. They are short on purpose; each one prevents a bug that is easy to ship.
- For a new app or a new feature, follow the guide: it says which call to make for each billing event, with code to adapt.
- Before you write a request or read a response, look up the operation in the [reference](https://mikrodius.com/llms-full.txt): exact paths, fields, types, limits and error codes. Do not guess field names.
- Put the API key in `MIKRODIUS_API_KEY` and the webhook secret in `MIKRODIUS_WEBHOOK_SECRET`. Ask the user for them, or tell them where to create them (dashboard, Developers page); never hard-code them.
- To act on a live account from the agent itself (list plans, look up a subscriber) instead of writing code, use the MCP server at https://mikrodius.com/api/v1/mcp with the same API key.

## Rules for building on this API

Follow these whenever you write code that calls Mikrodius. Each one prevents a real bug.

1. **Keep the API key on the server.** Read it from an environment variable
   (`MIKRODIUS_API_KEY`) and call the API only from backend code. Never put it in browser,
   mobile or client-side code, and never commit it.
2. **Link customers with `external_id`.** Create every subscriber with your own immutable
   customer ID as `external_id`, then address them as `external_id:<your id>` (URL-encoded)
   in every path. You do not need to store Mikrodius `sub_` IDs.
3. **Payment received means `renewSubscriber`, always with a `reference`.** Pass your
   payment or invoice ID as `reference`, so a retried call can never extend twice. Do not
   compute `expires_at` yourself and `PATCH` it for a payment.
4. **Let expiry do the cutting off.** A subscriber whose `expires_at` has passed is refused (or
   put on the isolation plan) automatically, and live sessions are ended. You do not need a
   cron job that suspends unpaid customers. Use `suspendSubscriber` only for reasons other
   than time running out (abuse, a manual hold).
5. **Units:** speed in **kbps** (20 Mbps = `20000`), data in **bytes**, time in **seconds**.
   For every limit, `null` means unlimited and `0` never does.
6. **Every write is safe to retry.** When a retried create returns `409` (`username_taken`,
   `external_id_taken`), fetch the subscriber by `external_id:<your id>`: if it is there, the
   earlier attempt worked, so carry on. Never invent a new username to get past a `409`.
7. **Switch on the error `code`**, never on `title` or `detail`, and log `request_id`. On
   `429 rate_limited` wait `Retry-After` seconds; retry `5xx` with backoff.
8. **Verify every webhook** (`Mikrodius-Signature`, HMAC-SHA256 over `<t>.<raw body>`),
   answer `2xx` within 10 seconds, do the work afterwards, de-duplicate on the event `id`
   in the verified body, and ignore event types you do not know.
9. **Use webhooks instead of polling** for expiry, quota, first login and NAS status, and
   back them with a reconcile job on `listSubscribers?updated_since=`. That job alone is
   enough for an app that has no public URL.
10. **Tolerate additions:** ignore unknown response fields and unknown enum values; they ship
    without a version change.
11. **Never ask for or store NAS credentials.** Mikrodius generates the tunnel keys and the
    RADIUS secret. Onboard a router by creating the NAS and showing the operator its
    `install_link.command` to paste into the RouterOS terminal.
12. **Only call operations that exist in this reference.** There are no `metadata` fields and
    no `Idempotency-Key` header; keep your own data in your database and link it with
    `external_id`.

## Guide: building a billing app on Mikrodius

This is the recommended way to build an ISP, RT/RW net or hotspot billing app on top of
Mikrodius. It is written for developers and for coding agents: follow it step by step and
you end up with an app that is correct under retries, late payments and flaky networks.

### Who does what

| Your billing app | Mikrodius |
|---|---|
| Customers, addresses, contracts | PPPoE and hotspot logins (RADIUS) |
| Products and prices | Plans: speed, quota, time limits, device limit |
| Invoices, payments, payment gateway | Expiry, suspension and quotas, enforced on the router |
| Reminders (WhatsApp, email, SMS) | Webhooks telling you what happened |
| Customer portal | Usage counters and live sessions to show in it |

Your app decides **whether a customer has paid**. Mikrodius makes the network enforce that
decision. Mikrodius stores no customer data beyond the login.

### What you can build

Anything that needs "this customer may be online, at this speed, until this date" on a
MikroTik network, without running RADIUS yourself:

- **A billing app** for an ISP or RT/RW net: customers, invoices, payment gateway, reminders.
  This guide walks through it.
- **A plugin for billing software that already exists**, so its operators get cloud RADIUS
  without changing tools. Map its customers, packages and payments to subscribers, plans and
  `renewSubscriber`.
- **A product for many operators** (SaaS, a mobile app): each operator connects their own
  Mikrodius account with one click. See "Apps used by many operators".
- **A customer portal or a WhatsApp/Telegram bot**: status, usage, "pay now", "restart my
  connection" (`getSubscriber`, `getSubscriberUsage`, `disconnectSubscriber`).
- **A hotspot voucher seller**: a kiosk, a reseller app or a bot that calls `generateVouchers`
  when a voucher is paid for.
- **Monitoring and reports**: who is online (`listSessions`, `streamSessions`), which router
  is down (`nas.offline`), usage and estimated sales, with a `read_only` key.
- **Remote CPE management** over TR-069: change a customer's Wi-Fi name and password from
  your app (`createCpeTask`).

You pay only for subscribers that actually get online (see the pricing document), so building
and testing costs nothing.

### Architecture

```
customer / admin UI ──> your backend ──(HTTPS, API key)──> https://mikrodius.com/api/v1
                           ^
                           └──(signed webhooks)── Mikrodius
```

- One small **API client module** in your backend wraps every call (auth header, JSON, errors,
  retries). Nothing else talks to Mikrodius directly.
- One **webhook route** receives events, verifies them, stores them and processes them in the
  background.
- Your database stays the source of truth for customers and payments. Mikrodius is the
  source of truth for "can this login get online right now" (`state`) and for usage.

### What to store in your database

| Your table | Add |
|---|---|
| settings / tenant | `mikrodius_workspace_id`; the API key and webhook secret come from environment variables or a secrets store |
| products | `mikrodius_plan_id`. Also give each plan your product ID as `external_id`: plan paths, `plan_id` in request bodies (create, update, `renew`, vouchers) and the `plan_id` filters then take `external_id:<your id>`, and you can find your plans again in `listPlans` without tags in their names |
| customers | `mikrodius_username` (the PPPoE or hotspot login); your own customer ID doubles as the `external_id` |
| payments | nothing new: the payment ID is the `reference` you pass to `renew` |
| webhook_events | `event_id` (unique), `type`, `received_at`, `processed_at`: for de-duplication |
| routers (optional) | `mikrodius_nas_id`, to show online/offline per router |

### One-time setup

1. **API key.** Create a `read_write` key in the dashboard (Developers → API keys). For a
   reporting-only tool, use a `read_only` key: it cannot write and never sees passwords.
   Check it with `getMe` (`GET /me`).
2. **Workspace.** A workspace is one isolated network (its own NAS, plans and subscribers).
   Most operators need one. Create it with `createWorkspace` (`POST /workspaces`) or pick an
   existing one from `listWorkspaces`, and store its `id`. Set `time_zone` (default
   `Asia/Jakarta`); renewals count months in it.
3. **Plans.** Create one plan per product with `createPlan`
   (`POST /workspaces/{workspace_id}/plans`) and store the returned `id` on the product.
   Example body for "Home 20 Mbps":

   ```json
   { "name": "Home 20 Mbps", "bandwidth": { "download_kbps": 20000, "upload_kbps": 5000 }, "max_sessions": 1 }
   ```

   A quota product adds `data_limit_bytes`; a voucher product adds `validity_seconds`
   (for example `86400` for "1 day from first login").

   Optional plan features, all in the same body:
   - `fup`: slow heavy users down instead of cutting them off. Steps start after
     `after_bytes` (counted as `counts`: `total` or `download`, reset `with_usage` or `daily`)
     and each caps the speed (`bandwidth`) or switches to another plan (`plan_id`):
     `"fup": { "counts": "total", "resets": "with_usage", "steps": [{ "after_bytes": 100000000000, "bandwidth": { "download_kbps": 5000, "upload_kbps": 2000 } }] }`.
     Every step must be below `data_limit_bytes`.
   - `speed_windows`: other speeds at set times, e.g. a night boost
     `[{ "start": "00:00", "end": "06:00", "days": null, "download_kbps": 40000, "upload_kbps": 10000 }]`,
     in the workspace `time_zone`.
   - `bandwidth.priority` (1 highest to 8) and `bandwidth.guaranteed` (MikroTik limit-at).
   - `price`, in the smallest unit of the workspace `currency`. Mikrodius only uses it for the
     estimated sales (`listSales`, `getSalesSummary`); your app still owns invoicing.
4. **Isolation plan (recommended).** Instead of a hard reject, unpaid customers can be let in
   on a slow plan that your router redirects to a payment page ("isolir"). Create a plan with a
   low speed and a reply attribute, then set it on the workspace with `updateWorkspace`
   (`PATCH /workspaces/{workspace_id}`):

   ```json
   { "name": "Isolir", "bandwidth": { "download_kbps": 256, "upload_kbps": 256 },
     "reply_attributes": [{ "name": "Mikrotik-Address-List", "value": "isolir" }] }
   ```

   ```json
   { "isolation_plan_id": "plan_..." }
   ```

   Expired, suspended and over-quota subscribers then get `state: "isolated"` and land on this
   plan instead of being refused.
5. **Webhook endpoint.** Register your HTTPS route with `createWebhookEndpoint`
   (`POST /webhook-endpoints`). The response contains the signing secret (`whsec_...`) **once**;
   store it as `MIKRODIUS_WEBHOOK_SECRET`. Send a test delivery with `testWebhookEndpoint`.
6. **Routers (NAS).** For each router, call `createNas`
   (`POST /workspaces/{workspace_id}/nas`) with a `name` and `connection` (`wireguard` for
   RouterOS 7, recommended; `l2tp` for routers still on RouterOS 6, or `sstp` when L2TP keeps
   disconnecting or won't connect, for example behind CGNAT). A RouterOS 6 NAS can switch
   between `l2tp` and `sstp` with `updateNas`; run a new install link on the router afterwards. Show the operator the returned `install_link.command`
   with a copy button and the instruction "paste this into the router terminal". The link
   works for 24 hours and once. For a new link later, call `createNasInstallLink`. The router
   comes online by itself; you receive `nas.online`. Never build a form for RADIUS secrets or
   tunnel keys. A workspace has 25 free NAS (`included_nas`); a NAS added while all of
   them are taken costs 30 credits a day with WireGuard or 125 with L2TP or SSTP, prepaid
   30 days at a time (900 or 3,750), charged when it is added (`Nas.billing` shows its
   state). Removing a billed NAS, or a free one so a billed NAS takes its place, refunds the
   unused whole days. To move a NAS to or from WireGuard, add the new one and remove the old one.

### Billing lifecycle: which call for which event

| Event in your app | Call |
|---|---|
| New customer is activated (first payment) | `createSubscriber`, then `renewSubscriber` with the payment as `reference` |
| Payment received | `renewSubscriber` with `period` and `reference` |
| Customer upgrades or downgrades now | `updateSubscriber` with `plan_id` (applied to the live session) |
| Customer changes plan at the next payment | `renewSubscriber` with `plan_id` |
| Invoice overdue | nothing: the subscriber expires at `expires_at` |
| Manual hold, abuse, fraud | `suspendSubscriber` with a `reason`; undo with `activateSubscriber` |
| Customer buys extra quota | `addSubscriberData` with `bytes` and the payment as `reference` |
| New quota cycle without a payment | `resetSubscriberUsage` |
| Password change or reset | `updateSubscriber` with `password` |
| "My internet is stuck" / force re-login | `disconnectSubscriber` |
| Customer cancels for good | `deleteSubscriber` |
| Customer portal: status and usage | `getSubscriber` (`state`, `online`, `expires_at`, `usage`) and `getSubscriberUsage` for history |
| Sell hotspot vouchers | `generateVouchers` with a plan that has `validity_seconds` |

### Activating a new customer

Create the subscriber already expired, then renew it with the first payment. The customer
cannot get online before paying, and the whole flow is safe to retry:

```ts
const ref = `external_id:${encodeURIComponent(customer.id)}`;
try {
  await mk.post(`/workspaces/${ws}/subscribers`, {
    username: customer.pppoeUsername,
    password: customer.pppoePassword,      // omit to let Mikrodius generate one
    external_id: customer.id,
    plan_id: product.mikrodiusPlanId,
    service_type: 'pppoe',                 // 'hotspot' or 'any'
    expires_at: new Date().toISOString(),  // no access until the first renew
  });
} catch (e) {
  if (e.status !== 409) throw e;
  // A 409 on a retry means an earlier attempt already created it. Confirm it is ours; if no
  // subscriber has our external_id, the username belongs to someone else.
  const existing = await mk.get(`/workspaces/${ws}/subscribers/${ref}`).catch(() => null);
  if (!existing) throw e;
}
await mk.post(`/workspaces/${ws}/subscribers/${ref}/renew`, {
  period: { unit: 'month', count: 1 },
  from: 'now',
  reference: payment.id,
});
```

The same in PHP (Laravel), with the client from "API client" below:

```php
$mk = app(MikrodiusClient::class);
$ref = MikrodiusClient::ref($customer->id);
try {
    $mk->post("/workspaces/{$ws}/subscribers", [
        'username' => $customer->pppoe_username,
        'password' => $customer->pppoe_password,       // omit to let Mikrodius generate one
        'external_id' => (string) $customer->id,
        'plan_id' => $product->mikrodius_plan_id,
        'service_type' => 'pppoe',                      // 'hotspot' or 'any'
        'expires_at' => now()->toIso8601ZuluString(),   // no access until the first renew
    ]);
} catch (MikrodiusException $e) {
    if ($e->status !== 409) throw $e;
    // Created by an earlier attempt, or the username belongs to someone else.
    try { $mk->get("/workspaces/{$ws}/subscribers/{$ref}"); }
    catch (MikrodiusException) { throw $e; }
}
$mk->post("/workspaces/{$ws}/subscribers/{$ref}/renew", [
    'period' => ['unit' => 'month', 'count' => 1],
    'from' => 'now',
    'reference' => (string) $payment->id,
]);
```

If the username belongs to another customer, ask the admin for a different one; do not add
random suffixes silently.

### Recording a payment

```ts
const sub = await mk.get(`/workspaces/${ws}/subscribers/${ref}`);
const expired = sub.expires_at !== null && new Date(sub.expires_at) < new Date();
await mk.post(`/workspaces/${ws}/subscribers/${ref}/renew`, {
  period: { unit: 'month', count: payment.months },
  // Paid on time: extend from the current expiry, so no days are lost.
  // Paid late: start the new period today instead of back-dating it.
  from: expired ? 'now' : 'current_expiry',
  reference: payment.id,
});
```

```php
$sub = $mk->get("/workspaces/{$ws}/subscribers/{$ref}");
$expired = $sub['expires_at'] !== null && now()->greaterThan($sub['expires_at']);
$mk->post("/workspaces/{$ws}/subscribers/{$ref}/renew", [
    'period' => ['unit' => 'month', 'count' => $payment->months],
    'from' => $expired ? 'now' : 'current_expiry',
    'reference' => (string) $payment->id,
]);
```

`renew` also reactivates a suspended subscriber and resets the usage counters, and the change
reaches the router immediately. If your business bills on a fixed day of the month, always use
`current_expiry` instead.

For postpaid billing with a grace period, renew so that `expires_at` lands on the due date
plus the grace days. Setting `expires_at` directly with `updateSubscriber` is for manual
corrections by an admin, not for payments.

### API client

Write this once. Every other part of the app goes through it.

```ts
// mikrodius.ts (server only)
const BASE = 'https://mikrodius.com/api/v1';
const KEY = process.env.MIKRODIUS_API_KEY!;

export class MikrodiusError extends Error {
  constructor(public status: number, public code: string, public requestId: string,
              public errors: { field: string; code: string; message: string }[] = [], detail = '') {
    super(`${code}: ${detail} (request_id ${requestId})`);
  }
}

async function call<T>(method: string, path: string, body?: unknown, attempt = 0): Promise<T> {
  const res = await fetch(BASE + path, {
    method,
    headers: { Authorization: `Bearer ${KEY}`, 'Content-Type': 'application/json' },
    body: body === undefined ? undefined : JSON.stringify(body),
  });
  if ((res.status === 429 || res.status >= 500) && attempt < 4) {
    const wait = Number(res.headers.get('Retry-After')) || 2 ** attempt;
    await new Promise((r) => setTimeout(r, wait * 1000));
    return call(method, path, body, attempt + 1); // safe: every write is idempotent
  }
  if (res.status === 204) return undefined as T;
  const json = await res.json();
  if (!res.ok) throw new MikrodiusError(res.status, json.code, json.request_id, json.errors, json.detail);
  return json as T;
}

export const mk = {
  get: <T = any>(p: string) => call<T>('GET', p),
  post: <T = any>(p: string, b: unknown = {}) => call<T>('POST', p, b),
  patch: <T = any>(p: string, b: unknown) => call<T>('PATCH', p, b),
  delete: (p: string) => call<void>('DELETE', p),
};

// Every list endpoint pages with a cursor.
export async function* all<T = any>(path: string) {
  let cursor: string | null = null;
  do {
    const sep = path.includes('?') ? '&' : '?';
    const page: { data: T[]; next_cursor: string | null } =
      await mk.get(`${path}${sep}limit=200${cursor ? `&cursor=${encodeURIComponent(cursor)}` : ''}`);
    yield* page.data;
    cursor = page.next_cursor;
  } while (cursor);
}
```

The same client in PHP (Laravel):

```php
// config/services.php: 'mikrodius' => ['key' => env('MIKRODIUS_API_KEY')],

// app/Services/MikrodiusException.php
class MikrodiusException extends \RuntimeException
{
    // $errorCode is the problem `code` (Exception::$code is taken).
    public function __construct(
        public int $status, public string $errorCode, public string $requestId,
        public array $errors = [], string $detail = '',
    ) {
        parent::__construct("{$errorCode}: {$detail} (request_id {$requestId})");
    }
}

// app/Services/MikrodiusClient.php (server only)
use Illuminate\Support\Facades\Http;

class MikrodiusClient
{
    private const BASE = 'https://mikrodius.com/api/v1';

    public function get(string $path, array $query = []): ?array { return $this->call('GET', $path, $query); }
    public function post(string $path, array $body = []): ?array { return $this->call('POST', $path, $body); }
    public function patch(string $path, array $body): ?array { return $this->call('PATCH', $path, $body); }
    public function delete(string $path): void { $this->call('DELETE', $path); }

    // Address a subscriber by your own customer ID.
    public static function ref(string|int $externalId): string
    {
        return 'external_id:' . rawurlencode((string) $externalId);
    }

    // Every list endpoint pages with a cursor.
    public function all(string $path, array $query = []): \Generator
    {
        $cursor = null;
        do {
            $page = $this->get($path, ['limit' => 200] + ($cursor ? ['cursor' => $cursor] : []) + $query);
            foreach ($page['data'] as $item) yield $item;
            $cursor = $page['next_cursor'];
        } while ($cursor);
    }

    private function call(string $method, string $path, array $data = [], int $attempt = 0): ?array
    {
        $req = Http::withToken(config('services.mikrodius.key'))->acceptJson()->timeout(30);
        $res = in_array($method, ['GET', 'DELETE'], true)
            ? $req->send($method, self::BASE . $path, ['query' => $data])
            : $req->send($method, self::BASE . $path, ['json' => (object) $data]);
        if (($res->status() === 429 || $res->serverError()) && $attempt < 4) {
            sleep((int) $res->header('Retry-After') ?: 2 ** $attempt);
            return $this->call($method, $path, $data, $attempt + 1); // safe: every write is idempotent
        }
        if ($res->status() === 204) return null;
        $json = $res->json() ?? [];
        if ($res->failed()) {
            throw new MikrodiusException($res->status(), $json['code'] ?? 'unknown',
                $json['request_id'] ?? '', $json['errors'] ?? [], $json['detail'] ?? '');
        }
        return $json;
    }
}
```

Without Laravel, write the same class on Guzzle. The shape works in any language: one
function that adds the bearer header, retries `429` and `5xx`, and turns problem details into
an error carrying `code`, `errors` and `request_id`. Add methods only for the operations your
app uses; you do not need a full SDK.

### Handling errors

| `code` | Meaning | What your app should do |
|---|---|---|
| `validation_failed` | A field is wrong; see `errors[].field` | Show the message next to that field |
| `username_taken`, `external_id_taken`, `plan_name_taken` | It already exists | On a retry, fetch and continue; otherwise ask for another value |
| `not_found` | Wrong ID, or outside the key's workspace scope | Re-sync your stored IDs |
| `plan_in_use` | Plan still has subscribers | Move them first, or keep the plan |
| `workspace_not_empty` | Workspace still has data | Delete its contents first |
| `insufficient_access` | The key is `read_only` | Use a `read_write` key for writes |
| `scope_restricted` | A workspace-scoped key tried an account-wide action | Use an unscoped key |
| `insufficient_balance`, `spend_cap_reached`, `workspace_limit_reached` | Account limits (`402`) | Tell the operator to top up, raise the workspace `spend_cap`, or contact support |
| `rate_limited` | Over 20 requests/second | Wait `Retry-After`; batch background jobs |
| `edge_unavailable` | The node that serves this workspace cannot be reached (`424`) | Retry after `Retry-After`. Keep the change in a queue and show it as pending; do not fail the payment |
| `move_in_progress` | The workspace is moving to another node; writes wait (`409`) | Retry in a few minutes; reads keep working |
| `unauthorized`, `account_suspended` | Key revoked or account suspended | Alert the operator; do not retry |
| `internal_error`, `service_unavailable` | Server side | Retry with backoff; report `request_id` if it persists |

### Webhooks

Mikrodius POSTs a JSON `Event` (`id`, `type`, `created_at`, `workspace_id`, `data`) with
three headers: `Mikrodius-Signature`, `Mikrodius-Event-Id` and `Mikrodius-Event-Type`.
Failed deliveries are retried for up to 24 hours, so events can arrive twice and out of order.

The handler must:

1. read the **raw** body (before any JSON parsing),
2. verify the signature and reject a timestamp more than 5 minutes off,
3. insert `event.id` (from the verified body, not the header: only the body is signed) into
   `webhook_events`; if it is already there, answer `200` and stop,
4. answer `2xx` within 10 seconds and do slow work (messages, emails) in a background job,
5. ignore types it does not handle, and use `created_at` to skip an event older than what you
   already applied.

Signature: the header is `t=<unix seconds>,v1=<hex>` and may carry several `v1` values while
a secret is being rotated. Compute `HMAC_SHA256(secret, "<t>.<raw body>")` in hex and accept
if it equals any `v1`, compared in constant time.

```ts
import crypto from 'node:crypto';

export function verifyMikrodius(rawBody: string, header: string, secret: string): boolean {
  const parts = header.split(',').map((p) => p.trim().split('='));
  const t = parts.find(([k]) => k === 't')?.[1];
  const sigs = parts.filter(([k]) => k === 'v1').map(([, v]) => v);
  if (!t || Math.abs(Date.now() / 1000 - Number(t)) > 300) return false;
  const expected = crypto.createHmac('sha256', secret).update(`${t}.${rawBody}`).digest('hex');
  return sigs.some((s) => s.length === expected.length &&
    crypto.timingSafeEqual(Buffer.from(s), Buffer.from(expected)));
}
```

```php
function verify_mikrodius(string $rawBody, string $header, string $secret): bool {
    $t = null; $sigs = [];
    foreach (explode(',', $header) as $part) {
        [$k, $v] = array_pad(explode('=', trim($part), 2), 2, '');
        if ($k === 't') $t = $v;
        if ($k === 'v1') $sigs[] = $v;
    }
    if ($t === null || abs(time() - (int) $t) > 300) return false;
    $expected = hash_hmac('sha256', $t . '.' . $rawBody, $secret);
    foreach ($sigs as $s) if (hash_equals($expected, $s)) return true;
    return false;
}
// $rawBody = file_get_contents('php://input'); in Laravel: $request->getContent()
```

```python
import hmac, hashlib, time

def verify_mikrodius(raw_body: bytes, header: str, secret: str) -> bool:
    items = [p.strip().split("=", 1) for p in header.split(",")]
    t = next((v for k, v in items if k == "t"), None)
    sigs = [v for k, v in items if k == "v1"]
    if t is None or abs(time.time() - int(t)) > 300:
        return False
    expected = hmac.new(secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256).hexdigest()
    return any(hmac.compare_digest(expected, s) for s in sigs)
```

Useful events for a billing app:

| Event | Typical reaction |
|---|---|
| `subscriber.expired` | Send "your package has ended, pay here" with a payment link |
| `subscriber.limit_reached` | Offer a top-up or the next quota package |
| `subscriber.fup_reached` | Tell the customer they were slowed down; offer an add-on or a bigger plan |
| `subscriber.first_login` | Mark the installation as done; start the warranty or contract |
| `subscriber.updated` | Keep your copy of status and expiry in sync (includes the `renew` `reference`) |
| `session.started` / `session.stopped` | Online indicator in the admin UI |
| `subscriber.login_rejected` | Support hints ("wrong password"); not sent unless you subscribe to it, and it is noisy |
| `nas.online` / `nas.offline` | Alert the operator that a router is down |

Remind customers *before* expiry from your own scheduler (you know `expires_at`); Mikrodius
only tells you when something has happened.

### Keeping your copy in sync

Webhooks can be missed: your server was down for more than the 24 hours of retries, or the
endpoint was disabled. Staff also edit subscribers in the Mikrodius dashboard. So keep a small
reconcile job next to the webhook route:

- Every 15 minutes, call `listSubscribers` with `updated_since` set to the time the previous
  run started, minus a minute, and apply each subscriber the same way a `subscriber.updated`
  event is applied. The first run has no `updated_since` and reads everything.
- Store the time Mikrodius said something (`created_at` of the event, or the start of the run)
  next to your copy and skip anything older, so late and repeated news changes nothing.
- A subscriber deleted in the dashboard arrives as `subscriber.updated` with
  `action: "deleted"`; the list does not show deletions.
- After `workspace.moved`, run the reconcile once.

An app with no public HTTPS address (on a LAN, behind CGNAT) cannot receive webhooks. Run the
same job every minute or two instead; it is the supported way to work without them.

Cache only what a list screen needs (`state`, `expires_at`, `online`, `usage`). For one
customer's detail page, read it live with `getSubscriber`.

### Who is online, and how fast

- `online` on the subscriber and `session.started` / `session.stopped` give the indicator.
- A live table: `streamSessions` sends the active sessions about every 5 seconds as
  server-sent events and closes after 25 seconds; reconnect to the same URL. From a server
  only: the key must not reach the browser, so relay the stream through your backend.
- There is no speed field. Work it out from two readings of `download_bytes` and
  `upload_bytes`, divided by the time between them. The counters move at the router's
  accounting interval, so treat the result as an average, not a live gauge.

### Apps used by many operators

When each of your users has their own Mikrodius account (a SaaS billing product, a mobile app,
a plugin), do not ask them to paste an API key. Use "Connect with Mikrodius", the OAuth 2.0
authorization code flow with PKCE:

1. Register your app once with `createOAuthClient` (`POST /oauth/clients`): its name and
   redirect URIs. Keep the `client_secret` on your server.
2. Send the user to the authorize page (the URL is under "Connect with Mikrodius" in the
   reference) with a random `state` and a PKCE `code_challenge`. They choose the workspaces and
   the access to allow.
3. On your redirect URI, check `state`, then exchange `code` with `createOAuthToken`
   (`POST /oauth/token`, form-encoded, client credentials as HTTP Basic). Its errors are
   `invalid_grant` and `invalid_client`.
4. The `access_token` is an ordinary API key, limited to `workspace_ids`. Store it encrypted,
   one per user. `getMe` tells you the account behind it.

What changes compared to a single-operator app:

- **One app webhook for all users.** Set `webhook_url` (and optionally `webhook_events`) on
  your client with `updateOAuthClient`, then call `rotateOAuthClientWebhookSecret` once and
  store the `webhook_secret`. Mikrodius sends that URL the events of every workspace a user
  connected, and stops when they disconnect. Verify the signature with that one secret, then
  use `account_id` and `workspace_id` in the body to find the user. Nothing needs registering
  in the user's account. If `webhook_disabled_reason` is set, fix your route and set
  `webhook_url` again to turn delivery back on.
- **A `401` means the user disconnected your app** (Connected apps in their dashboard). Mark
  the account "reconnect needed" and stop calling; do not retry.
- **The key is workspace-scoped**: `balance` in `getMe` is `null`, and it cannot create
  workspaces. Let the user manage credits in Mikrodius, and tell them when a call returns
  `insufficient_balance` or `spend_cap_reached`.
- **Prefix your `external_id`s** (`myapp:<id>`) for subscribers and plans, so your app
  recognizes its own records in a workspace that the operator also uses by hand or with
  another app, and leaves the rest alone.
- **The rate limit is per key**, so one busy operator does not slow the others.

### Hotspot vouchers

1. Create a plan with `validity_seconds` (for example `86400`) and usually a
   `data_limit_bytes` or `time_limit_seconds`.
2. Call `generateVouchers` (`POST /workspaces/{workspace_id}/vouchers`) with `count`,
   `plan_id` and optional `prefix`, `length` and `charset`.
3. Print or sell the returned codes. Each voucher's validity starts at its first login.

### Testing without touching live customers

- Create a separate workspace (for example "Staging") and point your development environment
  at it with its own workspace-scoped key. Subscribers cost nothing until they actually get
  online, so a test workspace without routers costs nothing.
- Use `testWebhookEndpoint` to send a signed `ping` to your webhook route, and a tunnel such
  as ngrok or Cloudflare Tunnel to reach your laptop over HTTPS.
- Test the retry paths on purpose: run the activation and payment flows twice with the same
  input and check that nothing is created or extended twice.

### Checks before you ship

Write these as automated tests against the staging workspace. Each one catches a bug that
costs real money:

1. **Webhook signature:** sign a body with the secret and the current time and check that your
   handler accepts it; change one byte of the body and check that it is rejected.
2. **Activation twice:** run the activation flow twice with the same customer. The second run
   gets a `409` on create, fetches the subscriber by `external_id:<your id>` and carries on;
   there is still one subscriber.
3. **Payment twice:** call `renewSubscriber` twice with the same `reference` and check that
   `expires_at` moved once.
4. **Someone else's username:** create a subscriber whose username is taken by another
   customer and check that the app asks for a different one instead of continuing.

### Common mistakes

- Treating `0` as unlimited, or sending Mbps where kbps is expected.
- Calling `renew` without `reference`, then retrying after a timeout and extending twice.
- Running a nightly job that suspends expired customers: expiry already does this, and the job
  hides the real `state`.
- Polling `listSessions` to detect expiry or quota instead of subscribing to webhooks.
- Trusting webhooks alone, with no reconcile job: one missed event leaves a customer wrong
  forever.
- Failing a customer's payment because Mikrodius could not be reached. Record the payment,
  queue the `renew` and retry it; the `reference` makes that safe.
- Parsing JSON before verifying the webhook signature, which changes the bytes being signed.
- Using a mutable value (name, phone number) as `external_id`.
- Parsing the `sub_` / `plan_` IDs, or assuming their format.
- Putting the API key in a frontend bundle "just for the admin panel".

### Build order for a new app

1. API client module (see "API client") and environment variables; verify the key with
   `getMe`. Every later step calls the API through this module, never directly.
2. Settings screen: choose or create the workspace; create the plans and store their IDs.
3. Customer create and edit screens backed by `createSubscriber` and `updateSubscriber`.
4. Payment recording backed by `renewSubscriber` with `reference`.
5. Webhook route with signature check, de-duplication and background processing, and the
   reconcile job from "Keeping your copy in sync".
6. Customer portal page: `state`, `expires_at`, `online` and usage from `getSubscriber`.
7. Router onboarding: `createNas` and a copy-to-clipboard install command; status from
   `nas.online` / `nas.offline`.
8. Optional: isolation plan, vouchers, usage charts from `getSubscriberUsage`.
