PHP code example of brickservers / gsuite

1. Go to this page and download the library: Download brickservers/gsuite 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/ */

    

brickservers / gsuite example snippets


'domain' => env('GOOGLE_WORKSPACE_DOMAIN', 'example.com'),
'credentials_path' => env('GOOGLE_WORKSPACE_CREDENTIALS_PATH', storage_path('credentials.json')),
'subject' => env('GOOGLE_WORKSPACE_SUBJECT'),
'scopes' => [
    'https://www.googleapis.com/auth/admin.directory.user',
    'https://www.googleapis.com/auth/admin.directory.group',
],

use BrickServers\GoogleWorkspace\GoogleWorkspace;

// Via the service container
$workspace = app('google-workspace');

// Via the facade (auto-registered as GSuite)
GSuite::users()->get('[email protected]');
GSuite::asUser('[email protected]')->gmail()->usersLabels()->listUsersLabels('me');

// Or using dependency injection
public function __construct(GoogleWorkspace $workspace)
{
    $this->workspace = $workspace;
}

// Or inject just the repository you need (handy for mocking in tests)
use BrickServers\GoogleWorkspace\Contracts\UsersRepositoryContract;

public function __construct(UsersRepositoryContract $users) { /* ... */ }

use BrickServers\GoogleWorkspace\DTOs\UserDTO;

$user = new UserDTO(
    email: '[email protected]',
    givenName: 'John',
    familyName: 'Doe',
    password: 'SecurePassword123!',
    phone: '+1 555 0100',
    title: 'Engineer',
);

$created = $workspace->users()->create($user);

$user = $workspace->users()->get('[email protected]');

// With projection and view type
use BrickServers\GoogleWorkspace\Enums\UserProjection;
use BrickServers\GoogleWorkspace\Enums\UserViewType;

$user = $workspace->users()->get(
    '[email protected]',
    projection: UserProjection::FULL,
    viewType: UserViewType::ADMIN_VIEW,
);

$result = $workspace->users()->list(maxResults: 100);

$users = $result['users']; // Array of UserDTO
$nextPageToken = $result['nextPageToken']; // For pagination

// Or iterate every user; pages are fetched lazily as you go
foreach ($workspace->users()->all() as $user) {
    echo $user->email;
}

// Change just the first name
$workspace->users()->update('[email protected]', new UserDTO(
    email: '[email protected]',
    givenName: 'Johnny',
));

// Pass an empty email to leave the address alone; false values are sent as-is
$workspace->users()->update('[email protected]', new UserDTO(
    email: '',
    changePasswordAtNextLogin: false,
));

$workspace->users()->delete('[email protected]');

// Suspend
$workspace->users()->suspend('[email protected]');

// Unsuspend
$workspace->users()->unsuspend('[email protected]');

$workspace->users()->makeAdmin('[email protected]');

// Add alias
$workspace->users()->addAlias('[email protected]', '[email protected]');

// Remove alias
$workspace->users()->removeAlias('[email protected]', '[email protected]');

use BrickServers\GoogleWorkspace\DTOs\GroupDTO;

$group = new GroupDTO(
    email: '[email protected]',
    name: 'Development Team',
    description: 'All developers in the organization',
);

$created = $workspace->groups()->create($group);

$group = $workspace->groups()->get('[email protected]');

$result = $workspace->groups()->list(maxResults: 100);

$groups = $result['groups']; // Array of GroupDTO
$nextPageToken = $result['nextPageToken']; // For pagination

// Or iterate every group
foreach ($workspace->groups()->all() as $group) {
    echo $group->email;
}

// Fields left null are not changed
$updates = new GroupDTO(
    email: '[email protected]',
    name: 'Dev Team',
);

$updated = $workspace->groups()->update('[email protected]', $updates);

$workspace->groups()->delete('[email protected]');

// Add member
$workspace->groups()->addMember('[email protected]', '[email protected]');

// Remove member
$workspace->groups()->removeMember('[email protected]', '[email protected]');

use Google\Service\Directory\OrgUnit;

// Org units, roles, domains, devices, schemas, buildings, ... (Directory API)
$workspace->directory()->orgunits()->insert('my_customer', new OrgUnit([
    'name' => 'Engineering',
    'parentOrgUnitPath' => '/',
]));
$roles = $workspace->directory()->roles()->listRoles('my_customer');
$workspace->directory()->users()->signOut('[email protected]');
$workspace->directory()->twoStepVerification()->turnOff('[email protected]');

// Classroom
$courses = $workspace->classroom()->courses()->listCourses(['teacherId' => '[email protected]']);

use Google\Service\Gmail\VacationSettings;

$jane = $workspace->asUser('[email protected]');

$jane->gmail()->usersSettings()->updateVacation('me', new VacationSettings([
    'enableAutoReply' => true,
    'responseSubject' => 'Out of office',
    'responseBodyPlainText' => 'Back on Monday.',
]));
$events = $jane->calendar()->events()->listEvents('primary');
$files = $jane->drive()->files()->listFiles(['pageSize' => 50]);

use Google\Service\Gmail;

$jane = $workspace->asUser('[email protected]', [Gmail::GMAIL_SETTINGS_BASIC, Gmail::GMAIL_SETTINGS_SHARING]);

foreach ($workspace->directory()->mobiledevices()->paginate('listMobiledevices', 'my_customer') as $device) {
    // every device, across all pages
}

foreach ($jane->drive()->files()->paginate('listFiles', ['q' => "mimeType = 'application/pdf'"]) as $file) {
    // ...
}

$batch = $workspace->batch();

$result = $batch->createUsers([$userA, $userB]);
$result = $batch->addGroupMembers('[email protected]', ['[email protected]', '[email protected]']);
$result = $batch->removeGroupMembers('[email protected]', ['[email protected]']);
$result = $batch->suspendUsers(['[email protected]']); // one call per user, so protected users are checked

// ['success' => [...], 'failed' => [['email' => ..., 'error' => ...], ...]]
// createUsers() returns UserDTOs in 'success' and uses a 'user' key in 'failed'

use BrickServers\GoogleWorkspace\Exceptions\GoogleWorkspaceException;

try {
    $workspace->users()->create($user);
} catch (GoogleWorkspaceException $e) {
    if ($e->getCode() === 5) {
        // Resource not found
    } elseif ($e->getCode() === 429) {
        // Still rate limited after automatic retries
    }

    // The original Google error is available for details
    $original = $e->getPrevious();

    logger()->error('Google Workspace API error: ' . $e->getMessage());
}

new UserDTO(
    email: string,
    givenName: ?string = null,
    familyName: ?string = null,
    password: ?string = null,
    changePasswordAtNextLogin: ?bool = null,
    suspended: ?bool = null,
    phone: ?string = null,   // sent as the primary work phone
    title: ?string = null,   // sent as the primary organization title
    customSchemas: ?array = null,
)

new GroupDTO(
    email: string,
    name: ?string = null,
    description: ?string = null,
)

UserProjection::BASIC    // Basic information only
UserProjection::FULL     // Full user information
UserProjection::CUSTOM   // Custom schema information

UserViewType::ADMIN_VIEW      // Admin perspective
UserViewType::DOMAIN_PUBLIC   // Public domain view

ApiScope::DIRECTORY_USER
ApiScope::DIRECTORY_GROUP
ApiScope::CLASSROOM_COURSES
ApiScope::CALENDAR
ApiScope::GMAIL_COMPOSE
ApiScope::DRIVE
// ... and more

GSuite::accounts()->create([
    ['first_name' => 'John', 'last_name' => 'Doe'],
    'email' => '[email protected]',
    'default_password' => 'password'
]);

use BrickServers\GoogleWorkspace\DTOs\UserDTO;

$user = new UserDTO(
    email: '[email protected]',
    givenName: 'John',
    familyName: 'Doe',
    password: 'password',
);

app('google-workspace')->users()->create($user);
bash
php artisan vendor:publish --provider="BrickServers\GoogleWorkspace\GoogleWorkspaceServiceProvider" --tag=config