Sample code for Python with Zoom API / Zoom SDK

This is a sample code page for Python. It shows the common code sample when interacting with Zoom Webhook, Zoom Meeting SDK Auth Signature, Zoom OAuth and Zoom REST API.

Github Link

github source code

Live Demo

Webhook
Get access token from S2S OAuth
Redirect URL for OAuth
Refresh Token for OAuth
Meeting SDK
Call REST API

application adding url

Code Samples

Tab 1 Content

    
    import json
    import hashlib
    import hmac
    from flask import Flask, request, jsonify
    import os
    from dotenv import load_dotenv
    
    
    # Load environment variables from .env file, this will try to load these values from your .env file
    load_dotenv()
    
    oauth_secret_token = os.getenv("OAUTH_SECRET_TOKEN")
    
    app = Flask(__name__)
    
    def handle_request(request):
    
        if request.method == 'POST':
            # This block handles POST requests
    
            # Get the raw POST data from the request
            input_data = request.data
    
            # Decode the JSON data
            try:
                data = json.loads(input_data)
            except json.JSONDecodeError:
                return "Invalid JSON data", 400
    
            # Check if the event type is "endpoint.url_validation"
            if data.get('event') == 'endpoint.url_validation':
                # Check if the payload contains the "plainToken" property
                payload = data.get('payload', {})
                plain_token = payload.get('plainToken')
                if plain_token is not None:
                    # Hash the plainToken using HMAC-SHA256
                    encrypted_token = hmac.new(
                        oauth_secret_token.encode('utf-8'),
                        plain_token.encode('utf-8'),
                        hashlib.sha256
                    ).hexdigest()
    
                    # Create the response JSON object
                    response = {
                        "plainToken": plain_token,
                        "encryptedToken": encrypted_token
                    }
    
                    # Set the response content type to JSON
                    return response, 200
                else:
                    # Payload is missing the "plainToken" property
                    return "Payload is missing 'plainToken' property.", 400
            else:
                # Invalid event type
                message = "Success."
                
                # Save the POST body to a text file
                with open('webhook.txt', 'w') as file:
                    file.write(str(request.get_json()))
    
                return message, 200
    
        elif request.method == 'GET':
            # This block handles GET requests
    
            # Read the content of the text file
            try:
                with open('webhook.txt', 'r') as file:
                    file_content = file.read()
                return file_content, 200
            except FileNotFoundError:
                return "File not found.", 404
    
        else:
            # Unsupported HTTP method
            return "Unsupported HTTP method.", 405
    


Tab 2 Content

    

import requests
import base64
import os
from dotenv import load_dotenv


# Load environment variables from .env file, this will try to load these values from your .env file
load_dotenv()


# Access the environment variables
s2s_oauth_client_secret = os.getenv("S2S_OAUTH_CLIENT_SECRET")
s2s_oauth_client_id = os.getenv("S2S_OAUTH_CLIENT_ID")
s2s_oauth_account_id = os.getenv("S2S_OAUTH_ACCOUNT_ID")
oauth_url = 'https://zoom.us/oauth/token?grant_type=account_credentials&account_id='+s2s_oauth_account_id  # Replace with your OAuth endpoint URL

def get_access_token():
    try:
        # Create the Basic Authentication header
        auth_header = f'Basic {base64.b64encode(f"{s2s_oauth_client_id}:{s2s_oauth_client_secret}".encode()).decode()}'

        # Define the headers for the OAuth request
        headers = {
            'Authorization': auth_header,
        }

        # Make the OAuth request
        response = requests.post(oauth_url, headers=headers)

        # Check if the request was successful (status code 200)
        if response.status_code == 200:
            # Parse the JSON response to get the access token
            oauth_response = response.json()
            access_token = oauth_response.get('access_token')
            return access_token
        else:
            print(f'OAuth Request Failed with Status Code: {response.status_code}')
            print(response.text)
            return None
    except Exception as e:
        print(f'An error occurred: {str(e)}')
        return None



    
    

Tab 3 Content

  
        from flask import Flask, request, jsonify
        import base64
        import requests
        import urllib.parse  # Import the urllib module for URL encoding
        
        def handle_redirect_url_data_request(path, oauth_client_id, oauth_client_secret, code):
            print ("handle_redirect_url_data_request")
            url = f"https://zoom.us/oauth/token"
            redirect_uri=f"https://python.asdc.cc/{path}"
            print (redirect_uri)
            
            # Encode the client ID and client secret
            credentials = f"{oauth_client_id}:{oauth_client_secret}"
            credentials_encoded = base64.b64encode(credentials.encode()).decode('utf-8')
        
            headers = {
                'Authorization': f'Basic {credentials_encoded}',
                'Content-Type': 'application/x-www-form-urlencoded',
               
            }
            print (credentials_encoded)
        
            data = {
                'grant_type': 'authorization_code',
                'redirect_uri': redirect_uri,
                'code': code
            }
            # Encode the data dictionary as x-www-form-urlencoded
            data_encoded = urllib.parse.urlencode(data).encode('utf-8')
        
        
            response = requests.post(url, data=data_encoded, headers=headers)
            # Check the HTTP status code before parsing as JSON
            if response.status_code == 200:
               print ("response 200")
               response_json = response.json()
               print(response_json)
               return response_json, 200  # Return JSON response with 200 status code
            else:
                
                # Handle the case where the response has an error status code
                return "Error: " + str(response.status_code), response.status_code
        



Tab 4 Content

    
from flask import Flask, jsonify
import jwt
import hashlib
import hmac
import base64
import time
import datetime

#pip3 install PyJ

app = Flask(__name__)

def generate_signature(data, secret):
    encoded_jwt = jwt.encode(data, secret, algorithm="HS256")
    return encoded_jwt

@app.route('/')
def handle_meetingsdk(msdk_client_id, msdk_client_secret):
    epoch_time = int(time.time())
    epoch_time_48hours_later = epoch_time + 172800
    SDK_SECRET = msdk_client_secret
    APP_KEY = msdk_client_id
    data = {
        "appKey": APP_KEY,
        "iat": epoch_time,
        "exp": epoch_time_48hours_later,
        "tokenExp": epoch_time_48hours_later,
        "mn": 9898533313,
        "role": 1
    }
    meeting_sdk_key = generate_signature(data, SDK_SECRET)

    # Get the current date
    current_date = datetime.date.today()

    # Create a datetime object for the start of the day
    start_of_day = datetime.datetime.combine(current_date, datetime.time.min)

    # Get the epoch time (in seconds) for the start of the day
    epoch_time = int(start_of_day.timestamp())

    epoch_time_48hours_later = epoch_time + 172800
    data = {
        "appKey": APP_KEY,
        "iat": epoch_time,
        "exp": epoch_time_48hours_later,
        "tokenExp": epoch_time_48hours_later,
        "mn": 9898533313,
        "role": 1
    }
    meeting_sdk_key_control = generate_signature(data, SDK_SECRET)

    return jsonify({"Meeting SDK Key": meeting_sdk_key, "Meeting SDK Key - Control": meeting_sdk_key_control})


Tab 5 Content

    
        from flask import Flask, request, jsonify
        import base64
        import requests
        import urllib.parse  # Import the urllib module for URL encoding
        
        def handle_oauth_refresh_token_data_request(oauth_client_id, oauth_client_secret, code):
            print ("handle_oauth_refresh_token_data_request")
            url = f"https://zoom.us/oauth/token"
            
            # Encode the client ID and client secret
            credentials = f"{oauth_client_id}:{oauth_client_secret}"
            credentials_encoded = base64.b64encode(credentials.encode()).decode('utf-8')
        
            headers = {
                'Authorization': f'Basic {credentials_encoded}',
                'Content-Type': 'application/x-www-form-urlencoded',
               
            }
            print (credentials_encoded)
        
            data = {
                'grant_type': 'refresh_token',
                'refresh_token': code
            }
            # Encode the data dictionary as x-www-form-urlencoded
            data_encoded = urllib.parse.urlencode(data).encode('utf-8')
        
        
            response = requests.post(url, data=data_encoded, headers=headers)
            # Check the HTTP status code before parsing as JSON
            if response.status_code == 200:
               print ("response 200")
               response_json = response.json()
               print(response_json)
               return response_json, 200  # Return JSON response with 200 status code
            else:
                
                # Handle the case where the response has an error status code
                return "Error: " + str(response.status_code), response.status_code

Tab 6 Content

    
      from flask import Flask, request
      import requests
      import json
      
      app = Flask(__name__)
      
      def handle_callapi():
          # Fetch access_token from query string
          access_token = request.args.get('access_token')
      
          # Meeting data
          meeting_data = {
              "topic": 'hello world',
              "type": 2,
              "start_time": "2023-10-01T10:00:00Z",
              "duration": 120,
              "password": "12345678",
              "agenda": "40 mins limit demonstration",
              "pre_schedule": False,
              "timezone": "Asia/Singapore",
              "default_password": False
          }
      
          # Zoom API endpoint
          api_url = 'https://api.zoom.us/v2/users/me/meetings'
      
          # Headers for the request
          headers = {
              "Authorization": f"Bearer {access_token}",
              "Content-Type": "application/json",
              "Accept": "application/json"
          }
      
          # Send POST request to create meeting
          response = requests.post(api_url, headers=headers, data=json.dumps(meeting_data))
      
          # Return response
          return "Meeting Details: " + response.text
      

Tab 7 Content

    
        S2S_OAUTH_CLIENT_ID='xxxxxxxxxx'
        S2S_OAUTH_CLIENT_SECRET='xxxxxxxxxx'
        S2S_OAUTH_ACCOUNT_ID='xxxxxxxxxx'
        OAUTH_SECRET_TOKEN='xxxxxxxxxx'
        OAUTH_CLIENT_ID='xxxxxxxxxx'
        OAUTH_CLIENT_SECRET='xxxxxxxxxx'
        MSDK_CLIENT_SECRET='xxxxxxxxxx'
        MSDK_CLIENT_ID='xxxxxxxxxx'


Tab 8 Content