PHPackages                             csenayeem025/google-workspace-sdk - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. csenayeem025/google-workspace-sdk

ActiveLibrary

csenayeem025/google-workspace-sdk
=================================

Google Workspace API SDK for Laravel

1.0.0(2y ago)06MITPHPPHP ^8.1

Since Oct 10Pushed 3mo agoCompare

[ Source](https://github.com/csenayeem025/google-workspace-sdk)[ Packagist](https://packagist.org/packages/csenayeem025/google-workspace-sdk)[ RSS](/packages/csenayeem025-google-workspace-sdk/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (17)Versions (3)Used By (0)

Google Workspace SDK
====================

[](#google-workspace-sdk)

Overview
--------

[](#overview)

The Google Workspace SDK is an open source [Composer](https://getcomposer.org/) package created by [GitLab IT Engineering](https://about.gitlab.com/handbook/business-technology/engineering/) for use in the [GitLab Access Manager](https://gitlab.com/gitlab-com/business-technology/engineering/access-manager) Laravel application for connecting to Google API endpoints for provisioning and deprovisioning of users, groups, group membership, and other related functionality.

> **Disclaimer:** This is not an official package maintained by the Google or GitLab product and development teams. This is an internal tool that we use in the GitLab IT department that we have open sourced as part of our company values.
>
> Please use at your own risk and create issues for any bugs that you encounter.

Dependencies
------------

[](#dependencies)

**Note:** This package will require the `glamstack/google-auth-sdk` package in order to operate. This is already configured as a required package in the composer.json file and should be automatically loaded when installing this package.

> All configurations for this package by default will be configured under the `glamstack-google-workspace.php` file that will be loaded when this package is installed. For further guidance please see the [Installation docs](#installation)

### Maintainers

[](#maintainers)

NameDevelopers[Dillon Wheeler](https://about.gitlab.com/company/team/#dillonwheeler)[@dillonwheeler](https://gitlab.com/dillonwheeler)[Jeff Martin](https://about.gitlab.com/company/team/#jeffersonmartin)[@jeffersonmartin](https://gitlab.com/jeffersonmartin)[Khurshed Alam Nayem](https://www.nayeem.dev)[@csenayeem025](https://github.com/csenayeem025)### How It Works

[](#how-it-works)

The package utilizes the [glamstack/google-auth-sdk](https://gitlab.com/gitlab-com/business-technology/engineering/access-manager/packages/composer/gitlab-sdk) package for creating the [Google JWT Web Token](https://cloud.google.com/iot/docs/how-tos/credentials/jwts) to authenticate with [Google Workspace API's](https://developers.google.com/admin-sdk/directory/reference/rest#service:-admin.googleapis.com).

For more information on [glamstack/google-auth-sdk](https://gitlab.com/gitlab-com/business-technology/engineering/access-manager/packages/composer/gitlab-sdk) please see the [Google Auth SDK README.md](https://gitlab.com/gitlab-com/business-technology/engineering/access-manager/packages/composer/google-auth-sdk/-/blob/main/README.md).

This package is not intended to provide functions for every endpoint for [Google Workspace API's](https://developers.google.com/admin-sdk/directory/reference/rest#service:-admin.googleapis.com). The endpoints will be constructed on an as needed basis. If you wish to add any additional endpoints please see [CONTRIBUTING](CONTRIBUTING.md).

If the endpoint that you need is not created yet we have provided the REST class that can perform GET, POST, PUT, and DELETE requests to any endpoint that you find in the [Google Workspace API's](https://developers.google.com/admin-sdk/directory/reference/rest#service:-admin.googleapis.com) documentation and the class will handle the API response, error handling, and pagination for you.

> ⚠️ `PATCH` request are not currently working but will be implemented in the future.

> This package builds upon the simplicity of the Laravel HTTP Client that is powered by the Guzzle HTTP client to provide "last lines of code parsing" for [Google Workspace API's](https://developers.google.com/admin-sdk/directory/reference/rest#service:-admin.googleapis.com) responses to improve the developer experience.

```
// Initialized Client with `connection_key` parameter
$google_workspace_api = new \Glamstack\GoogleWorkspace\ApiClient('workspace');

// Retrieves a paginated list of either deleted users or all users in a domain.
// https://developers.google.com/admin-sdk/directory/reference/rest/v1/users/list
$records = $google_workspace_api->rest()->get('https://admin.googleapis.com/admin/directory/v1/users');

// Retrieves a paginated list of either deleted users or all users in a domain
// with query parameters included.
// https://developers.google.com/admin-sdk/directory/reference/rest/v1/users/list
// https://developers.google.com/admin-sdk/directory/reference/rest/v1/users/list#OrderBy
// https://developers.google.com/admin-sdk/directory/v1/guides/search-users
$records = $google_workspace_api->rest()->get('https://admin.googleapis.com/admin/directory/v1/users',[
    'maxResults' => '200',
    'orderBy' => 'EMAIL',
    'query' => [
        'orgDepartment' => 'Test Department'
    ]
]);

// Get a specific user from Google Workspace
// https://developers.google.com/admin-sdk/directory/reference/rest/v1/users/get
$user_key = 'klibby@example.com';
$record = $google_workspace_api->rest()->get('https://admin.googleapis.com/admin/directory/v1/users/'.$user_key);

// Create new Google Workspace User
// https://developers.google.com/admin-sdk/directory/reference/rest/v1/users/insert
// https://developers.google.com/admin-sdk/directory/reference/rest/v1/users#User
$record = $google_workspace_api->rest()->post('https://admin.googleapis.com/admin/directory/v1/users', [
    'name' => [
        'familyName' => 'Libby',
        'givenName' => 'Kate'
    ],
    'password' => 'ac!dBurnM3ss3sWithTheB4$t',
    'primaryEmail' => 'klibby@example.com'
]);

// Update an existing Google Workspace User
// https://developers.google.com/admin-sdk/directory/reference/rest/v1/users/update
$user_key = 'klibby@example.com';
$record = $google_workspace_api->rest()->put('https://admin.googleapis.com/admin/directory/v1/users/'.$user_key, [
    'name' => [
        'givenName' => 'Libby-Murphy'
    ]
]);

// Delete a Google Workspace User
// https://developers.google.com/admin-sdk/directory/reference/rest/v1/users/delete
$user_key = 'klibby@example.com';
$record = $google_workspace_api->rest()->delete('https://admin.googleapis.com/admin/directory/v1/users/'.$user_key);
```

### Package Initialization

[](#package-initialization)

This package is initialized via a configuration see [How To Initialize With Configuration File](#how-to-initialize-with-configuration-file) for instructions on both initialization methods.

Installation
------------

[](#installation)

### Requirements

[](#requirements)

RequirementVersionPHP&gt;=8.1Laravel&gt;=10.0### Add Composer Package

[](#add-composer-package)

This package uses [Calendar Versioning](#calendar-versioning).

We recommend always using a specific version in your `composer.json` file and reviewing the [changelog](changelog/) to see the breaking changes in each release before assuming that the latest release is the right choice for your project.

```
composer require csenayeem025/google-workspace-sdk
```

> If you are contributing to this package, see [CONTRIBUTING](CONTRIBUTING.md) for instructions on configuring a local composer package with symlinks.

### Publish the configuration file

[](#publish-the-configuration-file)

```
php artisan vendor:publish --tag=glamstack-google-workspace
```

### Version upgrades

[](#version-upgrades)

If you have upgraded to a newer version of the package, you should back up your existing configuration file to avoid your custom configuration being overridden.

```
cp config/glamstack-google-workspace.php config/glamstack-google-workspace.php.bak

php artisan vendor:publish --tag=glamstack-google-workspace
```

### Calendar Versioning

[](#calendar-versioning)

The GitLab IT Engineering team uses a modified version of [Calendar Versioning (CalVer)](https://calver.org/) instead of [Semantic Versioning (SemVer)](https://semver.org/). CalVer has a YY (Ex. 2021 =&gt; 21) but having a version `21.xx` feels unintuitive to us. Since our team started this in 2021, we decided to use the last integer of the year only (2021 =&gt; 1.x, 2022 =&gt; 2.x, etc).

The version number represents the release date in `vY.M.D` format.

#### Why We Don't Use Semantic Versioning

[](#why-we-dont-use-semantic-versioning)

1. We are continuously shipping to `main`/`master`/`production` and make breaking changes in most releases, so having semantic backwards-compatible version numbers is unintuitive for us.
2. We don't like to debate what to call our release/milestone and whether it's a major, minor, or patch release. We simply write code, write a changelog, and ship it on the day that it's done. The changelog publication date becomes the tagged version number (Ex. `2022-02-01` is `v2.2.1`). We may refer to a bigger version number for larger releases (Ex. `v2.2`), however this is only for monthly milestone planning and canonical purposes only. All code tags include the day of release (Ex. `v2.2.1`).
3. This allows us to automate using GitLab CI/CD to automate the version tagging process based on the date the pipeline job runs.
4. We update each of our project `composer.json` files that use this package to specific or new version numbers during scheduled change windows without worrying about differences and/or breaking changes with "staying up to date with the latest version". We don't maintain any forks or divergent branches.
5. Our packages use underlying packages in your existing Laravel application, so keeping your Laravel application version up-to-date addresses most security concerns.

Initializing the SDK
--------------------

[](#initializing-the-sdk)

Initialization of the API Client can be done either by passing in a (string) [connection\_key](#connection-keys) or by passing in an (array) [connection\_config](#dynamic-connection-config-array)

### Google API Authentication

[](#google-api-authentication)

The package utilizes the [glamstack/google-auth-sdk](https://gitlab.com/gitlab-com/business-technology/engineering/access-manager/packages/composer/google-auth-sdk) package for creating the [Google JWT Web Token](https://cloud.google.com/iot/docs/how-tos/credentials/jwts) to authenticate with [Google Cloud API endpoints](https://cloud.google.com/apis).

For more information on [glamstack/google-auth-sdk](https://gitlab.com/gitlab-com/business-technology/engineering/access-manager/packages/composer/google-auth-sdk) please see the [Google Auth SDK README.md](https://gitlab.com/gitlab-com/business-technology/engineering/access-manager/packages/composer/google-auth-sdk/-/blob/main/README.md).

### Connection Keys

[](#connection-keys)

We use the concept of ***connection keys*** that refer to a configuration array in `config/glamstack-google-workspace.php` that allows you to pre-configure one or more API connections.

Each connection key is associated with a GCP service account JSON key. This can be used to configure different auth scope connections and permissions to your GCP organization or different GCP project(s) depending on the API calls that you're using. This allows for least privilege for specific API calls, and you can also configure multiple connections with the same GCP project and different API tokens that have different permission levels.

#### Example Connection Key Initialization

[](#example-connection-key-initialization)

```
// Initialize the SDK using the `test` configuration from `glamstack-google-workspace.php`
$client = new Glamstack\GoogleWorkspace\ApiClient('test');
```

#### Example Connection Key Configuration

[](#example-connection-key-configuration)

```
return [
    'connections' => [
        'test' => [
            'api_scopes' => [
                'https://www.googleapis.com/auth/admin.directory.group',
                'https://www.googleapis.com/auth/admin.directory.user'
            ],
            'json_key_file_path' => storage_path(env('GOOGLE_WORKSPACE_TEST_JSON_KEY_FILE_PATH')),
            'log_channels' => ['single'],
            'customer_id' => env('GOOGLE_WORKSPACE_TEST_CUSTOMER_ID'),
            'domain' => env('GOOGLE_WORKSPACE_TEST_DOMAIN'),
            'subject_email' => env('GOOGLE_WORKSPACE_TEST_SUBJECT_EMAIL'),
            'test_group_email' => env('GOOGLE_WORKSPACE_TEST_GROUP_EMAIL')
        ],
    ]
]
```

### Dynamic Connection Config Array

[](#dynamic-connection-config-array)

If you don't want to pre-configure your connection and prefer to dynamically use connection variables that are stored in your database, you have the ability to pass in the required configurations via an array (See [Example Connection Config Array Initialization](#example-connection-config-array-initialization)) using the `connection_config` array in the second argument of the `ApiClient` construct method.

#### Required Parameters

[](#required-parameters)

KeyTypeDescription`api_scopes`arrayArray of the API Scopes needed for the APIs to be used`customer_id`stringThe Google Workspace Customer ID`domain`stringThe Google Workspace Domain the APIs will be used in`json_key_file_path`stringOption 1 - Provide a file path to the `.json` key file`json_key`stringOption 2 - Provide the JSON key contents stored in your database#### Using a JSON Key File on your filesystem

[](#using-a-json-key-file-on-your-filesystem)

```
$client = new Glamstack\GoogleWorkspace\ApiClient(null, [
    'api_scopes' => [
        'https://www.googleapis.com/auth/admin.directory.group',
        'https://www.googleapis.com/auth/contacts'
    ],
    'customer_id' => config('tests.connections.test.customer_id'),
    'domain' => config('tests.connections.test.domain'),
    'json_key_file_path' => storage_path('keys/glamstack-google-workspace/test.json'),
    'log_channels' => ['single'],
    'subject_email' => config('tests.connections.test.subject_email')
]);
```

#### Using a JSON Key String in your database

[](#using-a-json-key-string-in-your-database)

**Security Warning:** You should never commit your service account key (JSON contents) into your source code as a variable to avoid compromising your credentials for your GCP organization or projects.

It is recommended to convert the JSON key to a base 64 encoded string before encryption since this is the format used by the GCP Service Account API for the `privateKeyData` field.

```
// Get service account from your model (`GoogleServiceAccount` is an example)
$service_account = \App\Models\GoogleServiceAccount::where('id', '123456')->firstOrFail();

// Get JSON key string from database column that has an encrypted value
$json_key_string = decrypt(json_decode($service_account->json_key));

$client = new \Glamstack\GoogleWorkspace\ApiClient(null, [
    'api_scopes' => [
        'https://www.googleapis.com/auth/admin.directory.group',
        'https://www.googleapis.com/auth/contacts'
    ],
    'customer_id' => config('tests.connections.test.customer_id'),
    'domain' => config('tests.connections.test.domain'),
    'json_key' => $json_key_string,
    'log_channels' => ['single'],
    'subject_email' => config('tests.connections.test.subject_email')
]);
```

The example below shows the value of the JSON key that is stored in your database.

```
// Get service account from your model (`GoogleServiceAccount` is an example)
$service_account = \App\Models\GoogleServiceAccount::where('id', '123456')->firstOrFail();

dd(decrypt(json_decode($service_account->json_key));
// {
//     "type": "service_account",
//     "project_id": "project_id",
//     "private_key_id": "key_id",
//     "private_key": "key_data",
//     "client_email": "xxxxx@xxxxx.iam.gserviceaccount.com",
//     "client_id": "123455667897654",
//     "auth_uri": "https://accounts.google.com/o/oauth2/auth",
//     "token_uri": "https://oauth2.googleapis.com/token",
//     "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
//     "client_x509_cert_url": "some stuff"
// }
```

### Custom Logging Configuration

[](#custom-logging-configuration)

By default, we use the `single` channel for all logs that is configured in your application's `config/logging.php` file. This sends all Google Workspace log messages to the `storage/logs/laravel.log` file.

If you would like to see Google Workspace logs in a separate log file that is easier to triage without unrelated log messages, you can create a custom log channel. For example, we recommend using the value of `glamstack-google-workspace`, however you can choose any name you would like.

Add the custom log channel to `config/logging.php`.

```
    'channels' => [
        // Add anywhere in the `channels` array
        'glamstack-google-workspace' => [
            'name' => 'glamstack-google-workspace',
            'driver' => 'single',
            'level' => 'debug',
            'path' => storage_path('logs/glamstack-google-workspace.log')
        ]
    ],
```

Update the `channels.stack.channels` array to include the array key (ex. `glamstack-google-workspace`) of your custom channel. Be sure to add `glamstack-google-workspace` to the existing array values and not replace the existing values.

```
    'channels' => [
        'stack' => [
            'driver' => 'stack',
            'channels' => [
                'single','slack', 'glamstack-google-workspace'
            ],
            'ignore_exceptions' => false
        ]
    ],
```

REST API Request
----------------

[](#rest-api-request)

You can make an API request to any of the resource endpoints in the [Google Workspace Admin SDK Directory Documentation](https://developers.google.com/admin-sdk/directory/reference/rest).

### Inline Usage

[](#inline-usage)

```
// Initialize the SDK
$api_client = new \Glamstack\GoogleWorkspace\ApiClient('workspace');
$response = $api_client->rest()->get('https://admin.googleapis.com/admin/directory/v1/users');
```

### GET Request

[](#get-request)

The endpoints when uiltizing the REST class will require the full URL of the endpoint.

For examples, the [List Google Workspace Users](https://developers.google.com/admin-sdk/directory/reference/rest/v1/users/list) API Documentation shows the endpoint

```
GET https://admin.googleapis.com/admin/directory/v1/users
```

With the SDK, you use the get() method with the endpoint for [Google Workspace Users](https://developers.google.com/admin-sdk/directory/reference/rest/v1/users/get).

```
$google_workspace_api->rest()->get('https://admin.googleapis.com/admin/directory/v1/users');
```

You can also use variables or database models to get data for constructing your endpoints.

```
$endpoint = 'https://admin.googleapis.com/admin/directory/v1/users';
$records = $google_workspace_api->rest()->get($endpoint);
```

Here are some more examples of using endpoints.

```
// Get a list of Google Workspace Users
// https://developers.google.com/admin-sdk/directory/reference/rest/v1/users/list
$records = $google_workspace_api->rest()->get('https://admin.googleapis.com/admin/directory/v1/users');

// Get a specific Google Workspace User
// https://developers.google.com/admin-sdk/directory/reference/rest/v1/users/get
$user_key = 'klibby@example.com';
$record = $google_workspace_api->get('https://admin.googleapis.com/admin/directory/v1/users/' . $userKey);
```

### GET Requests with Query String Parameters

[](#get-requests-with-query-string-parameters)

The second argument of a `get()` method is an optional array of parameters that is parsed by the SDK and the [Laravel HTTP Client](https://laravel.com/docs/8.x/http-client#get-request-query-parameters) and rendered as a query string with the `?` and `&` added automatically.

```
// Retrieves a paginated list of either deleted users or all users in a domain
// with query parameters included.
// https://developers.google.com/admin-sdk/directory/reference/rest/v1/users/list
// https://developers.google.com/admin-sdk/directory/reference/rest/v1/users/list#OrderBy
// https://developers.google.com/admin-sdk/directory/v1/guides/search-users
$records = $google_workspace_api->rest()->get('https://admin.googleapis.com/admin/directory/v1/users',[
    'maxResults' => '200',
    'orderBy' => 'EMAIL'
]);

// This will parse the array and render the query string
// https://admin.googleapis.com/admin/directory/v1/users?maxResults='200'&orderBy='EMAIL'
```

### POST Requests

[](#post-requests)

The `post()` method works almost identically to a `get()` request with an array of parameters, however the parameters are passed as form data using the `application/json` content type rather than in the URL as a query string. This is industry standard and not specific to the SDK.

You can learn more about request data in the [Laravel HTTP Client documentation](https://laravel.com/docs/8.x/http-client#request-data).

```
// Create new Google Workspace User
// https://developers.google.com/admin-sdk/directory/reference/rest/v1/users/insert
// https://developers.google.com/admin-sdk/directory/reference/rest/v1/users#User
$record = $google_workspace_api->rest()->post('https://admin.googleapis.com/admin/directory/v1/users', [
    'name' => [
        'familyName' => 'Libby',
        'givenName' => 'Kate'
    ],
    'password' => 'ac!dBurnM3ss3sWithTheB4$t',
    'primaryEmail' => 'klibby@example.com'
]);
```

### PUT Requests

[](#put-requests)

The `put()` method is used for updating an existing record (similar to `PATCH` requests). You need to ensure that the ID of the record that you want to update is provided in the first argument (URI).

In most applications, this will be a variable that you get from your database or another location and won't be hard-coded.

```
// Update an existing Google Workspace User
// https://developers.google.com/admin-sdk/directory/reference/rest/v1/users/update
$user_key = 'klibby@example.com';
$record = $google_workspace_api->rest()->put('https://admin.googleapis.com/admin/directory/v1/users/' . $user_key, [
    'name' => [
        'givenName' => 'Libby-Murphy'
    ]
]);
```

### DELETE Requests

[](#delete-requests)

The `delete()` method is used for methods that will destroy the resource based on the ID that you provide.

Keep in mind that `delete()` methods will return different status codes depending on the vendor (ex. 200, 201, 202, 204, etc). Google Workspace API's will return a `204` status code for successfully deleted resources.

```
// Delete a Google Workspace User
// https://developers.google.com/admin-sdk/directory/reference/rest/v1/users/delete
$user_key = 'klibby@example.com';
$record = $google_workspace_api->rest()->delete('https://admin.googleapis.com/admin/directory/v1/users/' . $user_key);
```

### Class Methods

[](#class-methods)

The examples above show basic inline usage that is suitable for most use cases. If you prefer to use classes and constructors, the example below will provide a helpful example.

```
