nieknijland / ista-php
PHP client for the Ista energy consumption API
Fund package maintenance!
Requires
- php: ^8.4
- guzzlehttp/guzzle: ^7.0
- psr/simple-cache: ^3.0
Requires (Dev)
- laravel/pint: ^1.0
- phpstan/phpstan: ^2.0
- phpstan/phpstan-strict-rules: ^2.1
- phpunit/phpunit: ^10.3
- rector/rector: ^2.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
PHP client for the Ista energy consumption API at mijn.ista.nl. Framework-agnostic.
Requires PHP 8.4+.
Installation
composer require nieknijland/ista-php
Quick start
use NiekNijland\Ista\Ista; $ista = new Ista( username: 'your@email.com', password: 'your-password', ); // Fetch all consumption data $userValues = $ista->getUserValues(); $customer = $userValues->customers[0]; foreach ($customer->consumption->services as $service) { echo "Current usage: {$service->totalNow}\n"; echo "Previous year: {$service->totalPrevious}\n"; foreach ($service->currentMeters as $meter) { echo " {$meter->position}: {$meter->value}\n"; } }
Constructor
$ista = new Ista( username: 'your@email.com', password: 'your-password', httpClient: $customGuzzleClient, // ?GuzzleHttp\ClientInterface, default: new Client() cache: $psr16Cache, // ?CacheInterface (PSR-16), default: null (no caching) cacheTtl: 3600, // int, cache TTL in seconds // resilience options, all optional (see below) maxRetries: 3, retryDelayMilliseconds: 500, requestDelayMilliseconds: 250, );
| Parameter | Type | Default | Description |
|---|---|---|---|
$username |
string |
(required) | Your mijn.ista.nl username |
$password |
string |
(required) | Your mijn.ista.nl password (marked #[SensitiveParameter]) |
$httpClient |
?ClientInterface |
null |
Custom Guzzle client; null creates a default one |
$cache |
?CacheInterface |
null |
Any PSR-16 cache; null disables caching |
$cacheTtl |
int |
3600 |
Cache time-to-live in seconds |
The resilience arguments are appended after $cacheTtl, so existing calls keep working.
API methods
All methods throw IstaException (or a subclass) on failure.
| Method | Description |
|---|---|
getUserValues() |
Customers (dwellings), billing services, billing periods, current and comparison period with all meters, temperatures, userKey |
getConsumptionValues($cuid, $year, $start, $end) |
Consumption for one billing period (use the values of Customer::$consumption->billingPeriods) |
getMonthlyConsumption($cuid) |
Month-by-month history with per-room device readings and the building average. Polls while the server answers HTTP 425 (see below) |
getConsumptionAverages($cuid, $start, $end, $language = 'nl') |
Normalised building average ("gebouw gemiddelde") per billing service |
getProfile() |
Read-only account profile (name, username, e-mail, phone, MFA flag). The password is never returned |
getSettings() |
Read-only server-side settings: current culture and the available cultures |
refreshSession() |
Extends the session like the portal does every ten minutes; the client also does it on its own |
Not exposed on purpose: everything that writes (/api/profile/set, /Settings/SetCulture, account deletion). The pages /Home, /Home/Graph, /Home/Monthly and /Home/Data are static shells that render the data of the endpoints above in the browser; theme and the "explain my consumption" toggle are browser-only settings.
$customer = $ista->getUserValues()->customers[0]; $period = $customer->consumption->billingPeriods[1]; $values = $ista->getConsumptionValues($customer->cuid, $period->year, $period->start, $period->end); $averages = $ista->getConsumptionAverages($customer->cuid, $customer->consumption->start, $customer->consumption->end); $months = $ista->getMonthlyConsumption($customer->cuid);
Monthly data and HTTP 425
The server prepares month values on demand and answers 425 Too Early until they are ready, which can take minutes
(the portal polls for up to 30 minutes). getMonthlyConsumption() polls like the portal does: 2 s doubling to 15 s,
Retry-After wins, at most monthlyMaxAttempts times (default 10). A partial answer (hasMonths < showMonths)
is returned when the attempts run out and is not cached; if nothing arrived at all a NotReadyException is thrown.
Raise monthlyMaxAttempts if you are willing to wait longer.
Login flow
The portal changed in late 2026; this package follows the current flow:
GET https://mijn.ista.nl/home/loginredirects to the Keycloak login page onlogin.ista.com. The old entry point/home/indexno longer starts the login. Requests without browser navigation headers (Sec-Fetch-*,Accept: text/html, ...) get an empty HTTP 401, so every request carries a browser header set from one place (BrowserHeaders). Override or extend it withdefaultHeaders.- The credentials are posted to the form action of that page (the form id is
kc-form-login; hidden fields are forwarded; the action is HTML-entity decoded and may only point tologin.ista.comormijn.ista.nlover https). The credential POST is never retried. - Keycloak answers with a
form_postpage that is submitted to/signin-oidc, which sets the session cookies and redirects to/Home. - There is no JWT any more. The session is the cookie jar plus the CSRF token from
<meta name="csrf-token">on/Home. API calls arePOSTwithContent-Type: application/json, the portal's staticAuthorization: Bearer ...constant (public, taken from its own JavaScript), theX-CSRF-TOKEN-ista-NL_TPheader and the cookies.
The session (cookies and CSRF token) is stored in the PSR-16 cache under ista:session when you pass a cache, so a new process reuses it. When a call is answered with HTTP 401 (or a page lands on the login host, or a cached session yields no customers) the client logs in again once and repeats the call; that re-login counts as a retry in the stats. A second 401 raises AuthenticationException, there is no loop.
Failures state the step and HTTP status without leaking secrets, for example
Ista authentication failed at step "login page" (HTTP 401).; the steps are login page, credential submission,
OIDC callback and session establishment.
Resilience options
All options are optional and appended to the constructor; the defaults keep a single attempt per request.
| Option | Default | Meaning |
|---|---|---|
requestTimeoutSeconds |
10.0 |
Request timeout, must be > 0 |
maxRetries |
0 |
Extra attempts after a transport error, 403, 429 or >= 500 (0 = one attempt) |
retryDelayMilliseconds |
200 |
Base for exponential backoff (base * 2^(attempt-1), +-25% jitter); 0 disables it (a Retry-After header is still honoured) |
defaultHeaders |
[] |
Headers merged over the browser headers (names compared case-insensitively) |
clock |
system clock | ClockInterface (sleepMilliseconds, now); use Testing\FakeClock in tests |
requestDelayMilliseconds |
0 |
Delay between operations (skipped before the first) |
requestDelayJitterMilliseconds |
0 |
Random 0..jitter added to that delay |
maxRequestsPerWindow |
0 |
Max HTTP attempts until resetStats(); 0 is unlimited. Exceeding it throws RequestLimitException |
proxyUrl |
null |
Proxy URL passed to Guzzle (needs scheme and host) |
monthlyMaxAttempts |
10 |
Polls of getMonthlyConsumption() while the server answers 425 |
Invalid values throw ConfigurationException.
- 429 and >= 500 are retried, 403 is retried after clearing the session cookies, transport errors are retried.
- On 429 and 503 a
Retry-Afterheader (seconds or HTTP date) is honoured when it is larger than the backoff, capped at 60 seconds. - Redirects (301, 302, 303, 307, 308) are followed up to 5 times; 301/302/303 become a body-less GET, 307/308 replay the request.
- Cookies are kept per host (
mijn.ista.nlandlogin.ista.comnever see each other's).
Stats
$stats = $ista->getStats(); // requests, successes, failures (transport errors and >= 500), content_failures (other 4xx), // retries, session_resets, last_request_at (unix seconds or null), total_sleep_ms $ista->resetStats(); // zeroes the stats and reopens the request window $ista->resetSession(); // clears cookies and the cached session
Caching
Pass any PSR-16 CacheInterface to cache API responses and the session:
$ista = new Ista( username: 'your@email.com', password: 'your-password', cache: new YourPsr16Cache(), cacheTtl: 86400, // 24 hours );
| Key pattern | Data |
|---|---|
ista:session |
Session cookies and CSRF token (treat the cache like a credential store) |
ista:user-values |
getUserValues() response |
ista:consumption-averages:{cuid}:{start}:{end} |
getConsumptionAverages() response |
ista:monthly-consumption:{cuid} |
getMonthlyConsumption() response (complete results only) |
ista:consumption-values:{cuid}:{year}:{start}:{end} |
getConsumptionValues() response |
Cache failures are silently ignored: the client will re-fetch from the API. Profile and settings are never cached.
Data objects
All API responses are returned as readonly DTOs with typed properties. Every DTO provides fromArray() and toArray() for serialization.
| Class | Description |
|---|---|
UserValuesResult |
Top-level response with customers |
Customer |
A customer with address and consumption data |
ConsumptionPeriod |
A billing period with services, meters, and temperatures |
ServiceComparison |
Current vs. previous year totals for a service type |
Meter |
A single meter reading with all technical fields |
BillingService |
Service type definition (e.g. Heating, Hot Water) |
BillingPeriod |
A billing year with start/end dates |
ConsumptionAverageResult |
Building average consumption |
ConsumptionValuesResult |
Consumption data for a specific billing period |
MonthlyConsumptionResult |
Monthly consumption history |
MonthlyConsumption |
A single month's consumption |
MonthlyServiceConsumption |
Per-service totals for a month |
MonthlyDeviceConsumption |
Per-device readings for a month |
Also available: Profile, Settings and Culture for the read-only account pages.
Error handling
Everything extends IstaException:
| Exception | When |
|---|---|
AuthenticationException |
The login flow failed; ->step (enum AuthenticationStep) and ->statusCode say where |
HttpException |
Non-success HTTP status; ->statusCode and ->step. Subclasses: NotFoundException (404), GoneException (410), RateLimitException (429, ->retryAfterSeconds), NotReadyException (425, ->retryAfterSeconds) |
TransportException |
No HTTP response (DNS, connect, TLS, timeout) |
RequestLimitException |
maxRequestsPerWindow exceeded |
ConfigurationException |
Invalid constructor option |
Messages never contain credentials, cookies, tokens, response bodies or URL query strings.
use NiekNijland\Ista\Exception\AuthenticationException; use NiekNijland\Ista\Exception\IstaException; try { $result = $ista->getUserValues(); } catch (AuthenticationException $e) { // $e->step, $e->statusCode } catch (IstaException $e) { // everything else }
Testing
The package ships testing utilities so you can mock the Ista client in your application tests without making real API calls.
use NiekNijland\Ista\Testing\FakeIsta; use NiekNijland\Ista\Testing\UserValuesResultFactory; $fake = new FakeIsta(); $fake->seedUserValuesResult(UserValuesResultFactory::make()); $result = $fake->getUserValues(); $fake->assertCalled('getUserValues'); $fake->assertCalledTimes('getUserValues', 1);
FakeIsta also supports seedProfile(), seedSettings(), seedStats() and records getStats(), resetStats(), resetSession() and refreshSession(). Testing\\FakeClock replaces the system clock so retry and polling tests never sleep.
Development
composer test # Unit tests composer test-integration # Integration tests (requires ISTA_USERNAME and ISTA_PASSWORD) composer test-all # All test suites composer analyse # PHPStan level 8 + strict rules composer format # Laravel Pint composer rector # Rector automated refactoring composer codestyle # Full pipeline: Rector + Pint + PHPStan
Changelog
Please see CHANGELOG for more information on what has changed recently.
License
The MIT License (MIT). Please see License File for more information.