PHP code example of pooshgan / pasarguard-php

1. Go to this page and download the library: Download pooshgan/pasarguard-php library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

pooshgan / pasarguard-php example snippets





Pooshgan\PasarGuard\Client;
use Pooshgan\PasarGuard\PasarGuard;

// 1. Initialize the HTTP client with your panel URL and admin token
$client = new Client(
    baseUrl: 'https://your-panel-domain.com',
    token:  'your-admin-bearer-token'
);

// 2. Wrap it with the high-level SDK facade
$api = new PasarGuard($client);

// 3. Call any endpoint group as a property
$users = $api->users->list();
print_r($users);

// 4. Create a new user with a data limit of 1 GB
$newUser = $api->users->create([
    'username'   => 'test_user',
    'status'     => 'active',
    'data_limit' => 1073741824, // bytes
    'expire'     => (time() + 86400 * 30) * 1000, // ms since epoch
]);

echo "Created user ID: " . $newUser['id'] . PHP_EOL;

// All users (paginated)
$all = $api->users->list();

// Lightweight list (id + username only)
$simple = $api->users->listSimple();

// Filter by query string (?status=active&limit=50)
$active = $api->users->list(['status' => 'active', 'limit' => 50]);

// Users that have already expired
$expired = $api->users->getExpired();

// By username (default variant)
$u1 = $api->users->get('john_doe');

// Explicit by-username variant
$u2 = $api->users->getByUsername('john_doe');

// By internal user ID
$u3 = $api->users->getById(42);

// Fetch the subscription URL for a specific client type
$sub = $api->users->getSubscriptionById(42, 'v2rayNG');

// Create a single user
$created = $api->users->create([
    'username'    => 'jane_doe',
    'proxies'     => ['vmess' => ['id' => '...']],
    'data_limit'  => 5368709120,        // 5 GB in bytes
    'expire'      => (time() + 86400*30) * 1000,
    'status'      => 'active',
    'data_limit_reset_strategy' => 'no_reset',
]);

// Update by username
$api->users->update('jane_doe', ['data_limit' => 10737418240]);

// Update by id (also via updateByUsername / updateById)
$api->users->updateById(42, ['status' => 'disabled']);

// Delete
$api->users->delete('jane_doe');
$api->users->deleteByUsername('jane_doe');
$api->users->deleteById(42);

$api->users->setDisabled('jane_doe', ['disabled' => true]);   // disable
$api->users->setDisabled('jane_doe', ['disabled' => false]);  // re-enable
$api->users->setDisabledByUsername('jane_doe', ['disabled' => true]);
$api->users->setDisabledById(42, ['disabled' => false]);

// Reset data usage of a single user
$api->users->resetDataUsage('jane_doe');
$api->users->resetDataUsageByUsername('jane_doe');
$api->users->resetDataUsageById(42);

// Reset data usage of EVERY user (be careful!)
$api->users->resetAllDataUsage();

// Revoke a user's subscription URL (generates a new one)
$api->users->revokeSubscription('jane_doe');
$api->users->revokeSubscriptionByUsername('jane_doe');
$api->users->revokeSubscriptionById(42);

// Transfer ownership to admin username "reseller_3"
$api->users->setOwner('jane_doe', ['admin_username' => 'reseller_3']);
$api->users->setOwnerByUsername('jane_doe', ['admin_username' => 'reseller_3']);
$api->users->setOwnerById(42, ['admin_username' => 'reseller_3']);

// Activate the user's queued "next plan"
$api->users->activeNextPlan('jane_doe');
$api->users->activeNextPlanByUsername('jane_doe');
$api->users->activeNextPlanById(42);

// Per-user usage
$usage = $api->users->getUsage('jane_doe');
$usage = $api->users->getUsageByUsername('jane_doe');
$usage = $api->users->getUsageById(42);

// Aggregate usage of all users
$allUsage = $api->users->getAllUsage();

// Counts grouped by a metric ("active", "expired", "limited", ...)
$counts = $api->users->getUsersCountMetric('active');

// Subscription update history (chart + list)
$chart = $api->users->getSubUpdateChart();
$list  = $api->users->getSubUpdateList('jane_doe');
$list  = $api->users->getSubUpdateListByUsername('jane_doe');
$list  = $api->users->getSubUpdateListById(42);

// List expired
$expired = $api->users->getExpired();

// Bulk-delete all expired users
$deleted = $api->users->deleteExpired();

// Bulk delete / reset / disable / enable / revoke
$api->users->bulkDelete(['usernames' => ['a', 'b', 'c']]);
$api->users->bulkReset(['usernames' => ['a', 'b', 'c']]);
$api->users->bulkDisable(['usernames' => ['a', 'b', 'c']]);
$api->users->bulkEnable(['usernames' => ['a', 'b', 'c']]);
$api->users->bulkRevokeSub(['usernames' => ['a', 'b', 'c']]);

// Bulk change owner
$api->users->bulkSetOwner([
    'usernames' => ['a', 'b'],
    'admin_username' => 'reseller_3',
]);

// Bulk modify expiration / data limit / proxy settings
$api->users->bulkModifyExpire([
    'usernames' => ['a', 'b'],
    'expire'    => (time() + 86400 * 7) * 1000,
]);
$api->users->bulkModifyDataLimit([
    'usernames'  => ['a', 'b'],
    'data_limit' => 10737418240,
]);
$api->users->bulkModifyProxySettings([
    'usernames' => ['a', 'b'],
    'proxies'   => ['vmess' => ['id' => '...']],
]);

// Bulk reallocate WireGuard peer IPs (re-run IPAM for the listed users)
$api->users->bulkReallocateWireguardPeerIps([
    'usernames' => ['a', 'b'],
]);

// Create a single user from a template
$api->users->createFromTemplate([
    'template_id' => 5,
    'username'    => 'from_tpl_1',
    'count'       => 1,
]);

// Bulk-create users from a template (e.g. 100 users)
$api->users->bulkCreateFromTemplate([
    'template_id' => 5,
    'count'       => 100,
    'prefix'      => 'bulk_user_',
]);

// Apply a template's settings to existing users
$api->users->bulkApplyTemplate([
    'template_id' => 5,
    'usernames'   => ['a', 'b', 'c'],
]);

// Update an existing user so it matches a template
$api->users->updateWithTemplate('jane_doe', ['template_id' => 5]);
$api->users->updateWithTemplateByUsername('jane_doe', ['template_id' => 5]);
$api->users->updateWithTemplateById(42, ['template_id' => 5]);

// Login: returns a bearer token for the admin
$login = $api->admins->getToken([
    'username' => 'reseller_3',
    'password' => 's3cret',
]);
$bearer = $login['access_token'];

// Telegram Mini App login (validateData from Telegram init payload)
$miniApp = $api->admins->getMiniAppToken([
    'init_data' => '<telegram_web_app_init_data>',
]);

// Create a new admin / reseller
$api->admins->create([
    'username'    => 'reseller_4',
    'password'    => 's3cret',
    'is_sudo'     => false,
    'users'       => [],
]);

// Update
$api->admins->update('reseller_4', ['is_sudo' => true]);
$api->admins->updateByUsername('reseller_4', ['password' => 'newpass']);
$api->admins->updateById(7, ['is_sudo' => false]);

// Delete
$api->admins->delete('reseller_4');
$api->admins->deleteByUsername('reseller_4');
$api->admins->deleteById(7);

$all      = $api->admins->list();
$simple   = $api->admins->listSimple();
$usage    = $api->admins->getUsage('reseller_4');
$usage    = $api->admins->getUsageByUsername('reseller_4');
$usage    = $api->admins->getUsageById(7);

// Disable / activate / delete every user owned by an admin
$api->admins->disableUsers('reseller_4');
$api->admins->disableUsersByUsername('reseller_4');
$api->admins->disableUsersById(7);

$api->admins->activateUsers('reseller_4');
$api->admins->activateUsersByUsername('reseller_4');
$api->admins->activateUsersById(7);

$api->admins->deleteUsers('reseller_4');
$api->admins->deleteUsersByUsername('reseller_4');
$api->admins->deleteUsersById(7);

// Reset usage of every user owned by an admin
$api->admins->resetUsage('reseller_4');
$api->admins->resetUsageByUsername('reseller_4');
$api->admins->resetUsageById(7);

$api->admins->bulkDelete(['usernames' => ['r1', 'r2']]);
$api->admins->bulkReset(['usernames' => ['r1', 'r2']]);
$api->admins->bulkDisable(['usernames' => ['r1', 'r2']]);
$api->admins->bulkEnable(['usernames' => ['r1', 'r2']]);
$api->admins->bulkDisableUsers(['usernames' => ['r1', 'r2']]);
$api->admins->bulkActivateUsers(['usernames' => ['r1', 'r2']]);
$api->admins->bulkDeleteUsers(); // no body — deletes ALL users of EVERY admin

// List all roles
$roles = $api->adminRoles->list();
$simple = $api->adminRoles->listSimple();

// Get a role
$role = $api->adminRoles->get(1);

// Create a role
$api->adminRoles->create([
    'name'        => 'Support Agent',
    'permissions' => ['users:read', 'users:reset'],
    'color'       => '#3b82f6',
]);

// Update / delete
$api->adminRoles->update(1, ['name' => 'Senior Support']);
$api->adminRoles->delete(1);

// Node settings + usage
$settings = $api->nodes->getSettings();
$usage    = $api->nodes->getUsage();
$counts   = $api->nodes->getUserCountMetric('online');

// List
$nodes    = $api->nodes->list();
$simple   = $api->nodes->listSimple();

// Reconnect every node at once
$api->nodes->reconnectAll();

// Create
$api->nodes->create([
    'name'       => 'de-fra-01',
    'address'    => '203.0.113.10',
    'port'       => 62050,
    'api_port'   => 62051,
]);

// Inspect / mutate one node
$node = $api->nodes->get(1);
$api->nodes->update(1, ['name' => 'de-fra-01-renamed']);

// Software / core / geofiles update
$api->nodes->updateNode(1);
$api->nodes->updateCore(1);
$api->nodes->updateGeofiles(1);

// Reset usage, reconnect, sync
$api->nodes->resetUsage(1);
$api->nodes->reconnect(1);
$api->nodes->sync(1, ['force' => true]);

// Logs and periodic stats
$logs  = $api->nodes->getLogs(1, ['limit' => 100]);
$stats = $api->nodes->getStatsPeriodic(1, ['interval' => '1h']);

// Delete
$api->nodes->delete(1);

// CRUD
$api->cores->create(['name' => 'Xray 1.8.24', 'version' => '1.8.24', 'type' => 'xray']);
$core = $api->cores->get(1);
$api->cores->update(1, ['version' => '1.8.25']);
$api->cores->delete(1);

// List
$all    = $api->cores->list();
$simple = $api->cores->listSimple();

// Restart the core on every node that uses it
$api->cores->restart(1);

// Bulk delete
$api->cores->bulkDelete(['ids' => [1, 2, 3]]);

// CRUD
$api->hosts->create([
    'remark' => 'CDN Host',
    'address' => 'cdn.example.com',
    'port' => 443,
    'sni' => 'cdn.example.com',
    'host' => 'cdn.example.com',
    'inbound_tag' => 'V2RAY-NG',
]);
$api->hosts->get(1);
$api->hosts->update(1, ['address' => 'cdn2.example.com']);
$api->hosts->delete(1);

// List / update all / bulk ops
$all = $api->hosts->list();
$api->hosts->updateAll(['mux' => false]);
$api->hosts->bulkDelete(['ids' => [1, 2, 3]]);
$api->hosts->bulkDisable(['ids' => [1, 2, 3]]);
$api->hosts->bulkEnable(['ids' => [1, 2, 3]]);

$api->groups->create(['name' => 'Premium Users']);
$api->groups->list();
$api->groups->listSimple();
$api->groups->get(1);
$api->groups->update(1, ['name' => 'Premium Plus']);
$api->groups->delete(1);

// Add / remove users
$api->groups->bulkAdd(['group_id' => 1, 'usernames' => ['a', 'b']]);
$api->groups->bulkRemove(['group_id' => 1, 'usernames' => ['a']]);

// Bulk disable / enable
$api->groups->bulkDisable(['ids' => [1, 2]]);
$api->groups->bulkEnable(['ids' => [1, 2]]);
$api->groups->bulkDelete(['ids' => [1, 2]]);

// List HWID locks of a user
$api->hwids->get(42);

// Delete a single HWID lock
$api->hwids->delete(42, 'hwid-string-from-client');

// Reset (clear) all HWID locks for a user
$api->hwids->reset(42, []);

// Get the auto-detected subscription content for a token
$api->subscriptions->get('subscription-token-here');

// Informational page (used by the panel's web UI)
$api->subscriptions->getInfo('subscription-token-here');

// Raw subscription (plain-text list of links)
$api->subscriptions->getRaw('subscription-token-here');

// App store / download page links
$api->subscriptions->getApps('subscription-token-here');

// Subscription usage statistics
$api->subscriptions->getUsage('subscription-token-here');

// Subscription content for a SPECIFIC client type (v2rayNG, Streisand, ...)
$api->subscriptions->getWithClientType('subscription-token-here', 'v2rayNG');

$client = new Client(
    baseUrl: 'https://panel.example.com',
    token:  '...',
    subscriptionPath: '/custom-sub',
);

$api->userTemplates->create([
    'name'       => 'Basic 10GB / 30d',
    'data_limit' => 10737418240,
    'duration'   => 2592000, // seconds
]);
$api->userTemplates->list();
$api->userTemplates->listSimple();
$api->userTemplates->get(1);
$api->userTemplates->update(1, ['name' => 'Basic 20GB / 30d']);
$api->userTemplates->delete(1);

$api->userTemplates->bulkDelete(['ids' => [1, 2]]);
$api->userTemplates->bulkDisable(['ids' => [1, 2]]);
$api->userTemplates->bulkEnable(['ids' => [1, 2]]);

$api->clientTemplates->create([
    'name'        => 'v2rayNG Default',
    'client_type' => 'v2rayNG',
    'body'        => '<config-template>',
]);
$api->clientTemplates->get(1);
$api->clientTemplates->list();
$api->clientTemplates->listSimple();
$api->clientTemplates->update(1, ['body' => '<updated-template>']);
$api->clientTemplates->delete(1);
$api->clientTemplates->bulkDelete(['ids' => [1, 2]]);

$all      = $api->settings->get();
$general  = $api->settings->getGeneral();

$api->settings->update([
    'telegram_bot_token' => '...',
    'captcha'            => ['enabled' => true, 'site_key' => '...'],
]);

$system       = $api->system->getStats();        // /api/system
$resources    = $api->system->getResourceStats();// /api/system/resources
$usersStats   = $api->system->getUsersStats();   // /api/system/users
$inbounds     = $api->system->getInbounds();     // /api/inbounds
$inboundDetails = $api->system->getInboundDetails();
$workersHealth  = $api->system->getWorkersHealth();

// First-run: create the panel owner (sudo admin)
$api->setup->createOwner([
    'username'   => 'root',
    'password'   => '...',
    'telegram_id'=> null,
]);

// Reset the owner's password
$api->setup->resetOwnerPassword(['password' => '...']);

// Upgrade the owner to a higher role (panel migrations)
$api->setup->upgradeOwner(['confirm' => true]);

// Delete the owner entirely (irreversible)
$api->setup->deleteOwner();

$health = $api->home->health();
// 200 OK -> {"status":"healthy"} typically


Pooshgan\PasarGuard\Client;
use Pooshgan\PasarGuard\PasarGuard;
use Pooshgan\PasarGuard\Exceptions\PasarGuardException;

$client = new Client('https://panel.example.com', getenv('PASARGUARD_TOKEN'));
$api    = new PasarGuard($client);

try {
    $result = $api->users->bulkCreateFromTemplate([
        'template_id' => 5,
        'count'       => 100,
        'prefix'      => 'student_',
        'username_pattern' => 'student_{n}',
    ]);

    printf("Created %d users\n", count($result['created']));
    foreach ($result['created'] as $u) {
        printf(" - %s (link: %s)\n", $u['username'], $u['subscription_url']);
    }
} catch (PasarGuardException $e) {
    fprintf(STDERR, "API error %d: %s\n", $e->getCode(), $e->getMessage());
    fprintf(STDERR, "Payload: %s\n", json_encode($e->getErrorData()));
    exit(1);
}


Pooshgan\PasarGuard\Client;
use Pooshgan\PasarGuard\PasarGuard;

$api = new PasarGuard(new Client('https://panel.example.com', getenv('PASARGUARD_TOKEN')));

$expired = $api->users->getExpired(['limit' => 1000]);
$usernames = array_column($expired, 'username');

if (!empty($usernames)) {
    $api->users->bulkDisable(['usernames' => $usernames]);
}

mail(
    '[email protected]',
    'PasarGuard Daily Report',
    sprintf('Disabled %d expired users.', count($usernames))
);


// Telegram Web App sends init_data in the URL fragment or Authorization header.
$initData = $_SERVER['HTTP_X_TELEGRAM_INIT_DATA'] ?? '';

$client = new Client('https://panel.example.com', ''); // no bearer needed for this route
$api    = new PasarGuard($client);

$resp = $api->admins->getMiniAppToken(['init_data' => $initData]);
$token = $resp['access_token']; // use this for subsequent calls as the admin

// Now make a real client with this admin token
$adminApi = new PasarGuard(
    new Client('https://panel.example.com', $token)
);

$me = $adminApi->admins->listSimple();
print_r($me);


$client = new Client(
    baseUrl: 'https://panel.example.com',
    token:  getenv('PASARGUARD_TOKEN'),
    guzzleOptions: [
        'proxy' => 'http://corporate-proxy.local:8080',
        'timeout' => 60,
        'verify'  => false,        // skip SSL verify (e.g., self-signed)
        'headers' => [
            'X-Request-Source' => 'internal-cron',
        ],
    ],
);
$api = new PasarGuard($client);
$users = $api->users->list(['limit' => 500]);

$api->users->list(
    [], // no query
    [
        'X-Telegram-Init-Data' => '<init_data_string>',
        'X-Admin-Username'     => 'reseller_3',
    ]
);

use Pooshgan\PasarGuard\Exceptions\PasarGuardException;

try {
    $api->users->get('non_existent_user');
} catch (PasarGuardException $e) {
    echo $e->getMessage();        // "User not found" (server-provided detail)
    echo $e->getCode();           // 404 (HTTP status)
    print_r($e->getErrorData());  // full decoded JSON body from the server
}

function withRetry(callable $fn, int $maxAttempts = 3): array {
    $attempt = 0;
    while (true) {
        $attempt++;
        try {
            return $fn();
        } catch (PasarGuardException $e) {
            if ($attempt >= $maxAttempts || $e->getCode() < 500 && $e->getCode() !== 429) {
                throw $e;
            }
            usleep(500_000 * (2 ** ($attempt - 1))); // 0.5s, 1s, 2s, ...
        }
    }
}

$users = withRetry(fn () => $api->users->list());

// worker bootstrap (RoadRunner / Swoole / FrankenPHP)
$api = new PasarGuard(new Client(/* ... */));

while ($job = $queue->consume()) {
    $api->users->resetDataUsage($job['username']);
}

$client = new Client(
    baseUrl: 'https://panel.example.com',
    token:  '...',
    guzzleOptions: [
        'connect_timeout' => 5,
        'timeout'         => 30,
        'http_errors'     => false, // already false by default
        'debug'           => fopen('php://stderr', 'w'),
    ],
);

$panelA = new PasarGuard(new Client('https://panel-a.example.com', $tokenA));
$panelB = new PasarGuard(new Client('https://panel-b.example.com', $tokenB));

$usersA = $panelA->users->list();
$usersB = $panelB->users->list();

$client = new Client(
    baseUrl: 'https://panel.example.com',
    token:  '...',
    subscriptionPath: '/custom-sub',
);

$api = new PasarGuard($client);
$api->subscriptions->get('token'); // GET /custom-sub/token

class CustomUser extends \Pooshgan\PasarGuard\Endpoints\User {
    public function createForm(array $formData): array {
        return $this->client->request('POST', $this->pathPrefix, [
            'form_params' => $formData,
        ]);
    }
}

public function __construct(
    string $baseUrl,
    string $token,
    string $subscriptionPath = '/sub',
    array  $guzzleOptions   = [],
)

public function request(string $method, string $uri, array $options = []): array

public function __construct(Client $client)

// Read (no body, optional query + headers)
public function list(array $query = [], array $headers = []): array;

// Mutate (JSON body, optional query + headers)
public function create(array $data = [], array $query = [], array $headers = []): array;

// Mutate with identifier
public function update(string $id, array $data = [], array $query = [], array $headers = []): array;

public function getMessage(): string;       // server-provided detail
public function getCode(): int;             // HTTP status code
public function getErrorData(): array;      // decoded JSON error body
bash
composer 
bash
curl -sS https://getcomposer.org/installer | php
php composer.phar