# @wisnots/netz

A TypeScript client for the Netz API: registering PV, storage, heat pumps, wallboxes and air conditioning with the responsible grid operator in Germany, Austria or Switzerland. Dependency-free; the types are generated from the OpenAPI documents the reference at https://www.wisnots.com/en/netzanmeldung/api renders.

This page documents the v2 client, `@wisnots/netz/v2`, first: build a new integration on it. v1 is being retired; its client stays for integrations already on v1 and is documented at the end, under [v1](#v1-being-retired).

Keys come from the console at https://www.wisnots.com/netzanmeldung/portal, under Developers. A `wnz_test_` key is the sandbox, a `wnz_live_` key is live, and that prefix is the whole switch: same host, same calls, same shapes.

## v2

`@wisnots/netz/v2` is the client for the Netz API v2 (reference: https://www.wisnots.com/en/netzanmeldung/api), over the same cases, keys and webhook signature as v1. Beside cases it has businesses, one list of what a case needs (`open[]`, each item with how it is answered), events that carry their case, business or invoice, and billing.

```ts
import { createNetzClient, NetzApiError } from '@wisnots/netz/v2';

const netz = createNetzClient({ apiKey: process.env.NETZ_API_KEY! });

const business = await netz.businesses.create({ external_ref: 'INST-0042', name: 'Nordlicht Elektrotechnik GmbH' });
const draft = await netz.cases.create({ type: 'charge_point', business_id: business.id, external_ref: 'ERP-4711' });
// draft.status is `needs_input` or `ready`: a case is a draft until you submit it, and no status says `draft`.
await netz.cases.addDocument(draft.id, { fixture: 'wallbox-invoice-de' });   // a file: { file: { filename, bytes } }
const read = await netz.cases.waitForDocuments(draft.id);                     // or the case.documents_read webhook

for (const item of read.open.filter((i) => i.blocking)) {
  // item.resolve.field: PATCH it under `declared`; item.resolve.document: send a document with resolves: item.code
}
// Once nothing blocking is open (`status` reads `ready`); before that, submit is a 409 case_incomplete.
const submitted = await netz.cases.submit(draft.id, { sandbox_pace: 'staged' });

for await (const kase of netz.cases.iterate({ business_id: business.id })) { /* every page, by its cursor */ }
const usage = await netz.usage.get({ month: '2026-11' });
const [invoice] = (await netz.invoices.list()).data;
if (invoice) await netz.invoices.pdf(invoice);                                 // the PDF's bytes, read at its pdf_url
```

On a `wnz_test_` key the sandbox plays what happens outside your platform, chosen by the site's postcode (`00041` is asked for more, `00150` rejected) and driven by its test helpers, which skip a wait. At the default `sandbox_pace: 'instant'` the grid operator has answered before `submit` returns, so a reply of yours would be a 409 `not_due`; the submit above chose `'staged'`, and the case waits a few seconds for its answer, in which you give it:

```ts
await netz.testHelpers.gridOperatorReply(submitted.id, 'approved');            // or 'rejected', 'query'; the staged steps still to come then do nothing
await netz.testHelpers.resolveRequirement(submitted.id, 'commissioning_report'); // the installer's report, as built and commissioned today
await netz.testHelpers.advance(submitted.id);                                   // the next stage: completion_filed
await netz.testHelpers.sendWebhook('case.status_changed');                      // the newest such event, again; needs a sandbox v2 endpoint (netz.webhooks.create), else a 409 not_due
```

Two cases of one connection (PV and its battery, the same `external_ref`, site, end customer and business) are one registration and one credit when the second is handed over before the first reached the grid operator. On the sandbox the first reaches it inside an `'instant'` submit; submit both at `'staged'`, the second within about four seconds, to see them filed as one (`group`).

A handed-over case the customer called off is withdrawn with `netz.cases.withdraw(id, { reason })`, after the hand-over and before the grid operator decided: `case.withdrawal` reads `requested` until a person at Wisnots has withdrawn it with the operator, then `status` reads `withdrawn`, and its credit stays spent. A draft reached nobody, so withdrawing one is a 409 `not_due`: delete it with `netz.cases.delete(id)`. On the sandbox the sandbox operator withdraws it a few seconds later, or `testHelpers.advance` does at once.

A webhook delivery is checked by the verifier both clients share; `verifyWebhookEvent` checks and parses in one step:

```ts
import { verifyWebhookEvent } from '@wisnots/netz/v2';

const event = await verifyWebhookEvent({ header: req.header('Wisnots-Signature') ?? '', body: rawBody, secret });
if (event.type === 'case.status_changed') console.log(event.case.id, event.stage?.code);
```

v2 sends again what may be sent again, twice unless `maxRetries` says otherwise: a 429 after `Retry-After`, and a read or a keyed create after a network failure or a 502, 503 or 504. `cases.create` carries an `Idempotency-Key` of its own when you give none, so a create sent again never opens a second case. A refusal is a `NetzApiError` (the same class as v1's), with v2's codes; on `business_exists`, `businessId` names the business that holds the ref.

### Embedded components

Our forms in your own page: your server mints a session with its key for one of your account's allowed pages (console, Developers, Connect, Embed), and your page's loader (`/netz-embed/v2/embed.js`) asks for the secret through `fetchClientSecret`.

```ts
// Your server, behind the route the page's fetchClientSecret calls: a fresh session on every call.
const session = await netz.businesses.createEmbedSession(business.id, {
  origin: 'https://app.example.com',
  components: ['registrations', 'new-registration'],
  platform_name: 'Your product',
});
return session.client_secret;   // to the frame only: never logged, never in a URL

// A case alone: `case` (the default), or `registration` / `upload` on a draft.
await netz.cases.createEmbedSession(draft.id, { origin: 'https://app.example.com', components: ['upload'] });
```

`client_secret` is a bearer credential for its session. It ends 30 minutes after minting, and sooner when the key is revoked, the page removed from the list or the business deactivated. Ended or revoked, it answers 401 and the loader asks `fetchClientSecret` again; a removed page or a deactivated business ends the frame for good. A page not on the list is a `NetzApiError` with `code: 'origin_not_allowed'`. A mint is not sent again after a network failure or a 5xx, since a second one would be a second session.

## v1, being retired

The v1 client, `@wisnots/netz` (reference: https://www.wisnots.com/en/netzanmeldung/api/v1), for an integration already on v1. A new integration uses v2, above.

### Quickstart

```ts
import { createNetzClient } from '@wisnots/netz';

const netz = createNetzClient({ apiKey: process.env.NETZ_API_KEY! });          // wnz_test_… first

const draft = await netz.cases.create('ladeeinrichtung', {
  intent: 'draft', material: [{ fixture: 'wallbox-invoice-de' }],           // a fixture: read for free, identically every time
});
const read = await netz.cases.waitForExtraction(draft.id);                    // or act on the case.extraction_completed webhook
console.log(read.open.filter((o) => o.blocking).map((o) => o.path));         // what is still missing, and who knows it

const ready = await netz.cases.patch(draft.id, { declared: { end_customer: { phone: '+49 40 5550123' } } });
const filed = await netz.cases.file(ready.id, { sandbox_outcome: 'accepted', sandbox_pace: 'staged' });
```

Then watch `GET /v1/anmeldungen/{id}/events` (`netz.cases.events(id)`) or a webhook deliver `submitted`, `waiting_operator` and the answer a few seconds apart. Swap in a `wnz_live_` key and drop the two sandbox fields; nothing else changes.

### Sending a document

Files open a case the way a back office has them: the documents, the customer's mail, whatever fields you already hold. One call, multipart, up to 20 MB (20,000,000 bytes) per file and 20 MiB for the whole request; the API reads the bytes and decides what each file is (a PDF, JPEG, PNG, WebP or HEIC, or plain text sent as `text/plain`).

```ts
import { readFile } from 'node:fs/promises';

const kase = await netz.cases.createFromFiles('pv', {
  files: [
    { filename: 'rechnung.pdf', bytes: await readFile('rechnung.pdf') },
    { filename: 'typenschild.jpg', bytes: await readFile('typenschild.jpg') },
  ],
  text: await readFile('kundenmail.txt', 'utf8'),
  external_ref: 'ERP-9001',
});
const read = await netz.cases.waitForExtraction(kase.id);                    // or the case.extraction_completed webhook
```

`upload` adds files to a case that exists, the same way:

```ts
await netz.cases.upload(kase.id, { filename: 'nachtrag.pdf', bytes: await readFile('nachtrag.pdf') });
```

A file also goes inline in the JSON body, base64 in `data`, up to 8 MB (`cases.create` or `cases.addMaterial` with `{ kind: 'file', data, filename, content_type }`). `uploadByTarget` is the three-call flow for a client that streams bytes and never holds the file.

### Errors

Every refusal is a `NetzApiError`. Branch on `code`, which is the closed enum the reference documents; `errors` names each refused field with a one-sentence reason.

```ts
import { NetzApiError } from '@wisnots/netz';

try {
  await netz.cases.file(id);
} catch (err) {
  if (err instanceof NetzApiError && err.code === 'case_incomplete') {
    // read the case's open[] and ask your user
  } else if (err instanceof NetzApiError && err.code === 'rate_limited') {
    await new Promise((r) => setTimeout(r, (err.retryAfterSeconds ?? 1) * 1000));
  } else throw err;
}
```

### Webhooks

Verify the raw body before you parse it. The scheme is Stripe's: `Wisnots-Signature: t=<seconds>,v1=<hex hmac-sha256>` over `${t}.${body}`.

```ts
import { verifyWebhookSignature } from '@wisnots/netz';

app.post('/netz-webhook', express.raw({ type: '*/*' }), async (req, res) => {
  const ok = await verifyWebhookSignature({
    header: req.header('Wisnots-Signature') ?? '',
    body: req.body.toString('utf8'),
    secret: process.env.NETZ_WEBHOOK_SECRET!,
  });
  if (!ok) return res.status(400).end();
  const event = JSON.parse(req.body.toString('utf8'));
  // Deliveries are at least once: key on the Wisnots-Event-Id header.
  res.status(204).end();
});
```

### Operators

```ts
const { data, resolved } = await netz.operators.byPostcode('20095');
// resolved: exactly one operator serves it; send data[0].key as `operator` on create.
// otherwise: none, or several, and the choice is your user's.
```

## Files

Both clients share `http.ts` (the HTTP core: requests, refusals, retries) and `webhooks.ts`. v1 is `index.ts`, `client.ts` and `types.gen.ts`; v2 is `v2.ts`, `client.v2.ts` and `types.v2.gen.ts`. All of them are served at https://www.wisnots.com/netz-api/sdk/ for a project that vendors them.
