PHP Classes

Use a PHP Token Generator to Access Agora Services Using the Package PHP Agora Tokens: Generate Agora user authentication tokens

Recommend this page to a friend!
     
  Info   Example   View files Files   Install with Composer Install with Composer   Download Download   Reputation   Support forum   Blog    
Last Updated Ratings Unique User Downloads Download Rankings
2025-05-15 (2 days ago) RSS 2.0 feedNot yet rated by the usersTotal: Not yet counted Not yet ranked
Version License PHP version Categories
php-agora-tokens 1.0.0MIT/X Consortium ...7Cryptography, User Management, PHP 7
Description 

Author

This package can generate Agora user authentication tokens.

It is a package based on the Agora PHP token generator.

The package can take a channel name, user identifier and the lifetime limit of the token to generate.

It can return the generated token as a string to communicate with Agora services.

Picture of Ujah Chigozie peter
  Performance   Level  
Name: Ujah Chigozie peter <contact>
Classes: 31 packages by
Country: Nigeria Nigeria
Innovation award
Innovation award
Nominee: 11x

Instructions

Please read this document to learn how to install and use this package to make PHP generate user tokens to access the Agora services.

Example

<?php
use \Peterujah\Agora\Agora;
use \
Peterujah\Agora\User;
use \
Peterujah\Agora\Roles;
use \
Peterujah\Agora\Builders\RtcToken;


$channelName = "7d72365eb983485397e3e3f9d460bdda";
$uid = 2882341273;
$uidStr = "2882341273";
$tokenExpirationInSeconds = 3600;
$privilegeExpirationInSeconds = 3600;
$joinChannelPrivilegeExpireInSeconds = 3600;
$pubAudioPrivilegeExpireInSeconds = 3600;
$pubVideoPrivilegeExpireInSeconds = 3600;
$pubDataStreamPrivilegeExpireInSeconds = 3600;

$client = new Agora(
   
getenv("AGORA_APP_ID"), // Need to set environment variable AGORA_APP_ID
   
getenv("AGORA_APP_CERTIFICATE"), // Need to set environment variable AGORA_APP_CERTIFICATE
);
$client->setExpiration($tokenExpirationInSeconds);

$user1 = (new User($uid))
    ->
setPrivilegeExpire($privilegeExpirationInSeconds)
    ->
setChannel($channelName)
    ->
setRole(Roles::RTC_PUBLISHER);

$token = RtcToken::buildTokenWithUid($client, $user1);
echo
'Token with int uid: ' . $token . PHP_EOL;

$user2 = (new User($uidStr))
    ->
setPrivilegeExpire($privilegeExpirationInSeconds)
    ->
setChannel($channelName)
    ->
setRole(Roles::RTC_PUBLISHER);

$token = RtcToken::buildTokenWithUserAccount($client, $user2);
echo
'Token with user account: ' . $token . PHP_EOL;

$user3 = (new User($uid))
    ->
setChannelPrivilegeExpire($joinChannelPrivilegeExpireInSeconds)
    ->
setAudioPrivilegeExpire($pubAudioPrivilegeExpireInSeconds)
    ->
setVideoPrivilegeExpire($pubVideoPrivilegeExpireInSeconds)
    ->
setStreamPrivilegeExpire($pubDataStreamPrivilegeExpireInSeconds)
    ->
setChannel($channelName);

$token = RtcToken::buildTokenWithUidAndPrivilege($client, $user3);
echo
'Token with int uid and privilege: ' . $token . PHP_EOL;

$user4 = (new User($uidStr))
    ->
setChannelPrivilegeExpire($joinChannelPrivilegeExpireInSeconds)
    ->
setAudioPrivilegeExpire($pubAudioPrivilegeExpireInSeconds)
    ->
setVideoPrivilegeExpire($pubVideoPrivilegeExpireInSeconds)
    ->
setStreamPrivilegeExpire($pubDataStreamPrivilegeExpireInSeconds)
    ->
setChannel($channelName);

$token = RtcToken::buildTokenWithUserAccountAndPrivilege($client, $user4);
echo
'Token with user account and privilege: ' . $token . PHP_EOL;

$user5 = (new User($uidStr))
    ->
setPrivilegeExpire($privilegeExpirationInSeconds)
    ->
setChannel($channelName)
    ->
setRole(Roles::RTC_PUBLISHER);

$token = RtcToken::buildTokenWithRtm($client, $user5);
echo
'Token with RTM: ' . $token . PHP_EOL;


Details

PHP Agora Token Builder

This package is a Composer-friendly rewrite of Agora's PHP token generator. It provides a simple and modern way to generate Agora Access Tokens (v2.1.0) and Dynamic Keys (v2.0.2 or earlier) for authenticating users in real-time communication applications.

> This rewrite preserves the integrity of Agora's token-signing logic while introducing improvements for better structure, developer experience, and Composer compatibility.

Features and Enhancements

  • Type Hints: Enforced strict typing for all method parameters and return types, making it IDE and static-analysis friendly.
  • Agora Client Class: Centralized class for initializing your `App ID` and `App Certificate`.
  • User Model: Object-oriented structure for setting user-specific values like UID, role, privileges, and token expiration.
  • Role Constants: Easy-to-read and self-documented roles for RTC and RTM users.
  • Privilege Constants: Easily manage supported privileges using named constants.
  • Namespace Organization: Organized into PHP namespaces for clarity and autoloading support.
  • Exception Handling: Errors now throw meaningful exceptions (e.g., missing credentials), improving debugging and robustness.
  • Composer Compatible: Easily install and autoload with Composer.

Class Refactor & Naming Convention

To improve clarity and follow modern naming conventions, we have renamed certain classes. The legacy version now uses a Legacy suffix, while the latest version drops the previous 2 suffix:

| Old Class Name | New Class Name | Description | | --------------- | ------------------------------------ | ---------------------------------------- | | AccessToken | AccessTokenLegacy | Agora AccessToken Version 006 (legacy) | | AccessToken2 | AccessToken | Agora AccessToken Version 007 (latest) | | RtcTokenBuilder | RtcTokenLegacy | Builder for AccessToken 006 | | RtcTokenBuilder2 | RtcToken | Builder for AccessToken 007 | | RtmTokenBuilder | RtmTokenLegacy | Builder for RTM token AccessTokenLegacy | | RtmTokenBuilder2 | RtmToken | Builder for RTM token AccessToken |

> This ensures the default token builder always targets the most up-to-date version, while legacy usage remains supported but explicitly labeled.

Target Versions

This package supports:

  • AccessToken Version 006
  • AccessToken2 Version 007

Installation

Install the package via Composer:

composer require peterujah/php-agora-tokens

Getting Started

  1. Sign Up for Agora

    Create an Agora account and obtain yourApp IDandApp Certificate*. * https://www.agora.io/en/

Class Namespaces

Below is a breakdown of the namespaces and classes provided by the package:

Core Components

  • Peterujah\Agora\Agora Manages the Agora `App ID`, `App Certificate`, default channel name, user role, and token expiration setup.
  • Peterujah\Agora\User Represents the user identity. Handles UID, channel name, user role, and privilege assignment.
  • Peterujah\Agora\Roles Defines constants for user roles used in RTC and RTM tokens:

    * `RTC_PUBLISHER`, `RTC_SUBSCRIBER`, `RTC_ATTENDEE`, `RTC_ADMIN`, `RTM_USER`

  • Peterujah\Agora\Privileges Contains all supported privilege constants for APAAS, CHAT, RTC and RTM services.

    * `APAAS_ROOM_USER`, `RTC_JOIN_CHANNEL`, `PERMISSIONS`

  • Peterujah\Agora\Message Handles basic agora message payload packing.
  • Peterujah\Agora\Util Utility helpers used internally for token formatting or time-based calculations.
  • Peterujah\Agora\BaseService Shared logic base for service-related classes (e.g., default token generators).
  • Peterujah\Agora\func Procedural utility functions for:

    * `DynamicKey4`, `DynamicKey5`, and `SignalingToken` generation.

Agora Access Token Handlers

  • Peterujah\Agora\Tokens\AccessTokenLegacy Builder for legacy AccessToken (`006`).
  • Peterujah\Agora\Tokens\AccessToken Builder for modern AccessToken2 (`007`) format.

Token Builders (Service Specific)

Each token builder generates a scoped access token for a specific Agora service:

  • Peterujah\Agora\Builders\ApaasToken ? For Agora Platform-as-a-Service (APaaS).
  • Peterujah\Agora\Builders\ChatToken ? For Chat/Messaging token generation.
  • Peterujah\Agora\Builders\EducationToken ? For Agora?s Education SDK token support.
  • Peterujah\Agora\Builders\FpaToken ? For First-Packet Acceleration (FPA).
  • Peterujah\Agora\Builders\RtcToken ? For RTC AccessToken (`007`) generation.
  • Peterujah\Agora\Builders\RtcTokenLegacy ? For RTC AccessToken2 (`006`) generation.
  • Peterujah\Agora\Builders\RtmToken ? For RTM AccessToken (`007`).
  • Peterujah\Agora\Builders\RtmTokenLegacy ? For RTM AccessToken2 (`006`).

Agora Service Interfaces

High-level abstractions that encapsulate Agora service-specific token generation:

  • Peterujah\Agora\Services\Apaas ? Handles APaaS token creation.
  • Peterujah\Agora\Services\Chat ? Token management for Chat services.
  • Peterujah\Agora\Services\Fpa ? Handles First-Packet Acceleration service tokens.
  • Peterujah\Agora\Services\Rtc ? Manages RTC token generation via builder classes.
  • Peterujah\Agora\Services\Rtm ? Manages RTM token generation via builder classes.

Usage Examples

You can generate tokens locally using your Agora App ID and App Certificate.

? Sample References

Basic Token Generation Example

use Peterujah\Agora\Agora;
use Peterujah\Agora\User;
use Peterujah\Agora\Roles;
use Peterujah\Agora\Builders\RtcToken;

// Example inputs
$channelName = "7d72365eb983485397e3e3f9d460bdda";
$uid = 2882341273;
$uidStr = "2882341273";
$maxTokenLive = 3600;

// Generate privilege expiration timestamp (UTC)
$currentTimestamp = (new DateTime("now", new DateTimeZone('UTC')))->getTimestamp();
$privilegeExpiredTs = $currentTimestamp + $maxTokenLive;

// Initialize Agora client using environment variables
$client = new Agora(
  getenv("AGORA_APP_ID"),           // Set this in your environment
  getenv("AGORA_APP_CERTIFICATE")   // Set this in your environment
);
$client->setExpiration($privilegeExpiredTs); // Agora Token expiration

// User using UID (int)
$user1 = (new User($uid))
  ->setPrivilegeExpire($privilegeExpiredTs)
  ->setChannel($channelName)
  ->setRole(Roles::RTC_PUBLISHER);

// Generate RTC token using legacy builder (AccessToken v007)
$token1 = RtcToken::buildTokenWithUid($client, $user1);
echo 'Token with int UID: ' . $token1 . PHP_EOL;

// User using User Account (string)
$user2 = (new User($uidStr))
  ->setPrivilegeExpire($privilegeExpiredTs)
  ->setChannel($channelName)
  ->setRole(Roles::RTC_PUBLISHER);

// Generate RTC token using legacy builder with user account
$token2 = RtcToken::buildTokenWithUserAccount($client, $user2);
echo 'Token with user account: ' . $token2 . PHP_EOL;

> Use RtcToken instead of RtcTokenLegacy if you're working with AccessToken2 (v007).

License

This project is licensed under the MIT License.

Credits

Original implementation by Agora. Composer-friendly rewrite and enhancements by @peterujah.


  Files folder image Files (38)  
File Role Description
Files folder imagesample (10 files)
Files folder imagesrc (7 files, 5 directories)
Accessible without login Plain text file composer.json Data Auxiliary data
Accessible without login Plain text file README.md Doc. Documentation

  Files folder image Files (38)  /  sample  
File Role Description
  Accessible without login Plain text file AccessToken2Sample.php Example Example script
  Accessible without login Plain text file ApaasTokenBuilderSample.php Example Example script
  Accessible without login Plain text file ChatTokenBuilder2Sample.php Example Example script
  Accessible without login Plain text file EducationTokenBuilderSample.php Example Example script
  Accessible without login Plain text file FpaTokenBuilderSample.php Example Example script
  Accessible without login Plain text file README.md Doc. Documentation
  Accessible without login Plain text file RtcTokenBuilder2Sample.php Example Example script
  Accessible without login Plain text file RtcTokenBuilderSample.php Example Example script
  Accessible without login Plain text file RtmTokenBuilder2Sample.php Example Example script
  Accessible without login Plain text file RtmTokenBuilderSample.php Example Example script

  Files folder image Files (38)  /  src  
File Role Description
Files folder imageBuilders (8 files)
Files folder imageExceptions (1 file)
Files folder imagefunc (3 files)
Files folder imageServices (5 files)
Files folder imageTokens (2 files)
  Plain text file Agora.php Class Class source
  Plain text file BaseService.php Class Class source
  Plain text file Message.php Class Class source
  Plain text file Privileges.php Class Class source
  Plain text file Roles.php Class Class source
  Plain text file User.php Class Class source
  Plain text file Util.php Class Class source

  Files folder image Files (38)  /  src  /  Builders  
File Role Description
  Plain text file ApaasToken.php Class Class source
  Plain text file ChatToken.php Class Class source
  Plain text file EducationToken.php Class Class source
  Plain text file FpaToken.php Class Class source
  Plain text file RtcToken.php Class Class source
  Plain text file RtcTokenLegacy.php Class Class source
  Plain text file RtmToken.php Class Class source
  Plain text file RtmTokenLegacy.php Class Class source

  Files folder image Files (38)  /  src  /  Exceptions  
File Role Description
  Plain text file AgoraException.php Class Class source

  Files folder image Files (38)  /  src  /  func  
File Role Description
  Accessible without login Plain text file DynamicKey4.php Aux. Configuration script
  Accessible without login Plain text file DynamicKey5.php Aux. Configuration script
  Accessible without login Plain text file SignalingToken.php Aux. Configuration script

  Files folder image Files (38)  /  src  /  Services  
File Role Description
  Plain text file Apaas.php Class Class source
  Plain text file Chat.php Class Class source
  Plain text file Fpa.php Class Class source
  Plain text file Rtc.php Class Class source
  Plain text file Rtm.php Class Class source

  Files folder image Files (38)  /  src  /  Tokens  
File Role Description
  Plain text file AccessToken.php Class Class source
  Plain text file AccessTokenLegacy.php Class Class source

The PHP Classes site has supported package installation using the Composer tool since 2013, as you may verify by reading this instructions page.
Install with Composer Install with Composer
 Version Control Unique User Downloads  
 100%
Total:0
This week:0