uncgits/zoom-api-php-library

PHP Library used to interact with the Zoom API for UNCG

1.1 2020-07-31 14:49 UTC

This package is auto-updated.

Last update: 2024-10-29 04:59:30 UTC


README

This package is a PHP library used to interact with the Zoom REST API.

Scope

This package is not (yet) as a comprehensive interface with the Zoom API. If you would like to contribute additional functionality to this library, pull requests are very welcome.

Installation and Quick Start

To install the package: composer require uncgits/zoom-api-php-library

If you are using the built-in Guzzle driver, you will also need to make sure you have Guzzle in your project (version 6 or 7 is supported): composer require guzzlehttp/guzzle. This package does not list Guzzle as a dependency because it is not strictly required (adapters for other HTTP clients are in the plans, and you can always write your own).

Use it!

Create a config object

This library is set up to be flexible. By default the intent is for you to create a Config object per Zoom Account you are interacting with. To do so, create a class in your application that extends Uncgits\ZoomApi\ZoomApiConfig. Then, on __construct(), utilize $this->setApiKey() and $this->setApiSecret() to set up your API credentials. Then, generate a JWT by using $this->refreshToken(), or set your own with $this->setJwt() (for instance, if you are storing it somewhere so as to not need to generate it with every call). Example:

<?php

namespace App\ZoomConfigs;

use Uncgits\ZoomApi\ZoomApiConfig;

class TestAccount extends ZoomApiConfig
{
    public function __construct()
    {
        $this->setApiKey('super-secret-key-that-you-would-reference-from-a-non-committed-file-of-course'); // please don't commit your keys...
        $this->setApiSecret('super-secret-key-that-you-would-reference-from-a-non-committed-file-of-course'); // please don't commit your keys...

        // Then...

        // generate a token from Firebase library
        $jwt = $this->refreshToken();
        // OR, set one yourself:

        // ... code that fetches a stored token value from a database or something...
        $this->setJwt('your-stored-token-value');

        // more likely, you'll write your own method here that calls either $this->refreshToken() or $this->setJwt() depending on whether you determine you need a new token. that logic is up to you!
    }
}

Instantiate the ZoomApi class

  1. Choose the Client you want (found in Uncgits\ZoomApi\Clients), based on the type of call(s) you want to make.

  2. Then, choose the Adapter you want to use for the HTTP interaction (found in Uncgits\ZoomApi\Adapters).

By default, the Guzzle adapter is available with this package (You can write your own; more later).

  1. Finally, choose the Config you want to use.

  2. Instantiate the Uncgits\ZoomApi\ZoomApi class, and pass in the above three objects either using a constructor array, or the setter methods:

// OPTION 1 - array in constructor

// instantiate a client
$meetingsClient = new \Uncgits\ZoomApi\Clients\Meetings;
// instantiate an adapter
$adapter = new \Uncgits\ZoomApi\Adapters\Guzzle;
// instantiate a config
$config = new App\ZoomConfigs\TestAccount;

// pass as array to API class
$api = new \Uncgits\ZoomApi\ZoomApi([
    'client' => $meetingsClient,
    'adapter' => $adapter,
    'config' => $config,
]);

// OPTION 2 - use setters

// instantiate a client
$meetingsClient = new \Uncgits\ZoomApi\Clients\Meetings;
// instantiate an adapter
$adapter = new \Uncgits\ZoomApi\Adapters\Guzzle;
// instantiate a config
$config = new App\ZoomConfigs\TestAccount;

// instantiate API class
$api = new \Uncgits\ZoomApi\ZoomApi;
$api->setClient($meetingsClient);
$api->setAdapter($adapter);
$api->setConfig($config);

Or, take the shortcut and instead pass the class names using either of the methods above:

// OPTION 1 - pass class names

use \Uncgits\ZoomApi\Clients\Meetings;
use \Uncgits\ZoomApi\Adapters\Guzzle;
use App\ZoomConfigs\TestAccount;

// instantiate the API class and pass in the array using class names
$api = new \Uncgits\ZoomApi\ZoomApi([
    'client' => Meetings::class,
    'adapter' => Guzzle::class,
    'config' => TestAccount::class,
]);
// OPTION 2 - use setters
use \Uncgits\ZoomApi\Clients\Meetings;
use \Uncgits\ZoomApi\Adapters\Guzzle;
use App\ZoomConfigs\TestAccount;

$api = new \Uncgits\ZoomApi\ZoomApi;
$api->setClient(new Meetings);
$api->setAdapter(new Guzzle);
$api->setConfig(new TestAccount);

Then, once you have the client, if you want to list all Meetings for user@domain.com:

// make the call
$result = $api->listMeetings('user@domain.com'); // methods are named simply based on the operation being performed
var_dump($result); // you receive a ZoomApiResult object
var_dump($result->getContent()); // use getContent() to get the meaningful content of the response

Client fluent shortcut

You may want to use a different Client while maintaining the same Adapter and Config. You can do this permanently by using the setClient() on the API class, or you can do it for a single transaction using the fluent using() chainable method.

using() will accept a complete class name (with namespace) for a Client class, or a simplified class name for a built-in Client class, like 'groups' or 'signupforms'.

use Uncgits\ZoomApi\Clients\Groups;
use Uncgits\ZoomApi\Clients\Meetings;
use Uncgits\ZoomApi\Adapters\Guzzle;
use App\ZoomConfigs\TestAccount;

$api = new \Uncgits\ZoomApi\ZoomApi([
    'client' => Meetings::class,
    'adapter' => Guzzle::class,
    'config' => TestAccount::class,
]);

// API class will use Meetings client.
$api->listMeetings('user@domain.com');

// use explicit setter - now API class will use Groups client for all future calls
$api->setClient(Groups::class);
$api->listGroups();
$api->getGroup(123); // still Groups client

// OR, use fluent setter with explicit class
$api->using(Groups::class)->listGroups();
$api->listMeetings('user@domain.com'); // defaults back to original Meetings Client

// OR, fluent setter with implied class (from default library)
$api->using('groups')->listGroups();
$api->listMeetings('user@domain.com'); // defaults back to Meetings Client

Setting parameters

Some API calls need additional parameters, and there are two different ways to pass them. The way(s) you choose are directly in line with the following logic:

  • If the parameter belongs in the URL, it will be required as an argument to the method call. Example: getGroup() calls api/v2/groups/{groupId}, where groupId is the ID of the group you are requesting. Therefore, the signature for the method is getGroup($groupId), and you would pass in your ID value there.

  • If the parameter is not contained in the URL, you need to set it as a body parameter. This includes all required parameters as well as optional parameters. Example: listMeetings($userId) requires the $userId as part of the URL (thus requires it as a method parameter), but you may also optionally provide the type parameter to the call (among others - refer to Zoom API docs). To do this, use the chainable addParameters() method on the client object like so:

$parameters = [
    'type' => 'past',
];

$result = $meetingsClient->addParameters($parameters)->listMeetings('user@domain.com');

Refer to the API documentation for the accepted parameters, as well as the structure of the parameters (especially for multi-level nested parameters), for each specific API call. This library has scaffolding built for parameter validation (to ensure parameters are valid for the endpoint being called), but currently does not perform the validation (PR anyone?).

Laravel wrapper

This package has a dedicated wrapper package for Laravel, that includes container bindings, facades, config files, adapters, and other utilities to help you use this package easily within a Laravel application.

Detailed Usage

Architecture

General Architecture

This library is comprised of many Clients, each of which interacts with one specific category / area of the Zoom API. For instance, there is a Quizzes client, an Meetings client, a Users client, and so on. Each client class is based fully on its architecture in the Zoom API Documentation. All client classes implement the Uncgits\ZoomApi\Clients\ZoomApiClientInterface interface, which is currently an empty interface but helps to identify each Client as a "valid" Client (so you can build your own). The job of a Client is to return an array that can be parsed into a ZoomApiEndpoint object, which requires an endpoint string, HTTP method string, and optional array of required parameters for the call to that Zoom API method.

Adapter classes are basically abstracted HTTP request handlers. They worry about structuring and making API calls to Zoom, handling pagination as necessary, and formatting the response in a simple, structured way (using a ZoomApiResult object). These Adapter classes implement the Uncgits\ZoomApi\Adapters\ZoomApiAdapterInterface interface. At the time of initial release, only an adapter for Guzzle is included - however, more will be added later, and you can always write your own to use your PHP HTTP library of choice. (Or straight cURL. Nobody's judging.) Adapters technically exist as properties on the Client class.

Config classes are classes that configure basic things that the adapter needs to know about in order to interact with the Zoom API. No concrete classes are included in this package - only the abstract ZoomApiConfig class. The purpose for this architecture is so that you can create several classes to support different Zoom environments or accounts.

The Master API class is essentially the "traffic controller" class, that worries about making sure the separate components (Client, Adapter, Config) know everything they need to know in order to execute the API call. This class exists as such so that it can be extended as needed. Basically, when asked to make a call, the API class should know everything about what is required to make said API call, including the Client, Adapter, and Config that are being used, the endpoint and method, and so on, making it easy to leverage this class for informational purposes (such as logging or caching... see the Laravel wrapper package for an example).

Naming

Each client's methods are named as fluently as possible based on the name and operation of the method according to API documentation. General terms used in naming attempt to mirror RESTful operations, such as list for retrieving multiple records, get for retrieving single records, and so on. For example, the Groups client contains methods like listGroups(), createGroups(), and so on.

Aliasing

Where prudent, additional methods are defined on the client classes to help with additional flexibility. For instance, Zoom's API documentation contains a GET method for listing members of a group. The main method is listGroupMembers($groupId), but you can also use the listMembers($groupId) alias, since it's implied that you're running this on a Group (since you're using the Groups client).

Pagination

Pagination is handled automatically, where and when necessary, at the adapter level.

The default number of records to retrieve per page is set at the preconfigured default of 500. To customize pagination on any API call, you may utilize setPerPage() on the config class.

Because of the way pagination is handled, each client transaction may initiate several API calls before it reaches completion. See below for details on how results are presented.

Handling Results

Every time a client transaction is requested, this library will encapsulate important information and present it in the Uncgits\ZoomApi\ZoomApiResult class. Within that class, you are able to access structured information on each API call made during that transaction, as well as an aggregated resultset that should be iterable as an array. For example, if you ask for all Meetings, and it requires 5 API calls of retrieve all pages of results, your result contents would be a single array of all accounts; this is designed to save you time in parsing them yourself!

$result = $api->listMeetings('user@domain.com');

// get the result content - all of your Meeting objects from this series of paginated calls
$accounts = $result->getContent();
$accounts = $result->content(); // alias

// get a list of the API calls made
$apiCalls = $result->getCalls();
// get the first API call made
$firstCall = $result->getFirstCall();
// get the last API call made
$lastCall = $result->getLastCall();

// get the aggregate status code (success or failure) based on the result of all calls
$status = $result->getStatus();
$status = $result->status(); // alias
// get the aggregate message (helpful if there were failures) based on the result of all calls
$status = $result->getMessage();
$status = $result->message(); // alias

The API call array

Each API call (retrieved from the $calls array on the ZoomApiResult object) is made up of some key information that may be useful as you deal with things like throttling (see below), or other meta information on your calls. The API call array stores information on both the request (what is sent) and the response (what is received), and is structured as follows:

[
    'request' => [
        'endpoint'   => $endpoint, // the final assembled endpoint
        'query'      => $requestOptions['query'] ?? '', // query parameters
        'method'     => $method, // get, post, put, delete
        'headers'    => $requestOptions['headers'] ?? '', // all headers passed - includes bearer info
        'proxy'      => $this->config->getProxy(), // proxy host and port, if using
        'parameters' => $this->parameters, // any parameters used by the client,
        'entity'     => $this->entity, // entity name used to determine key for paginated requests
    ],
    'response' => [
        'headers'              => $response->getHeaders(), // raw headers
        'code'                 => $response->getStatusCode(), // 200, 403, etc.
        'reason'               => $response->getReasonPhrase(), // OK, Forbidden, etc.
        'body'                 => json_decode($response->getBody()->getContents()) // raw body content of the response
    ],
]

Rate limit / throttling

This library does not account for Rate Limit, Throttling, or automatic retries / exponential backoff. Most of the time, those issues are only encountered when running scripts that would invoke simultaneous API calls, and will not be a problem even when paginating through a large dataset. Be aware that Zoom's Rate Limit thresholds vary per-request. Documentation link.

In short, this library is meant to act simply as an interface to the Zoom REST API; it does not need to be concerned about how it is being used in client applications. Thus, account for rate limits is your responsibility, and you should take care to handle this in your application code. You'll receive the standard HTTP 429 with "Rate Limit Exceeded" message if this becomes a problem, and you can check this with ->getLastCode() on the ZoomApiResult object.

Using a proxy

If you need to use an HTTP proxy, set that up in your ZoomApiConfig object using setProxyHost(), setProxyPort(), and useProxy().

Passing additional headers

If you need to set additional headers on your requests, you can utilize the setAdditionalHeaders() method on the client class, which accepts an array of key-value pairs.

Writing your own Adapters

An adapter is responsible for everything involved in the actual interaction with the Zoom API. The Adapter's responsibilities include:

  • assembling the call endpoint, headers, parameters, body, and other options
  • making the proper HTTP request
  • parsing the response
  • reading pagination headers and determining whether another call is necessary to fulfill the requested transaction
  • reporting errors
  • collating results into a single array
  • recording all calls made in a transaction.

The ZoomApiAdapterInterface interface shows how an adapter should be implemented. Most of the basic methods in that interface (setters, getters, convenience aliases, etc.) are implemented for you in the ExecutesApiCalls trait, so generally speaking you should use that trait as a good first step. (Of course you can always override methods on the Trait if you prefer.)

On each adapter, therefore, that leaves you to implement the following methods on your own:

  • call()
  • transaction()
  • parsePagination()
  • normalizeResult()

Writing your own Clients

All Clients are implementations of the ZoomApiClientInterface class, and passed in explicitly to the API object - and therefore writing your own Client classes is possible. There is no concrete implementation required by this interface class at this time...you can begin writing your custom Client anytime!.

Theoretically this API library will be complete at some point, and so writing custom Clients won't be necessary, but as this library is still growing it is possible that some API functionality is missing, and you'll want to fill gaps yourself. If you do, please consider creating a pull request to add your adapter to this repo!

Extending the API class

If you need additional functionality like logging or caching, you can write your own ZoomApi wrapper class that extends this ZoomApi class. The most common use cases would be to set some default values for the Config and Adapter classes, perhaps in the constructor, or to override the execute() method to perform additional operations before the transaction is kicked off or after it is finished.

Contributing

Please feel free to submit a pull request to this package to help improve its coverage of the Zoom API, and/or to add Adapters or fix issues. The package was initially built to serve the needs of UNC Greensboro's immediate needs around Zoom integration, ad hoc, and is therefore not yet comprehensive.

License

See the LICENSE file for license rights and limitations (BSD).

Questions? Concerns?

Please use the Issue Tracker on this repository for reporting bugs. For security-related concerns, please contact its-laravel-devs-l@uncg.edu directly instead of using the Issue Tracker.

Version History

1.1

  • Readme overhaul with better examples and cleanup
  • Moves JWT generation from the Laravel wrapper to this library, using firebase/jwt-php

1.0.1

  • Adds BSD license info to composer.json

1.0

  • Official open source licensing

0.4.5

  • adds Billing client

0.4.4

  • adds Accounts client
  • adds more methods to Users client

0.4.3

  • adds Webinars client

0.4.2

  • adds listRecordingsOfAccount() method to CloudRecording client.

0.4.1

  • fix for pagination where next_page_token is used
  • adds removeParameter() method to ExecutesZoomApiCalls trait

0.4

  • adds fluent aliases for most methods on ZoomApiResult class
  • fix for pagination on GET calls with parameters

0.3

  • Adds:
    • Cloud Recording
    • Reports
  • Tweaks:
    • Dashboards
  • further refining of pagination, including manual setting of entity name, and better handling of paginated vs. single content

0.2.1

  • support for token refreshing

0.2

  • Meetings client
  • Dashboard client

0.1.1

  • change to PSR-4 declaration since we were already following it

0.1

  • Ported over from Emma API PHP Library (apologies for lingering references to Emma / mass mailing)
  • First tagged release
  • Basic implementation of the following operation sets (not all fully tested):
    • Users
    • Groups