Tập tành to Create a Meeting on Zoom using Zoom API and PHP

29th Jun 2022
Table of contents

Zoom is a platform that is used for teleconferencing, telecommuting, distance education, etc. It is popular among people for online conferences, meetings, webinars, and other stuff.

Recently I was working on a client project where I needed to interact with the Zoom API. In the application, we implemented a lot of stuff using Zoom API like Accounts, Billing, Meetings, Groups, Reports, Rooms, etc. Though we did a lot of stuff using the Zoom API, this video will focus on how to create a meeting using Zoom API and PHP.

As we all know, Zoom is a platform that is used for teleconferencing, telecommuting, distance education, etc. It is popular among people for online conferences, meetings, webinars, and other stuff.

Those who are looking for creating a meeting through Zoom API need to choose either OAuth or JWT for interacting with their APIs. OAuth and JWT(JSON web token) provide a high level of security to make interactions with the third-party services. In this tutorial, we will use the OAuth process and communicate with the Zoom API through it.

You may also check the tutorial Zoom integration with JWT in PHP.

Create an OAuth App on Zoom

Once you have your Zoom account, you need to create an OAuth app on Zoom using the below steps.

  1. Register your app on Zoom APP Marketplace.
  2. Upon registering an app, you will get your generated credentials. Here you need to pass Redirect URL for OAuth and Whitelist URL.
  3. On the next step, enter the basic information about your app.
  4. In the tab, you can optionally enable some additional features such as Event Subscriptions and Chat Subscriptions for your app.
  5. Under the ‘Scopes’ tab, you need to add scopes regarding your app. For example, you can add a scope for Zoom meetings.

If you are on localhost then use the ngrok and generate the local URL. In my case, ngrok URLs for OAuth redirection and Whitelist URL are as shown below.

App Credentials

If you are facing any issue with creating an OAuth app please refer to Zoom’s official documentation on Create an OAuth App.

Basic Setup and Configuration

I didn’t find any PHP library which can be used to interact with the Zoom API. Doing some research I am able to manage it through the Guzzle library and Zoom REST API. Install the Guzzle library using the command:

composer require guzzlehttp/guzzle

To interact with Zoom REST API requires sending an access token. We are going to generate it and store it in the database. The access token is valid for a short period of time. In our code, we will regenerate the access token in the background so that the user doesn’t need to do the authorization process again.

CREATE TABLE `zoom_oauth` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `provider` varchar(255) NOT NULL,
 `provider_value` text NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

As we will require to fetch token values from the database, we need to write a code for it. Create a file class-db.php and add the code below to it.

class-db.php

<?php
class DB {
    private $dbHost     = "DB_HOST";
    private $dbUsername = "DB_USERNAME";
    private $dbPassword = "DB_PASSWORD";
    private $dbName     = "DB_NAME";
 
    public function __construct(){
        if(!isset($this->db)){
            // Connect to the database
            $conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);
            if($conn->connect_error){
                die("Failed to connect with MySQL: " . $conn->connect_error);
            }else{
                $this->db = $conn;
            }
        }
    }
 
    public function is_table_empty() {
        $result = $this->db->query("SELECT id FROM zoom_oauth WHERE provider = 'zoom'");
        if($result->num_rows) {
            return false;
        }
 
        return true;
    }
 
    public function get_access_token() {
        $sql = $this->db->query("SELECT provider_value FROM zoom_oauth WHERE provider = 'zoom'");
        $result = $sql->fetch_assoc();
        return json_decode($result['provider_value']);
    }
 
    public function get_refersh_token() {
        $result = $this->get_access_token();
        return $result->refresh_token;
    }
 
    public function update_access_token($token) {
        if($this->is_table_empty()) {
            $this->db->query("INSERT INTO zoom_oauth(provider, provider_value) VALUES('zoom', '$token')");
        } else {
            $this->db->query("UPDATE zoom_oauth SET provider_value = '$token' WHERE provider = 'zoom'");
        }
    }
}

Make sure to replace the placeholders with your actual database credentials. Next, let’s generate an access token through the OAuth process.

Generate an Access Token

The user can create an access token for their account using the App credentials and OAuth process. Create a config.php file, store app credentials, and redirect URL in this PHP file. Include the other environments like DB class and vendor library also as follows.

config.php

<?php
require_once 'vendor/autoload.php';
require_once "class-db.php";
 
define('CLIENT_ID', 'YOUR_CLIENT_ID');
define('CLIENT_SECRET', 'YOUR_CLIENT_SECRET');
define('REDIRECT_URI', 'REDIRECT_URL_FOR_OAUTH');

Replace the placeholders with your app credentials and set the same redirect URL you added in the Zoom OAuth app. In my case, the redirect URL is https://f2448150.ngrok.io/zoom/callback.php. It means in the callback.php file, we have to write the code which calls a Zoom API, request an access token, and store it in the database.

callback.php

<?php
require_once 'config.php';
 
try {
    $client = new GuzzleHttp\Client(['base_uri' => 'https://zoom.us']);
 
    $response = $client->request('POST', '/oauth/token', [
        "headers" => [
            "Authorization" => "Basic ". base64_encode(CLIENT_ID.':'.CLIENT_SECRET)
        ],
        'form_params' => [
            "grant_type" => "authorization_code",
            "code" => $_GET['code'],
            "redirect_uri" => REDIRECT_URI
        ],
    ]);
 
    $token = json_decode($response->getBody()->getContents(), true);
 
    $db = new DB();
    $db->update_access_token(json_encode($token));
    echo "Access token inserted successfully.";
} catch(Exception $e) {
    echo $e->getMessage();
}

Now, let’s generate an authorized URL where a user can click and complete the authorization process. I am going to create this URL in the index.php file.

index.php

<?php
require_once 'config.php';
 
$url = "https://zoom.us/oauth/authorize?response_type=code&client_id=".CLIENT_ID."&redirect_uri=".REDIRECT_URI;
?>
 
<a href="<?php echo $url; ?>">Login with Zoom</a>

Run the above file on the browser, click on the ‘Login with Zoom’ link and complete the authorization process. On successful authentication, you should see a success message and the access token would store in your ‘zoom_oauth’ table. If that works, we can go ahead and create a meeting with the Zoom API.

Create a Meeting on Zoom using Zoom API

Zoom is providing an endpoint for creating a meeting through their REST API. You may read about it on their documentation. It requires sending a POST request to the given endpoint along with the required parameters.

The API endpoint also requires an access token to be passed in the Authorization header. As I said earlier, the access token has a short life and we are going to regenerate it in the background without asking for the authentication process again.

I have created a create-meeting.php file for sending a POST request to the endpoint. I also handled the condition of token expiry and regenerating it if expired.

create-meeting.php

<?php
require_once 'config.php';
 
function create_meeting() {
    $client = new GuzzleHttp\Client(['base_uri' => 'https://api.zoom.us']);
 
    $db = new DB();
    $arr_token = $db->get_access_token();
    $accessToken = $arr_token->access_token;
 
    try {
        $response = $client->request('POST', '/v2/users/me/meetings', [
            "headers" => [
                "Authorization" => "Bearer $accessToken"
            ],
            'json' => [
                "topic" => "Let's learn Laravel",
                "type" => 2,
                "start_time" => "2021-03-05T20:30:00",
                "duration" => "30", // 30 mins
                "password" => "123456"
            ],
        ]);
 
        $data = json_decode($response->getBody());
        echo "Join URL: ". $data->join_url;
        echo "<br>";
        echo "Meeting Password: ". $data->password;
 
    } catch(Exception $e) {
        if( 401 == $e->getCode() ) {
            $refresh_token = $db->get_refersh_token();
 
            $client = new GuzzleHttp\Client(['base_uri' => 'https://zoom.us']);
            $response = $client->request('POST', '/oauth/token', [
                "headers" => [
                    "Authorization" => "Basic ". base64_encode(CLIENT_ID.':'.CLIENT_SECRET)
                ],
                'form_params' => [
                    "grant_type" => "refresh_token",
                    "refresh_token" => $refresh_token
                ],
            ]);
            $db->update_access_token($response->getBody());
 
            create_meeting();
        } else {
            echo $e->getMessage();
        }
    }
}
 
create_meeting();

If you noticed the code, I have passed “2021-03-20T20:30:00” as a ‘start_time’. It means the meeting time will be 20 March 2021, 08:30 PM. The user should pass the format for it in yyyy-MM-ddTHH:mm:ss. For the ‘type’ key I passed the value ‘2’ which is for a Scheduled meeting. The user also needs to set a meeting password which I set to ‘123456’.

Go ahead and run this code and you should see a meeting is created on your Zoom account.

Update Zoom Meeting

If you want to update the meeting information, send a PATCH request along with the details that need to be updated. Refer to the below code to update your Zoom meeting. For more information, you may read the documentation.

<?php
require_once 'config.php';
   
$client = new GuzzleHttp\Client(['base_uri' => 'https://api.zoom.us']);
   
$db = new DB();
$arr_token = $db->get_access_token();
$accessToken = $arr_token->access_token;
   
$response = $client->request('PATCH', '/v2/meetings/{meeting_id}', [
    "headers" => [
        "Authorization" => "Bearer $accessToken"
    ],
    'json' => [
        "topic" => "Let's Learn WordPress",
        "type" => 2,
        "start_time" => "2021-07-20T10:30:00",
        "duration" => "45", // 45 mins
        "password" => "123456"
    ],
]);
 
if (204 == $response->getStatusCode()) {
    echo "Meeting is updated successfully.";
}

Zoom returns 204 as HTTP status code upon updating a meeting.

List Zoom Meetings

We have written a code for creating/updating Zoom meetings. After this, you may want to list all meetings in your application.

Zoom provides an API through which we can fetch all our Zoom meetings. Create a file list-meeting.php and use the code below which will print all meetings.

list-meeting.php

<?php
require_once 'config.php';
 
function list_meetings($next_page_token = '') {
    $db = new DB();
    $arr_token = $db->get_access_token();
    $accessToken = $arr_token->access_token;
 
    $client = new GuzzleHttp\Client(['base_uri' => 'https://api.zoom.us']);
   
    $arr_request = [
        "headers" => [
            "Authorization" => "Bearer $accessToken"
        ]
    ];
 
    if (!empty($next_page_token)) {
        $arr_request['query'] = ["next_page_token" => $next_page_token];
    }
 
    $response = $client->request('GET', '/v2/users/me/meetings', $arr_request);
      
    $data = json_decode($response->getBody());
 
    if ( !empty($data) ) {
        foreach ( $data->meetings as $d ) {
            $topic = $d->topic;
            $join_url = $d->join_url;
            echo "<h3>Topic: $topic</h3>";
            echo "Join URL: $join_url";
        }
 
        if ( !empty($data->next_page_token) ) {
            list_meetings($data->next_page_token);
        }
    }
}
 
list_meetings();

In the above code, I am printing a topic and URL of meetings. You may print other information as well. Print the variable $data to get a list of available information.

While fetching meetings Zoom return 30 records in a single call. Using the next_page_token value we can get the next set of records as shown in the code.

Get Past Meeting Participants

Once the meeting is over, you can get a list of participants using the Zoom API. It is recommended to call this API only if you are on a paid account. This specific API requires to have paid account. If you try to call this API with a free account you would get an error.

<?php
require_once 'config.php';
   
$client = new GuzzleHttp\Client(['base_uri' => 'https://api.zoom.us']);
   
$db = new DB();
$arr_token = $db->get_access_token();
$accessToken = $arr_token->access_token;
   
$response = $client->request('GET', '/v2/past_meetings/MEETING_ID/participants', [
    "headers" => [
        "Authorization" => "Bearer $accessToken"
    ]
]);
 
$data = json_decode($response->getBody());
if ( !empty($data) ) {
    foreach ( $data->participants as $p ) {
        $name = $p->name;
        $email = $p->user_email;
        echo "Name: $name";
        echo "Email: $email";
    }
}

Replace the placeholder MEETING_ID with the actual past meeting id. In the response, you will get the names and emails of participants.

Delete a Meeting

The user can play with the Zoom API endpoints like list, update, delete a meeting. All you need to do is follow their guidelines on using specific endpoints. For example, you can delete a meeting by sending a DELETE request to the API endpoint. To this endpoint, you need to pass your meeting id as shown below.

<?php
require_once 'config.php';
 
$client = new GuzzleHttp\Client(['base_uri' => 'https://api.zoom.us']);
 
$db = new DB();
$arr_token = $db->get_access_token();
$accessToken = $arr_token->access_token;
 
$response = $client->request('DELETE', '/v2/meetings/{meeting_id}', [
    "headers" => [
        "Authorization" => "Bearer $accessToken"
    ]
]);
 
if (204 == $response->getStatusCode()) {
    echo "Meeting is deleted.";
}

I hope you got to know how to create a meeting using Zoom API and PHP. I would like to hear your thoughts and suggestions in the comment section below.

Bạn thấy bài viết này như thế nào?
0 reactions

Add new comment

Image CAPTCHA
Enter the characters shown in the image.
Câu nói tâm đắc: “Điều tuyệt với nhất trong cuộc sống là làm được những việc mà người khác tin là không thể!”

Related Articles

Master list (in progress) of how to get parts of fields for use in Twig templates. I’m always having to look these up, so I thought I’d hash them out and write them down.

Litespeed Cache là plugin WordPress dùng để kết hợp với Web Server LiteSpeed nhằm tăng tốc website WordPress của bạn gấp nhiều lần

In this article, we are going to see how some tools & libraries will make people's lives easier during the development & code review process.

In this tutorial, you will learn how to improve the custom code, theme and module, and general code development by using the pre-commit hook on git

Trước khi tìm hiểu xem PHP Code Sniffer là gì thì các bạn cần phải nắm được coding convention là gì đã.