- PHP 100%
| Filename | Latest commit message | Latest commit date |
|---|---|---|
- Update assertions in tests/run.php to reflect changes in SDK documentation. - Enhance PHP examples generation in tools/generate-docs.php to include query and path parameters. - Modify the API reference structure to include Composer installation command and examples for synchronous and asynchronous calls. - Revise HTML documentation to improve clarity and organization, including a new quick start section and updated terminology. - Adjust endpoint metadata to provide clearer information on authentication and request parameters. - Update the output messages to reflect the focus on PHP SDK operations instead of general API endpoints. |
||
| docs | ||
| src | ||
| tests | ||
| tools | ||
| .gitignore | ||
| composer.json | ||
| composer.lock | ||
| README.en.md | ||
| README.fa.md | ||
| README.md | ||
Barghman PHP
An unofficial PHP SDK for the API used by the Barghman (برق من) web application. It provides a synchronous client, an Amp-based asynchronous client, named multi-account sessions, and encrypted file-based token persistence.
- راهنمای کامل فارسی
- Documentation home
- Interactive PHP SDK documentation
- Machine-readable PHP SDK reference
This is an independent, unofficial project. It is not affiliated with or endorsed by Barghman, Tavanir, or Saapa. The API contract is not publicly documented in the recovered source and may change without notice. Use only accounts and data you are authorized to access.
Contents
- Requirements and installation
- Quick start: OTP login and bills
- Synchronous requests
- Async requests with Amp
- Tokens and multi-account sessions
- Available endpoints
- Custom requests
- Responses and errors
- Security and limitations
- Tests
Requirements and installation
- PHP 8.1 or later
- PHP extensions:
curl,json, andsodium - Composer
- Async support uses
amphp/http-client5, installed as a package dependency.
Install from Composer
composer require barghman/barghman-php
The package must be published to Packagist or another Composer registry configured for your project. If Composer says that the package cannot be found, it has not yet been published to a registry available to your project. For a local checkout, configure a path repository. For example, if your application and the barghmanphp directory are siblings, add this to the application’s composer.json:
{
"repositories": [
{
"type": "path",
"url": "../barghmanphp",
"options": {
"symlink": true
}
}
],
"require": {
"barghman/barghman-php": "*@dev"
}
}
Then run:
composer update barghman/barghman-php
Generated PHP SDK documentation
The interactive, bilingual web documentation explains Composer installation, PHP client setup, synchronous and Amp usage, tokens and sessions, and PHP call examples for every registered operation. HTTP route details are secondary metadata; you do not need to construct cURL or HTTP requests yourself. Public client, session, and transport method signatures are reflected from the source. A machine-readable version is available at docs/api.json.
Regenerate the reference after changing the endpoint registry or public SDK methods:
composer docs:generate
Open docs/index.html directly in a browser or host the docs/ directory as a static website. The generator does not require a CDN or external JavaScript library.
Response-schema limitation: The recovered client returns API response bodies without endpoint-specific mapping, and the source does not define per-route output fields. The reference documents the actual mixed return contract, JSON decoding, empty/non-JSON behavior, and HTTP exceptions; it does not invent endpoint response fields.
Load Composer’s autoloader in your application:
require __DIR__ . '/vendor/autoload.php';
Quick start: OTP login and bills
<?php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use Barghman\BarghmanClient;
$client = new BarghmanClient();
// OTP payload fields must match the current API version.
$sendResult = $client->sendOtp([
'mobile' => '09xxxxxxxxx',
]);
// Obtain the SMS code from a secure user input; never log it.
$otp = readline('OTP: ');
$loginResult = $client->verifyOtp([
'mobile' => '09xxxxxxxxx',
'code' => $otp,
]);
// If the response includes Token, the client retains it for later calls.
$bills = $client->getBills();
print_r($bills);
mobile and code are example field names observed in common usage; confirm the request and response shape against the live API. The client does not invent a schema for API payloads. JSON responses are returned as associative PHP arrays; non-JSON bodies are returned as strings.
Example login response shape recognized by the recovered client (the actual token is secret):
{
"data": {
"Token": "<opaque-token>"
}
}
Add, update, and remove a bill
// Use the exact fields required by the current API/form.
// No real bill identifier or unverified payload fields are included here.
$billPayload = [
'bill_id' => getenv('BARGHMAN_BILL_ID') ?: '',
// Add any other fields required by the current API.
];
$added = $client->addBill($billPayload);
// updateBill follows the web app and sets BillType to 2.
$updated = $client->updateBill($billPayload);
$removed = $client->removeBill($billPayload);
For an electricity bill inquiry:
$billData = $client->getPowerBillData([
// Fields required by GetPowerBillData.
]);
// The authenticated variant observed in the web app:
$limitedBillData = $client->getPowerBillData(
payload: [
// Fields required by the API.
],
authenticated: true
);
Synchronous requests
The synchronous client uses cURL and waits for each response:
use Barghman\BarghmanClient;
$client = new BarghmanClient(
baseUrl: 'https://uiapi2.saapa.ir',
timeout: 20
);
$providers = $client->call('getProviders');
$cities = $client->call(
'getProviderCities',
query: ['code' => '...']
);
$siteConfig = $client->call(
'getSiteConfig',
pathParameters: ['key' => '...']
);
baseUrl must be an HTTP(S) origin or base path. For GET requests, _timeStamp is added automatically unless you provide it, matching the behavior of the recovered web client.
Async requests with Amp
AsyncBarghmanClient uses Amp 3 and amphp/http-client 5. Async methods return Amp\Future. Create all futures before awaiting them to let independent operations run concurrently:
<?php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use Barghman\AsyncBarghmanClient;
use function Amp\Future\awaitAll;
$client = new AsyncBarghmanClient(
token: getenv('BARGHMAN_TOKEN') ?: null,
timeout: 20
);
$futures = [
'bills' => $client->getBillsAsync(),
'profile' => $client->callAsync('getProfileSettings'),
'providers' => $client->callAsync('getProviders'),
];
// Results are returned with the same keys as the input futures.
$results = awaitAll($futures);
$bills = $results['bills'];
$profile = $results['profile'];
$providers = $results['providers'];
You can also create several futures and await them individually:
$billsFuture = $client->getBillsAsync();
$paymentsFuture = $client->callAsync('getPaymentHistory', payload: [
// Fields required by PaymentHistory.
]);
$bills = $billsFuture->await();
$payments = $paymentsFuture->await();
Awaiting one request before creating the next makes the operations sequential.
Endpoint calls with query, path, and payload parameters
$citiesFuture = $client->callAsync(
'getProviderCities',
query: ['code' => '...']
);
$configFuture = $client->callAsync(
'getSiteConfig',
pathParameters: ['key' => '...']
);
$billFuture = $client->callAsync(
'addBill',
payload: [
'bill_id' => getenv('BARGHMAN_BILL_ID') ?: '',
// Fields required by the API.
]
);
$cities = $citiesFuture->await();
$config = $configFuture->await();
$bill = $billFuture->await();
Every name returned by BarghmanClient::endpoints() is also exposed through a magic convenience method with an Async suffix, for example getProvidersAsync() or getSiteConfigAsync(pathParameters: ['key' => '...']). For IDE autocomplete, static analysis, and less common endpoints, callAsync() is the recommended interface.
Cancel an operation
use Amp\DeferredCancellation;
$cancellation = new DeferredCancellation();
$future = $client->callAsync(
'getProviders',
cancellation: $cancellation->getCancellation()
);
// Cancel when the user or an upstream operation no longer needs the result.
$cancellation->cancel();
try {
$result = $future->await();
} catch (Amp\CancelledException $exception) {
// Handle cancellation as cancellation, not as a successful API response.
}
TCP connection, TLS handshake, transfer, and inactivity timeouts use the constructor’s timeout. The default transport disables automatic redirects to avoid forwarding authentication headers to a redirect destination.
Tokens and multi-account sessions
For a short-lived process, you can pass a token directly:
$client = new BarghmanClient(
token: getenv('BARGHMAN_TOKEN') ?: null
);
$bills = $client->getBills();
For persistence across application runs, use the encrypted file store. Generate a key once and keep it in an environment variable or secret manager:
php -r 'echo base64_encode(random_bytes(SODIUM_CRYPTO_SECRETBOX_KEYBYTES)), PHP_EOL;'
Set the generated value as BARGHMAN_SESSION_KEY. Do not put the key in source code, logs, or Git:
use Barghman\BarghmanClient;
use Barghman\EncryptedFileSessionStore;
use Barghman\SessionManager;
$key = EncryptedFileSessionStore::keyFromBase64(
(string) getenv('BARGHMAN_SESSION_KEY')
);
$sessionStore = new EncryptedFileSessionStore(
__DIR__ . '/var/barghman-sessions.dat',
$key
);
$sessions = new SessionManager($sessionStore);
$client = new BarghmanClient(sessionManager: $sessions);
// Log into the first account; use your own stable internal account ID.
$client->beginSession('account-home');
$client->sendOtp(['mobile' => '09xxxxxxxxx']);
$client->verifyOtp(['mobile' => '09xxxxxxxxx', 'code' => '...']);
// A second account does not overwrite the first account's token.
$client->beginSession('account-work');
$client->sendOtp(['mobile' => '09yyyyyyyyy']);
$client->verifyOtp(['mobile' => '09yyyyyyyyy', 'code' => '...']);
// Switch between saved accounts:
$client->useSession('account-home');
$homeBills = $client->getBills();
The same SessionManager can be shared with AsyncBarghmanClient. Async OTP verification (verifyOtpAsync) saves its token to the selected session:
$client = new AsyncBarghmanClient(sessionManager: $sessions);
$client->beginSession('account-home');
$client->sendOtpAsync(['mobile' => '09xxxxxxxxx'])->await();
$client->verifyOtpAsync(['mobile' => '09xxxxxxxxx', 'code' => '...'])->await();
Session management methods:
$sessions->get('account-home'); // BarghmanSession|null
$sessions->getActive(); // active session
$sessions->all(); // all saved sessions
$sessions->activate('account-work'); // choose the active session
$sessions->remove('account-work'); // remove only that session
$sessions->clear(); // remove all sessions
The encrypted file and lock are written with restricted 0600 permissions; session contents are encrypted with Sodium. A lost encryption key cannot be recovered. InMemorySessionStore is available for tests and one-shot processes. JWTs containing the standard exp claim are checked for expiration; their signatures are not verified. Expiration cannot be determined for opaque tokens. No token-refresh endpoint was found in the recovered source, so an expired session requires a new OTP login.
Available endpoints
Inspect the endpoint names programmatically:
$names = BarghmanClient::endpoints();
print_r($names);
Examples by area:
| Area | Example endpoint names |
|---|---|
| Authentication and account | sendOtp, verifyOtp, logout, updateUser, verifyUser |
| Bills | getBills, addBill, updateBill, removeBill, getPowerBillData |
| Payments and history | createBillPaymentRequest, getTransactionPspData, getPaymentHistory, getSaleEnergyHistory |
| Branches and regions | searchBranchData, getProviders, getProviderCities, getProviderRegions, getVillages |
| Requests and documents | saveRequest, traceRequest, getRequestNeededDocuments, getInstallmentDocuments |
| Meters | getMeterCompanies, getRemoteMeters, buyMeter, splitMeter, getMeterPdf |
| Notifications and outages | getNotifications, markNotificationSeen, getBlackoutsReport, getPlannedBlackoutsReport |
| Services and consumption | getServiceList, getOrganizationBills, getConsumptionDiagram, calculateSaapaBill |
call() and callAsync() accept an endpoint name, payload, query parameters, and path parameters. Protected endpoints require a valid token. The endpoint name alone does not define the exact request payload; match payload fields to the active API form or contract.
Custom requests
Use request() for an API route not present in the recovered endpoint catalogue or for a route that has changed:
$response = $client->request(
method: 'POST',
path: '/api/example/route',
payload: [
'field' => 'value',
],
authenticated: true,
query: [
'page' => 1,
]
);
The async counterpart returns a Future:
$future = $asyncClient->requestAsync(
method: 'POST',
path: '/api/example/route',
payload: ['field' => 'value'],
authenticated: true
);
$response = $future->await();
Paths must be relative /api/... paths. Query and path parameter values are URL-encoded. GET requests do not accept a body; pass parameters through query.
Responses and errors
- JSON responses are decoded to associative PHP arrays.
- An empty response body returns
null. - A non-JSON response is returned as a string. Invalid JSON with an
application/jsoncontent type raises an exception. - Non-2xx HTTP responses raise
Barghman\ApiException. - Network and transport errors remain exceptions; failed responses are not converted into success-shaped fallbacks.
- Protected requests without a token or with an expired JWT are rejected before sending.
use Barghman\ApiException;
try {
$bills = $client->getBills();
} catch (ApiException $exception) {
error_log(sprintf(
'Barghman API HTTP %d',
$exception->statusCode
));
// responseBody may contain sensitive data; do not log it indiscriminately.
} catch (LogicException $exception) {
// No token or an expired token; check login/session selection.
}
For async requests, errors are raised when awaiting the Future:
try {
$bills = $client->getBillsAsync()->await();
} catch (ApiException $exception) {
// HTTP error
} catch (Amp\CancelledException $exception) {
// Request cancellation
}
Security and limitations
- Do not log tokens, OTPs, phone numbers, or bill identifiers.
- Store session files in a private directory; keep the Sodium key outside the repository and separate from the encrypted file.
- Payload requirements may change with the API version.
- This package does not bypass CAPTCHA, authenticate on behalf of a user, or generate/refresh API tokens.
- No token-refresh endpoint was found in the recovered source; use the permitted OTP flow for expired sessions.
- Follow the service’s terms and use the API only with authorized access.
Tests
Tests run offline with mock transports and do not send real requests to Barghman:
composer install
php tests/run.php
To install exact dependency versions from the lock file:
composer install --no-interaction