代码初始化

This commit is contained in:
2025-08-07 20:21:47 +08:00
commit 50f3a2dbb0
2191 changed files with 374790 additions and 0 deletions

View File

@@ -0,0 +1,92 @@
<?php
namespace shengwang;
include("src/RtcTokenBuilder.php");
include("src/RtmTokenBuilder.php");
include("src/RtcTokenBuilder2.php");
class Shengwang{
public function RtcTokenBuilder($uid, $channelName, $role_type=0, $appID, $appCertificate){
$uid = (string)$uid;
$uid = $uid;
$channelName = (string)$channelName;
// $appID = "3653ea090a98432a8f8c0beb0f92c963";
// $appCertificate = "ec2bf365f7014683a32b3dc41141e945";
$appID = $appID;
$appCertificate = $appCertificate;
// $uid = 0;
// // $uidStr = "2882341273";
$role = \RtcTokenBuilder::RoleAttendee;
if($role_type==0){
$role = \RtcTokenBuilder::RoleAttendee;
}elseif($role_type==1){
$role = \RtcTokenBuilder::RolePublisher;
}elseif($role_type==2){
$role = \RtcTokenBuilder::RoleSubscriber;
}else{
$role = \RtcTokenBuilder::RoleRtmUser;
}
$expireTimeInSeconds = 86400;
$currentTimestamp = (new \DateTime("now", new \DateTimeZone('UTC')))->getTimestamp();
$privilegeExpiredTs = $currentTimestamp + $expireTimeInSeconds;
$token = \RtcTokenBuilder::buildTokenWithUid($appID, $appCertificate, $channelName, $uid, $role, $privilegeExpiredTs);
// dump($token);
// $token = substr($token,0,50).chr(rand(97,122)).chr(rand(65,90)).chr(rand(97,122)).chr(rand(65,90)).substr($token,50,999);
// $token=substr($token,0,50)."####".substr($token,50,999);
return $token;
}
public function RtmTokenBuilder($user_id, $appID, $appCertificate){
/*
$appID = "3653ea090a98432a8f8c0beb0f92c963";
$appCertificate = "ec2bf365f7014683a32b3dc41141e945";
// $uid = 0;
// // $uidStr = "2882341273";
$role = \RtmTokenBuilder::RoleRtmUser;
$expireTimeInSeconds = 3600;
$currentTimestamp = (new \DateTime("now", new \DateTimeZone('UTC')))->getTimestamp();
$privilegeExpiredTs = $currentTimestamp + $expireTimeInSeconds;
//dump($appID);dump($appCertificate);dump($user_id);dump($role);dump($privilegeExpiredTs);
$token = \RtmTokenBuilder::buildToken($appID, $appCertificate, $user_id, $role, $privilegeExpiredTs);
// echo $token;exit;
return $token;
*/
// $appID = "3653ea090a98432a8f8c0beb0f92c963";
// $appCertificate = "ec2bf365f7014683a32b3dc41141e945";
$appID = $appID;
$appCertificate = $appCertificate;
$user = (string)$user_id;
$role = \RtcTokenBuilder::RoleAttendee;
$expireTimeInSeconds = 86400;
$currentTimestamp = (new \DateTime("now", new \DateTimeZone('UTC')))->getTimestamp();
$privilegeExpiredTs = $currentTimestamp + $expireTimeInSeconds;
$token = \RtmTokenBuilder::buildToken($appID, $appCertificate, $user, $role, $privilegeExpiredTs);
// $token = substr($token,0,50).chr(rand(97,122)).chr(rand(65,90)).chr(rand(97,122)).chr(rand(65,90)).substr($token,50,999);
//$token=substr($token,0,50)."####".substr($token,50,999);
return $token;
}
public function RtmTokenBuilders($user_id, $appID, $appCertificate, $channelName){
$user = (string)$user_id;
$expireTimeInSeconds = 86400;
$currentTimestamp = (new \DateTime("now", new \DateTimeZone('UTC')))->getTimestamp();
$privilegeExpiredTs = $currentTimestamp + $expireTimeInSeconds;
// 生成具备 RTC 和 RTM 权限的 Token
$token = \RtcTokenBuilder2::buildTokenWithRtm($appID, $appCertificate, $channelName, $user, \RtcTokenBuilder2::ROLE_PUBLISHER, $privilegeExpiredTs, $privilegeExpiredTs);
return $token;
}
}

View File

@@ -0,0 +1,13 @@
- **RtcTokenBuilder.php**: Source code for generating a token for the following SDKs:
- Agora Native SDK v2.1+
- Agora Web SDK v2.4+
- Agora Recording SDK v2.1+
- Agora RTSA SDK
> The Agora RTSA SDK supports joining multiple channels. If you join multiple channels at the same time, then you MUST generate a specific token for each channel you join.
- **RtmTokenBuilder.php**: Source code for generating a token for the Agora RTM SDK.
- **AccessToken.php**: Implements all the underlying algorithms for generating a token. Both **RtcTokenBuilder.php** and **RtmTokenBuilder.php** are a wrapper of **AccessToken.php** and have much easier-to-use APIs. We recommend using **RtcTokenBuilder.php** for generating an RTC token or **RtmTokenBuilder.php** for an RTM token.

View File

@@ -0,0 +1,19 @@
<?php
include("../src/RtcTokenBuilder.php");
$appID = "970CA35de60c44645bbae8a215061b33";
$appCertificate = "5CFd2fd1755d40ecb72977518be15d3b";
$channelName = "7d72365eb983485397e3e3f9d460bdda";
$uid = 2882341273;
$uidStr = "2882341273";
$role = RtcTokenBuilder::RoleAttendee;
$expireTimeInSeconds = 3600;
$currentTimestamp = (new DateTime("now", new DateTimeZone('UTC')))->getTimestamp();
$privilegeExpiredTs = $currentTimestamp + $expireTimeInSeconds;
$token = RtcTokenBuilder::buildTokenWithUid($appID, $appCertificate, $channelName, $uid, $role, $privilegeExpiredTs);
echo 'Token with int uid: ' . $token . PHP_EOL;
$token = RtcTokenBuilder::buildTokenWithUserAccount($appID, $appCertificate, $channelName, $uidStr, $role, $privilegeExpiredTs);
echo 'Token with user account: ' . $token . PHP_EOL;
?>

View File

@@ -0,0 +1,15 @@
<?php
include("../src/RtmTokenBuilder.php");
$appID = "970CA35de60c44645bbae8a215061b33";
$appCertificate = "5CFd2fd1755d40ecb72977518be15d3b";
$user = "test_user_id";
$role = RtmTokenBuilder::RoleRtmUser;
$expireTimeInSeconds = 3600;
$currentTimestamp = (new DateTime("now", new DateTimeZone('UTC')))->getTimestamp();
$privilegeExpiredTs = $currentTimestamp + $expireTimeInSeconds;
$token = RtmTokenBuilder::buildToken($appID, $appCertificate, $user, $role, $privilegeExpiredTs);
echo 'Rtm Token: ' . $token . PHP_EOL;
?>

View File

@@ -0,0 +1,198 @@
<?php
// namespace shengwang;
class Message
{
public $salt;
public $ts;
public $privileges;
public function __construct()
{
//$this->salt = random_int(1, 99999999);
$this->salt = mt_rand(1, 99999999);
$date = new DateTime("now", new DateTimeZone('UTC'));
$this->ts = $date->getTimestamp() + 24 * 3600;
$this->privileges = array();
}
public function packContent()
{
$buffer = unpack("C*", pack("V", $this->salt));
$buffer = array_merge($buffer, unpack("C*", pack("V", $this->ts)));
$buffer = array_merge($buffer, unpack("C*", pack("v", sizeof($this->privileges))));
foreach ($this->privileges as $key => $value) {
$buffer = array_merge($buffer, unpack("C*", pack("v", $key)));
$buffer = array_merge($buffer, unpack("C*", pack("V", $value)));
}
return $buffer;
}
public function unpackContent($msg)
{
$pos = 0;
$salt = unpack("V", substr($msg, $pos, 4))[1];
$pos += 4;
$ts = unpack("V", substr($msg, $pos, 4))[1];
$pos += 4;
$size = unpack("v", substr($msg, $pos, 2))[1];
$pos += 2;
$privileges = array();
for ($i = 0; $i < $size; $i++) {
$key = unpack("v", substr($msg, $pos, 2));
$pos += 2;
$value = unpack("V", substr($msg, $pos, 4));
$pos += 4;
$privileges[$key[1]] = $value[1];
}
$this->salt = $salt;
$this->ts = $ts;
$this->privileges = $privileges;
}
}
class AccessToken
{
const Privileges = array(
"kJoinChannel" => 1,
"kPublishAudioStream" => 2,
"kPublishVideoStream" => 3,
"kPublishDataStream" => 4,
"kPublishAudioCdn" => 5,
"kPublishVideoCdn" => 6,
"kRequestPublishAudioStream" => 7,
"kRequestPublishVideoStream" => 8,
"kRequestPublishDataStream" => 9,
"kInvitePublishAudioStream" => 10,
"kInvitePublishVideoStream" => 11,
"kInvitePublishDataStream" => 12,
"kAdministrateChannel" => 101,
"kRtmLogin" => 1000,
);
public $appID, $appCertificate, $channelName, $uid;
public $message;
function __construct()
{
$this->message = new Message();
}
function setUid($uid)
{
if ($uid === 0) {
$this->uid = "";
} else {
$this->uid = $uid . '';
}
}
function is_nonempty_string($name, $str)
{
if (is_string($str) && $str !== "") {
return true;
}
echo $name . " check failed, should be a non-empty string";
return false;
}
static function init($appID, $appCertificate, $channelName, $uid)
{
$accessToken = new AccessToken();
if (!$accessToken->is_nonempty_string("appID", $appID) ||
!$accessToken->is_nonempty_string("appCertificate", $appCertificate) ||
!$accessToken->is_nonempty_string("channelName", $channelName)) {
return null;
}
$accessToken->appID = $appID;
$accessToken->appCertificate = $appCertificate;
$accessToken->channelName = $channelName;
$accessToken->setUid($uid);
$accessToken->message = new Message();
return $accessToken;
}
static function initWithToken($token, $appCertificate, $channel, $uid)
{
$accessToken = new AccessToken();
if (!$accessToken->extract($token, $appCertificate, $channel, $uid)) {
return null;
}
return $accessToken;
}
function addPrivilege($key, $expireTimestamp)
{
$this->message->privileges[$key] = $expireTimestamp;
return $this;
}
function extract($token, $appCertificate, $channelName, $uid)
{
$ver_len = 3;
$appid_len = 32;
$version = substr($token, 0, $ver_len);
if ($version !== "006") {
echo 'invalid version ' . $version;
return false;
}
if (!$this->is_nonempty_string("token", $token) ||
!$this->is_nonempty_string("appCertificate", $appCertificate) ||
!$this->is_nonempty_string("channelName", $channelName)) {
return false;
}
$appid = substr($token, $ver_len, $appid_len);
$content = (base64_decode(substr($token, $ver_len + $appid_len, strlen($token) - ($ver_len + $appid_len))));
$pos = 0;
$len = unpack("v", $content . substr($pos, 2))[1];
$pos += 2;
$sig = substr($content, $pos, $len);
$pos += $len;
$crc_channel = unpack("V", substr($content, $pos, 4))[1];
$pos += 4;
$crc_uid = unpack("V", substr($content, $pos, 4))[1];
$pos += 4;
$msgLen = unpack("v", substr($content, $pos, 2))[1];
$pos += 2;
$msg = substr($content, $pos, $msgLen);
$this->appID = $appid;
$message = new Message();
$message->unpackContent($msg);
$this->message = $message;
//non reversable values
$this->appCertificate = $appCertificate;
$this->channelName = $channelName;
$this->setUid($uid);
return true;
}
function build()
{
$msg = $this->message->packContent();
$val = array_merge(unpack("C*", $this->appID), unpack("C*", $this->channelName), unpack("C*", $this->uid), $msg);
$sig = hash_hmac('sha256', implode(array_map("chr", $val)), $this->appCertificate, true);
$crc_channel_name = crc32($this->channelName) & 0xffffffff;
$crc_uid = crc32($this->uid) & 0xffffffff;
$content = array_merge(unpack("C*", packString($sig)), unpack("C*", pack("V", $crc_channel_name)), unpack("C*", pack("V", $crc_uid)), unpack("C*", pack("v", count($msg))), $msg);
$version = "006";
$ret = $version . $this->appID . base64_encode(implode(array_map("chr", $content)));
return $ret;
}
}
function packString($value)
{
return pack("v", strlen($value)) . $value;
}

View File

@@ -0,0 +1,266 @@
<?php
require_once "Util.php";
class Service
{
public $type;
public $privileges;
public function __construct($serviceType)
{
$this->type = $serviceType;
}
public function addPrivilege($privilege, $expire)
{
$this->privileges[$privilege] = $expire;
}
public function getServiceType()
{
return $this->type;
}
public function pack()
{
return Util::packUint16($this->type) . Util::packMapUint32($this->privileges);
}
public function unpack(&$data)
{
$this->privileges = Util::unpackMapUint32($data);
}
}
class ServiceRtc extends Service
{
const SERVICE_TYPE = 1;
const PRIVILEGE_JOIN_CHANNEL = 1;
const PRIVILEGE_PUBLISH_AUDIO_STREAM = 2;
const PRIVILEGE_PUBLISH_VIDEO_STREAM = 3;
const PRIVILEGE_PUBLISH_DATA_STREAM = 4;
public $channelName;
public $uid;
public function __construct($channelName = "", $uid = "")
{
parent::__construct(self::SERVICE_TYPE);
$this->channelName = $channelName;
$this->uid = $uid;
}
public function pack()
{
return parent::pack() . Util::packString($this->channelName) . Util::packString($this->uid);
}
public function unpack(&$data)
{
parent::unpack($data);
$this->channelName = Util::unpackString($data);
$this->uid = Util::unpackString($data);
}
}
class ServiceRtm extends Service
{
const SERVICE_TYPE = 2;
const PRIVILEGE_LOGIN = 1;
public $userId;
public function __construct($userId = "")
{
parent::__construct(self::SERVICE_TYPE);
$this->userId = $userId;
}
public function pack()
{
return parent::pack() . Util::packString($this->userId);
}
public function unpack(&$data)
{
parent::unpack($data);
$this->userId = Util::unpackString($data);
}
}
class ServiceFpa extends Service
{
const SERVICE_TYPE = 4;
const PRIVILEGE_LOGIN = 1;
public function __construct()
{
parent::__construct(self::SERVICE_TYPE);
}
public function pack()
{
return parent::pack();
}
public function unpack(&$data)
{
parent::unpack($data);
}
}
class ServiceChat extends Service
{
const SERVICE_TYPE = 5;
const PRIVILEGE_USER = 1;
const PRIVILEGE_APP = 2;
public $userId;
public function __construct($userId = "")
{
parent::__construct(self::SERVICE_TYPE);
$this->userId = $userId;
}
public function pack()
{
return parent::pack() . Util::packString($this->userId);
}
public function unpack(&$data)
{
parent::unpack($data);
$this->userId = Util::unpackString($data);
}
}
class ServiceApaas extends Service
{
const SERVICE_TYPE = 7;
const PRIVILEGE_ROOM_USER = 1;
const PRIVILEGE_USER = 2;
const PRIVILEGE_APP = 3;
public $roomUuid;
public $userUuid;
public $role;
public function __construct($roomUuid = "", $userUuid = "", $role = -1)
{
parent::__construct(self::SERVICE_TYPE);
$this->roomUuid = $roomUuid;
$this->userUuid = $userUuid;
$this->role = $role;
}
public function pack()
{
return parent::pack() . Util::packString($this->roomUuid) . Util::packString($this->userUuid) . Util::packInt16($this->role);
}
public function unpack(&$data)
{
parent::unpack($data);
$this->roomUuid = Util::unpackString($data);
$this->userUuid = Util::unpackString($data);
$this->role = Util::unpackInt16($data);
}
}
class AccessToken2
{
const VERSION = "007";
const VERSION_LENGTH = 3;
public $appCert;
public $appId;
public $expire;
public $issueTs;
public $salt;
public $services = [];
public function __construct($appId = "", $appCert = "", $expire = 900)
{
$this->appId = $appId;
$this->appCert = $appCert;
$this->expire = $expire;
$this->issueTs = time();
$this->salt = rand(1, 99999999);
}
public function addService($service)
{
$this->services[$service->getServiceType()] = $service;
}
public function build()
{
if (!self::isUUid($this->appId) || !self::isUUid($this->appCert)) {
return "";
}
$signing = $this->getSign();
$data = Util::packString($this->appId) . Util::packUint32($this->issueTs) . Util::packUint32($this->expire)
. Util::packUint32($this->salt) . Util::packUint16(count($this->services));
ksort($this->services);
foreach ($this->services as $key => $service) {
$data .= $service->pack();
}
$signature = hash_hmac("sha256", $data, $signing, true);
return self::getVersion() . base64_encode(zlib_encode(Util::packString($signature) . $data, ZLIB_ENCODING_DEFLATE));
}
public function getSign()
{
$hh = hash_hmac("sha256", $this->appCert, Util::packUint32($this->issueTs), true);
return hash_hmac("sha256", $hh, Util::packUint32($this->salt), true);
}
public static function getVersion()
{
return self::VERSION;
}
public static function isUUid($str)
{
if (strlen($str) != 32) {
return false;
}
return ctype_xdigit($str);
}
public function parse($token)
{
if (substr($token, 0, self::VERSION_LENGTH) != self::getVersion()) {
return false;
}
$data = zlib_decode(base64_decode(substr($token, self::VERSION_LENGTH)));
$signature = Util::unpackString($data);
$this->appId = Util::unpackString($data);
$this->issueTs = Util::unpackUint32($data);
$this->expire = Util::unpackUint32($data);
$this->salt = Util::unpackUint32($data);
$serviceNum = Util::unpackUint16($data);
$servicesObj = [
ServiceRtc::SERVICE_TYPE => new ServiceRtc(),
ServiceRtm::SERVICE_TYPE => new ServiceRtm(),
ServiceFpa::SERVICE_TYPE => new ServiceFpa(),
ServiceChat::SERVICE_TYPE => new ServiceChat(),
ServiceApaas::SERVICE_TYPE => new ServiceApaas(),
];
for ($i = 0; $i < $serviceNum; $i++) {
$serviceTye = Util::unpackUint16($data);
$service = $servicesObj[$serviceTye];
if ($service == null) {
return false;
}
$service->unpack($data);
$this->services[$serviceTye] = $service;
}
return true;
}
}

View File

@@ -0,0 +1,36 @@
<?php
namespace shengwang;
function generateRecordingKey($appID, $appCertificate, $channelName, $ts, $randomInt, $uid, $expiredTs ,$serviceType='ARS')
{
return generateDynamicKey($appID, $appCertificate, $channelName, $ts, $randomInt, $uid, $expiredTs ,$serviceType);
}
function generateMediaChannelKey($appID, $appCertificate, $channelName, $ts, $randomInt, $uid, $expiredTs ,$serviceType='ACS')
{
return generateDynamicKey($appID, $appCertificate, $channelName, $ts, $randomInt, $uid, $expiredTs ,$serviceType);
}
function generateDynamicKey($appID, $appCertificate, $channelName, $ts, $randomInt, $uid, $expiredTs ,$serviceType)
{
$version = "004";
$randomStr = "00000000" . dechex($randomInt);
$randomStr = substr($randomStr,-8);
$uidStr = "0000000000" . $uid;
$uidStr = substr($uidStr,-10);
$expiredStr = "0000000000" . $expiredTs;
$expiredStr = substr($expiredStr,-10);
$signature = generateSignature($appID, $appCertificate, $channelName, $ts, $randomStr, $uidStr, $expiredStr ,$serviceType);
return $version . $signature . $appID . $ts . $randomStr . $expiredStr;
}
function generateSignature($appID, $appCertificate, $channelName, $ts, $randomStr, $uidStr, $expiredStr ,$serviceType)
{
$concat = $serviceType . $appID . $ts . $randomStr . $channelName . $uidStr . $expiredStr;
return hash_hmac('sha1', $concat, $appCertificate);
}
?>

View File

@@ -0,0 +1,84 @@
<?php
$version = "005";
$NO_UPLOAD = "0";
$AUDIO_VIDEO_UPLOAD = "3";
// InChannelPermissionKey
$ALLOW_UPLOAD_IN_CHANNEL = 1;
// Service Type
$MEDIA_CHANNEL_SERVICE = 1;
$RECORDING_SERVICE = 2;
$PUBLIC_SHARING_SERVICE = 3;
$IN_CHANNEL_PERMISSION = 4;
function generateRecordingKey($appID, $appCertificate, $channelName, $ts, $randomInt, $uid, $expiredTs)
{
return generateDynamicKey($appID, $appCertificate, $channelName, $ts, $randomInt, $uid, $expiredTs, $GLOBALS["RECORDING_SERVICE"], array());
}
function generateMediaChannelKey($appID, $appCertificate, $channelName, $ts, $randomInt, $uid, $expiredTs)
{
return generateDynamicKey($appID, $appCertificate, $channelName, $ts, $randomInt, $uid, $expiredTs, $GLOBALS["MEDIA_CHANNEL_SERVICE"], array());
}
function generateInChannelPermissionKey($appID, $appCertificate, $channelName, $ts, $randomInt, $uid, $expiredTs, $permission)
{
$extra[$GLOBALS["ALLOW_UPLOAD_IN_CHANNEL"]] = $permission;
return generateDynamicKey($appID, $appCertificate, $channelName, $ts, $randomInt, $uid, $expiredTs, $GLOBALS["IN_CHANNEL_PERMISSION"], $extra);
}
function generateDynamicKey($appID, $appCertificate, $channelName, $ts, $randomInt, $uid, $expiredTs, $serviceType, $extra)
{
$signature = generateSignature($serviceType, $appID, $appCertificate, $channelName, $uid, $ts, $randomInt, $expiredTs, $extra);
$content = packContent($serviceType, $signature, hex2bin($appID), $ts, $randomInt, $expiredTs, $extra);
// echo bin2hex($content);
return $GLOBALS["version"] . base64_encode($content);
}
function generateSignature($serviceType, $appID, $appCertificate, $channelName, $uid, $ts, $salt, $expiredTs, $extra)
{
$rawAppID = hex2bin($appID);
$rawAppCertificate = hex2bin($appCertificate);
$buffer = pack("S", $serviceType);
$buffer .= pack("S", strlen($rawAppID)) . $rawAppID;
$buffer .= pack("I", $ts);
$buffer .= pack("I", $salt);
$buffer .= pack("S", strlen($channelName)) . $channelName;
$buffer .= pack("I", $uid);
$buffer .= pack("I", $expiredTs);
$buffer .= pack("S", count($extra));
foreach ($extra as $key => $value) {
$buffer .= pack("S", $key);
$buffer .= pack("S", strlen($value)) . $value;
}
return strtoupper(hash_hmac('sha1', $buffer, $rawAppCertificate));
}
function packString($value)
{
return pack("S", strlen($value)) . $value;
}
function packContent($serviceType, $signature, $appID, $ts, $salt, $expiredTs, $extra)
{
$buffer = pack("S", $serviceType);
$buffer .= packString($signature);
$buffer .= packString($appID);
$buffer .= pack("I", $ts);
$buffer .= pack("I", $salt);
$buffer .= pack("I", $expiredTs);
$buffer .= pack("S", count($extra));
foreach ($extra as $key => $value) {
$buffer .= pack("S", $key);
$buffer .= packString($value);
}
return $buffer;
}
?>

View File

@@ -0,0 +1,59 @@
<?php
// namespace shengwang;
require_once "AccessToken.php";
class RtcTokenBuilder
{
const RoleAttendee = 0;
const RolePublisher = 1;
const RoleSubscriber = 2;
const RoleAdmin = 101;
# appID: The App ID issued to you by Agora. Apply for a new App ID from
# Agora Dashboard if it is missing from your kit. See Get an App ID.
# appCertificate: Certificate of the application that you registered in
# the Agora Dashboard. See Get an App Certificate.
# channelName:Unique channel name for the AgoraRTC session in the string format
# uid: User ID. A 32-bit unsigned integer with a value ranging from
# 1 to (232-1). optionalUid must be unique.
# role: Role_Publisher = 1: A broadcaster (host) in a live-broadcast profile.
# Role_Subscriber = 2: (Default) A audience in a live-broadcast profile.
# privilegeExpireTs: represented by the number of seconds elapsed since
# 1/1/1970. If, for example, you want to access the
# Agora Service within 10 minutes after the token is
# generated, set expireTimestamp as the current
# timestamp + 600 (seconds)./
public static function buildTokenWithUid($appID, $appCertificate, $channelName, $uid, $role, $privilegeExpireTs){
return RtcTokenBuilder::buildTokenWithUserAccount($appID, $appCertificate, $channelName, $uid, $role, $privilegeExpireTs);
}
# appID: The App ID issued to you by Agora. Apply for a new App ID from
# Agora Dashboard if it is missing from your kit. See Get an App ID.
# appCertificate: Certificate of the application that you registered in
# the Agora Dashboard. See Get an App Certificate.
# channelName:Unique channel name for the AgoraRTC session in the string format
# userAccount: The user account.
# role: Role_Publisher = 1: A broadcaster (host) in a live-broadcast profile.
# Role_Subscriber = 2: (Default) A audience in a live-broadcast profile.
# privilegeExpireTs: represented by the number of seconds elapsed since
# 1/1/1970. If, for example, you want to access the
# Agora Service within 10 minutes after the token is
# generated, set expireTimestamp as the current
public static function buildTokenWithUserAccount($appID, $appCertificate, $channelName, $userAccount, $role, $privilegeExpireTs){
$token = AccessToken::init($appID, $appCertificate, $channelName, $userAccount);
$Privileges = AccessToken::Privileges;
$token->addPrivilege($Privileges["kJoinChannel"], $privilegeExpireTs);
if(($role == RtcTokenBuilder::RoleAttendee) ||
($role == RtcTokenBuilder::RolePublisher) ||
($role == RtcTokenBuilder::RoleAdmin))
{
$token->addPrivilege($Privileges["kPublishVideoStream"], $privilegeExpireTs);
$token->addPrivilege($Privileges["kPublishAudioStream"], $privilegeExpireTs);
$token->addPrivilege($Privileges["kPublishDataStream"], $privilegeExpireTs);
}
return $token->build();
}
}
?>

View File

@@ -0,0 +1,308 @@
<?php
require_once "AccessToken2.php";
class RtcTokenBuilder2
{
/**
* RECOMMENDED. Use this role for a voice/video call or a live broadcast, if
* your scenario does not require authentication for
* [Co-host](https://docs.agora.io/en/video-calling/get-started/authentication-workflow?#co-host-token-authentication).
*/
const ROLE_PUBLISHER = 1;
/**
* Only use this role if your scenario require authentication for
* [Co-host](https://docs.agora.io/en/video-calling/get-started/authentication-workflow?#co-host-token-authentication).
*
* @note In order for this role to take effect, please contact our support team
* to enable authentication for Hosting-in for you. Otherwise, Role_Subscriber
* still has the same privileges as Role_Publisher.
*/
const ROLE_SUBSCRIBER = 2;
/**
* Build the RTC token with uid.
*
* @param $appId : The App ID issued to you by Agora. Apply for a new App ID from
* Agora Dashboard if it is missing from your kit. See Get an App ID.
* @param $appCertificate : Certificate of the application that you registered in
* the Agora Dashboard. See Get an App Certificate.
* @param $channelName : Unique channel name for the AgoraRTC session in the string format
* @param $uid : User ID. A 32-bit unsigned integer with a value ranging from 1 to (2^32-1).
* uid must be unique.
* @param $role : ROLE_PUBLISHER: A broadcaster/host in a live-broadcast profile.
* ROLE_SUBSCRIBER: An audience(default) in a live-broadcast profile.
* @param $tokenExpire : Represented by the number of seconds elapsed since now. If, for example, you want to access the Agora Service within 10 minutes after the token is generated, set $tokenExpire as 600(seconds).
* @param $privilegeExpire :Represented by the number of seconds elapsed since now. If, for example, you want to enable your privilege for 10 minutes, set $privilegeExpire as 600(seconds).
* @return The RTC token.
*/
public static function buildTokenWithUid($appId, $appCertificate, $channelName, $uid, $role, $tokenExpire, $privilegeExpire = 0)
{
return self::buildTokenWithUserAccount($appId, $appCertificate, $channelName, $uid, $role, $tokenExpire, $privilegeExpire);
}
/**
* Build the RTC token with account.
*
* @param $appId : The App ID issued to you by Agora. Apply for a new App ID from
* Agora Dashboard if it is missing from your kit. See Get an App ID.
* @param $appCertificate : Certificate of the application that you registered in
* the Agora Dashboard. See Get an App Certificate.
* @param $channelName : Unique channel name for the AgoraRTC session in the string format
* @param $account : The user's account, max length is 255 Bytes.
* @param $role : ROLE_PUBLISHER: A broadcaster/host in a live-broadcast profile.
* ROLE_SUBSCRIBER: An audience(default) in a live-broadcast profile.
* @param $tokenExpire : Represented by the number of seconds elapsed since now. If, for example, you want to access the Agora Service within 10 minutes after the token is generated, set $tokenExpire as 600(seconds).
* @param $privilegeExpire :Represented by the number of seconds elapsed since now. If, for example, you want to enable your privilege for 10 minutes, set $privilegeExpire as 600(seconds).
* @return The RTC token.
*/
public static function buildTokenWithUserAccount($appId, $appCertificate, $channelName, $account, $role, $tokenExpire, $privilegeExpire = 0)
{
$token = new AccessToken2($appId, $appCertificate, $tokenExpire);
$serviceRtc = new ServiceRtc($channelName, $account);
$serviceRtc->addPrivilege($serviceRtc::PRIVILEGE_JOIN_CHANNEL, $privilegeExpire);
if ($role == self::ROLE_PUBLISHER) {
$serviceRtc->addPrivilege($serviceRtc::PRIVILEGE_PUBLISH_AUDIO_STREAM, $privilegeExpire);
$serviceRtc->addPrivilege($serviceRtc::PRIVILEGE_PUBLISH_VIDEO_STREAM, $privilegeExpire);
$serviceRtc->addPrivilege($serviceRtc::PRIVILEGE_PUBLISH_DATA_STREAM, $privilegeExpire);
}
$token->addService($serviceRtc);
return $token->build();
}
/**
* Generates an RTC token with the specified privilege.
*
* This method supports generating a token with the following privileges:
* - Joining an RTC channel.
* - Publishing audio in an RTC channel.
* - Publishing video in an RTC channel.
* - Publishing data streams in an RTC channel.
*
* The privileges for publishing audio, video, and data streams in an RTC channel apply only if you have
* enabled co-host authentication.
*
* A user can have multiple privileges. Each privilege is valid for a maximum of 24 hours.
* The SDK triggers the onTokenPrivilegeWillExpire and onRequestToken callbacks when the token is about to expire
* or has expired. The callbacks do not report the specific privilege affected, and you need to maintain
* the respective timestamp for each privilege in your app logic. After receiving the callback, you need
* to generate a new token, and then call renewToken to pass the new token to the SDK, or call joinChannel to re-join
* the channel.
*
* @note
* Agora recommends setting a reasonable timestamp for each privilege according to your scenario.
* Suppose the expiration timestamp for joining the channel is set earlier than that for publishing audio.
* When the token for joining the channel expires, the user is immediately kicked off the RTC channel
* and cannot publish any audio stream, even though the timestamp for publishing audio has not expired.
*
* @param $appId The App ID of your Agora project.
* @param $appCertificate The App Certificate of your Agora project.
* @param $channelName The unique channel name for the Agora RTC session in string format. The string length must be less than 64 bytes. The channel name may contain the following characters:
* - All lowercase English letters: a to z.
* - All uppercase English letters: A to Z.
* - All numeric characters: 0 to 9.
* - The space character.
* - "!", "#", "$", "%", "&", "(", ")", "+", "-", ":", ";", "<", "=", ".", ">", "?", "@", "[", "]", "^", "_", " {", "}", "|", "~", ",".
* @param $uid The user ID. A 32-bit unsigned integer with a value range from 1 to (2^32 - 1). It must be unique. Set uid as 0, if you do not want to authenticate the user ID, that is, any uid from the app client can join the channel.
* @param $tokenExpire represented by the number of seconds elapsed since now. If, for example, you want to access the
* Agora Service within 10 minutes after the token is generated, set tokenExpire as 600(seconds).
* @param $joinChannelPrivilegeExpire represented by the number of seconds elapsed since now.
* If, for example, you want to join channel and expect stay in the channel for 10 minutes, set $joinChannelPrivilegeExpire as 600(seconds).
* @param $pubAudioPrivilegeExpire represented by the number of seconds elapsed since now.
* If, for example, you want to enable publish audio privilege for 10 minutes, set $pubAudioPrivilegeExpire as 600(seconds).
* @param $pubVideoPrivilegeExpire represented by the number of seconds elapsed since now.
* If, for example, you want to enable publish video privilege for 10 minutes, set $pubVideoPrivilegeExpire as 600(seconds).
* @param $pubDataStreamPrivilegeExpire represented by the number of seconds elapsed since now.
* If, for example, you want to enable publish data stream privilege for 10 minutes, set $pubDataStreamPrivilegeExpire as 600(seconds).
* @return The RTC Token
*/
public static function buildTokenWithUidAndPrivilege(
$appId,
$appCertificate,
$channelName,
$uid,
$tokenExpire,
$joinChannelPrivilegeExpire,
$pubAudioPrivilegeExpire,
$pubVideoPrivilegeExpire,
$pubDataStreamPrivilegeExpire
) {
return self::buildTokenWithUserAccountAndPrivilege(
$appId,
$appCertificate,
$channelName,
$uid,
$tokenExpire,
$joinChannelPrivilegeExpire,
$pubAudioPrivilegeExpire,
$pubVideoPrivilegeExpire,
$pubDataStreamPrivilegeExpire
);
}
/**
* Generates an RTC token with the specified privilege.
*
* This method supports generating a token with the following privileges:
* - Joining an RTC channel.
* - Publishing audio in an RTC channel.
* - Publishing video in an RTC channel.
* - Publishing data streams in an RTC channel.
*
* The privileges for publishing audio, video, and data streams in an RTC channel apply only if you have
* enabled co-host authentication.
*
* A user can have multiple privileges. Each privilege is valid for a maximum of 24 hours.
* The SDK triggers the onTokenPrivilegeWillExpire and onRequestToken callbacks when the token is about to expire
* or has expired. The callbacks do not report the specific privilege affected, and you need to maintain
* the respective timestamp for each privilege in your app logic. After receiving the callback, you need
* to generate a new token, and then call renewToken to pass the new token to the SDK, or call joinChannel to re-join
* the channel.
*
* @note
* Agora recommends setting a reasonable timestamp for each privilege according to your scenario.
* Suppose the expiration timestamp for joining the channel is set earlier than that for publishing audio.
* When the token for joining the channel expires, the user is immediately kicked off the RTC channel
* and cannot publish any audio stream, even though the timestamp for publishing audio has not expired.
*
* @param $appId The App ID of your Agora project.
* @param $appCertificate The App Certificate of your Agora project.
* @param $channelName The unique channel name for the Agora RTC session in string format. The string length must be less than 64 bytes. The channel name may contain the following characters:
* - All lowercase English letters: a to z.
* - All uppercase English letters: A to Z.
* - All numeric characters: 0 to 9.
* - The space character.
* - "!", "#", "$", "%", "&", "(", ")", "+", "-", ":", ";", "<", "=", ".", ">", "?", "@", "[", "]", "^", "_", " {", "}", "|", "~", ",".
* @param $account The user account.
* @param $tokenExpire represented by the number of seconds elapsed since now. If, for example, you want to access the
* Agora Service within 10 minutes after the token is generated, set tokenExpire as 600(seconds).
* @param $joinChannelPrivilegeExpire represented by the number of seconds elapsed since now.
* If, for example, you want to join channel and expect stay in the channel for 10 minutes, set $joinChannelPrivilegeExpire as 600(seconds).
* @param $pubAudioPrivilegeExpire represented by the number of seconds elapsed since now.
* If, for example, you want to enable publish audio privilege for 10 minutes, set $pubAudioPrivilegeExpire as 600(seconds).
* @param $pubVideoPrivilegeExpire represented by the number of seconds elapsed since now.
* If, for example, you want to enable publish video privilege for 10 minutes, set $pubVideoPrivilegeExpire as 600(seconds).
* @param $pubDataStreamPrivilegeExpire represented by the number of seconds elapsed since now.
* If, for example, you want to enable publish data stream privilege for 10 minutes, set $pubDataStreamPrivilegeExpire as 600(seconds).
* @return The RTC Token
*/
public static function buildTokenWithUserAccountAndPrivilege(
$appId,
$appCertificate,
$channelName,
$account,
$tokenExpire,
$joinChannelPrivilegeExpire,
$pubAudioPrivilegeExpire,
$pubVideoPrivilegeExpire,
$pubDataStreamPrivilegeExpire
) {
$token = new AccessToken2($appId, $appCertificate, $tokenExpire);
$serviceRtc = new ServiceRtc($channelName, $account);
$serviceRtc->addPrivilege($serviceRtc::PRIVILEGE_JOIN_CHANNEL, $joinChannelPrivilegeExpire);
$serviceRtc->addPrivilege($serviceRtc::PRIVILEGE_PUBLISH_AUDIO_STREAM, $pubAudioPrivilegeExpire);
$serviceRtc->addPrivilege($serviceRtc::PRIVILEGE_PUBLISH_VIDEO_STREAM, $pubVideoPrivilegeExpire);
$serviceRtc->addPrivilege($serviceRtc::PRIVILEGE_PUBLISH_DATA_STREAM, $pubDataStreamPrivilegeExpire);
$token->addService($serviceRtc);
return $token->build();
}
/**
* Build the RTC and RTM token with account.
*
* @param $appId : The App ID issued to you by Agora. Apply for a new App ID from
* Agora Dashboard if it is missing from your kit. See Get an App ID.
* @param $appCertificate : Certificate of the application that you registered in
* the Agora Dashboard. See Get an App Certificate.
* @param $channelName : Unique channel name for the AgoraRTC session in the string format
* @param $account : The user's account, max length is 255 Bytes.
* @param $role : ROLE_PUBLISHER: A broadcaster/host in a live-broadcast profile.
* ROLE_SUBSCRIBER: An audience(default) in a live-broadcast profile.
* @param $tokenExpire : Represented by the number of seconds elapsed since now. If, for example, you want to access the Agora Service within 10 minutes after the token is generated, set $tokenExpire as 600(seconds).
* @param $privilegeExpire :Represented by the number of seconds elapsed since now. If, for example, you want to enable your privilege for 10 minutes, set $privilegeExpire as 600(seconds).
* @return The RTC and RTM token.
*/
public static function buildTokenWithRtm($appId, $appCertificate, $channelName, $account, $role, $tokenExpire, $privilegeExpire = 0)
{
$token = new AccessToken2($appId, $appCertificate, $tokenExpire);
$serviceRtc = new ServiceRtc($channelName, $account);
$serviceRtc->addPrivilege($serviceRtc::PRIVILEGE_JOIN_CHANNEL, $privilegeExpire);
if ($role == self::ROLE_PUBLISHER) {
$serviceRtc->addPrivilege($serviceRtc::PRIVILEGE_PUBLISH_AUDIO_STREAM, $privilegeExpire);
$serviceRtc->addPrivilege($serviceRtc::PRIVILEGE_PUBLISH_VIDEO_STREAM, $privilegeExpire);
$serviceRtc->addPrivilege($serviceRtc::PRIVILEGE_PUBLISH_DATA_STREAM, $privilegeExpire);
}
$token->addService($serviceRtc);
$serviceRtm = new ServiceRtm($account);
$serviceRtm->addPrivilege($serviceRtm::PRIVILEGE_LOGIN, $tokenExpire);
$token->addService($serviceRtm);
return $token->build();
}
/**
* Build the RTC and RTM token with account.
*
* @param $appId The App ID issued to you by Agora. Apply for a new App ID from
* Agora Dashboard if it is missing from your kit. See Get an App ID.
* @param $appCertificate Certificate of the application that you registered in
* the Agora Dashboard. See Get an App Certificate.
* @param $channelName Unique channel name for the AgoraRTC session in the string format
* @param $rtcAccount The RTC user's account, max length is 255 Bytes.
* @param $rtcRole ROLE_PUBLISHER: A broadcaster/host in a live-broadcast profile.
* ROLE_SUBSCRIBER: An audience(default) in a live-broadcast profile.
* @param $rtcTokenExpire Represented by the number of seconds elapsed since now. If, for example, you want to access the Agora Service within 10 minutes after the token is generated, set $tokenExpire as 600(seconds).
* @param $joinChannelPrivilegeExpire represented by the number of seconds elapsed since now.
* If, for example, you want to join channel and expect stay in the channel for 10 minutes, set $joinChannelPrivilegeExpire as 600(seconds).
* @param $pubAudioPrivilegeExpire represented by the number of seconds elapsed since now.
* If, for example, you want to enable publish audio privilege for 10 minutes, set $pubAudioPrivilegeExpire as 600(seconds).
* @param $pubVideoPrivilegeExpire represented by the number of seconds elapsed since now.
* If, for example, you want to enable publish video privilege for 10 minutes, set $pubVideoPrivilegeExpire as 600(seconds).
* @param $pubDataStreamPrivilegeExpire represented by the number of seconds elapsed since now.
* If, for example, you want to enable publish data stream privilege for 10 minutes, set $pubDataStreamPrivilegeExpire as 600(seconds).
* @param $rtmUserId The RTM user's account, max length is 255 Bytes.
* @param $rtmTokenExpire represented by the number of seconds elapsed since now. If, for example,
* you want to access the Agora Service within 10 minutes after the token is generated, set $rtmTokenExpire as 600(seconds).
* @return The RTC and RTM token.
*/
public static function buildTokenWithRtm2(
$appId,
$appCertificate,
$channelName,
$rtcAccount,
$rtcRole,
$rtcTokenExpire,
$joinChannelPrivilegeExpire,
$pubAudioPrivilegeExpire,
$pubVideoPrivilegeExpire,
$pubDataStreamPrivilegeExpire,
$rtmUserId,
$rtmTokenExpire
) {
$token = new AccessToken2($appId, $appCertificate, $rtcTokenExpire);
$serviceRtc = new ServiceRtc($channelName, $rtcAccount);
$serviceRtc->addPrivilege($serviceRtc::PRIVILEGE_JOIN_CHANNEL, $joinChannelPrivilegeExpire);
if ($rtcRole == self::ROLE_PUBLISHER) {
$serviceRtc->addPrivilege($serviceRtc::PRIVILEGE_PUBLISH_AUDIO_STREAM, $pubAudioPrivilegeExpire);
$serviceRtc->addPrivilege($serviceRtc::PRIVILEGE_PUBLISH_VIDEO_STREAM, $pubVideoPrivilegeExpire);
$serviceRtc->addPrivilege($serviceRtc::PRIVILEGE_PUBLISH_DATA_STREAM, $pubDataStreamPrivilegeExpire);
}
$token->addService($serviceRtc);
$serviceRtm = new ServiceRtm($rtmUserId);
$serviceRtm->addPrivilege($serviceRtm::PRIVILEGE_LOGIN, $rtmTokenExpire);
$token->addService($serviceRtm);
return $token->build();
}
}

View File

@@ -0,0 +1,29 @@
<?php
// namespace shengwang;
require_once "AccessToken.php";
class RtmTokenBuilder
{
const RoleRtmUser = 1;
# appID: The App ID issued to you by Agora. Apply for a new App ID from
# Agora Dashboard if it is missing from your kit. See Get an App ID.
# appCertificate: Certificate of the application that you registered in
# the Agora Dashboard. See Get an App Certificate.
# channelName:Unique channel name for the AgoraRTC session in the string format
# userAccount: The user account.
# role: Role_Rtm_User = 1
# privilegeExpireTs: represented by the number of seconds elapsed since
# 1/1/1970. If, for example, you want to access the
# Agora Service within 10 minutes after the token is
# generated, set expireTimestamp as the current
# timestamp + 600 (seconds)./
public static function buildToken($appID, $appCertificate, $userAccount, $role, $privilegeExpireTs){
$token = AccessToken::init($appID, $appCertificate, $userAccount, "");
$Privileges = AccessToken::Privileges;
$token->addPrivilege($Privileges["kRtmLogin"], $privilegeExpireTs);
return $token->build();
}
}
?>

View File

@@ -0,0 +1,17 @@
<?php
$SDK_VERSION = "1";
function getToken($appid, $appcertificate, $account, $validTimeInSeconds){
global $SDK_VERSION;
$expiredTime = time() + $validTimeInSeconds;
$token_items = array();
array_push($token_items, $SDK_VERSION);
array_push($token_items, $appid);
array_push($token_items, $expiredTime);
array_push($token_items, md5($account.$appid.$appcertificate.$expiredTime));
return join(":", $token_items);
}
?>

View File

@@ -0,0 +1,84 @@
<?php
class Util
{
public static function assertEqual($expected, $actual)
{
$debug = debug_backtrace();
$info = "\n- File:" . basename($debug[1]["file"]) . ", Func:" . $debug[1]["function"] . ", Line:" . $debug[1]["line"];
if ($expected != $actual) {
echo $info . "\n Assert failed" . "\n Expected :" . $expected . "\n Actual :" . $actual;
} else {
echo $info . "\n Assert ok";
}
}
public static function packUint16($x)
{
return pack("v", $x);
}
public static function unpackUint16(&$data)
{
$up = unpack("v", substr($data, 0, 2));
$data = substr($data, 2);
return $up[1];
}
public static function packUint32($x)
{
return pack("V", $x);
}
public static function unpackUint32(&$data)
{
$up = unpack("V", substr($data, 0, 4));
$data = substr($data, 4);
return $up[1];
}
public static function packInt16($x)
{
return pack("s", $x);
}
public static function unpackInt16(&$data)
{
$up = unpack("s", substr($data, 0, 2));
$data = substr($data, 2);
return $up[1];
}
public static function packString($str)
{
return self::packUint16(strlen($str)) . $str;
}
public static function unpackString(&$data)
{
$len = self::unpackUint16($data);
$up = unpack("C*", substr($data, 0, $len));
$data = substr($data, $len);
return implode(array_map("chr", $up));
}
public static function packMapUint32($arr)
{
ksort($arr);
$kv = "";
foreach ($arr as $key => $val) {
$kv .= self::packUint16($key) . self::packUint32($val);
}
return self::packUint16(count($arr)) . $kv;
}
public static function unpackMapUint32(&$data)
{
$len = self::unpackUint16($data);
$arr = [];
for ($i = 0; $i < $len; $i++) {
$arr[self::unpackUint16($data)] = self::unpackUint32($data);
}
return $arr;
}
}

View File

@@ -0,0 +1,103 @@
<?php
include "../src/RtcTokenBuilder.php";
include "../src/RtmTokenBuilder.php";
include "TestTool.php";
$appID = "970CA35de60c44645bbae8a215061b33";
$appCertificate = "5CFd2fd1755d40ecb72977518be15d3b";
$channelName = "7d72365eb983485397e3e3f9d460bdda";
$ts = 1111111;
$salt = 1;
$uid = "2882341273";
$expiredTs = 1446455471;
$expected = "006970CA35de60c44645bbae8a215061b33IACV0fZUBw+72cVoL9eyGGh3Q6Poi8bgjwVLnyKSJyOXR7dIfRBXoFHlEAABAAAAR/QQAAEAAQCvKDdW";
$builder = AccessToken::init($appID, $appCertificate, $channelName, $uid);
$builder->message->salt = $salt;
$builder->message->ts = $ts;
$builder->addPrivilege(AccessToken::Privileges["kJoinChannel"], $expiredTs);
$result = $builder->build();
assertEqual($expected, $result);
$builder2 = AccessToken::initWithToken($expected, $appCertificate, $channelName, $uid);
$result2 = $builder2->build();
assertEqual($expected, $result2);
//test 2 uid 0 case
$appID = "970CA35de60c44645bbae8a215061b33";
$appCertificate = "5CFd2fd1755d40ecb72977518be15d3b";
$channelName = "7d72365eb983485397e3e3f9d460bdda";
$ts = 1111111;
$salt = 1;
$uid = "0";
$expiredTs = 1446455471;
$expected = "006970CA35de60c44645bbae8a215061b33IABNRUO/126HmzFc+J8lQFfnkssUdUXqiePeE2WNZ7lyubdIfRAh39v0EAABAAAAR/QQAAEAAQCvKDdW";
$builder = AccessToken::init($appID, $appCertificate, $channelName, $uid);
$builder->message->salt = $salt;
$builder->message->ts = $ts;
$builder->addPrivilege(AccessToken::Privileges["kJoinChannel"], $expiredTs);
$result = $builder->build();
assertEqual($expected, $result);
$builder2 = AccessToken::initWithToken($expected, $appCertificate, $channelName, $uid);
$result2 = $builder2->build();
assertEqual($expected, $result2);
//test 2 uid 0 number case
$appID = "970CA35de60c44645bbae8a215061b33";
$appCertificate = "5CFd2fd1755d40ecb72977518be15d3b";
$channelName = "7d72365eb983485397e3e3f9d460bdda";
$ts = 1111111;
$salt = 1;
$uid = 0;
$expiredTs = 1446455471;
$expected = "006970CA35de60c44645bbae8a215061b33IACw1o7htY6ISdNRtku3p9tjTPi0jCKf9t49UHJhzCmL6bdIfRAAAAAAEAABAAAAR/QQAAEAAQCvKDdW";
$builder = AccessToken::init($appID, $appCertificate, $channelName, $uid);
$builder->message->salt = $salt;
$builder->message->ts = $ts;
$builder->addPrivilege(AccessToken::Privileges["kJoinChannel"], $expiredTs);
$result = $builder->build();
assertEqual($expected, $result);
$builder2 = AccessToken::initWithToken($expected, $appCertificate, $channelName, $uid);
$result2 = $builder2->build();
assertEqual($expected, $result2);
$appID = "3d76392019ca47599548a67ad27c9699";
$appCertificate = "386668c56db0499791d32264810c2a29";
$channelName = "7d72365eb983485397e3e3f9d460bdda";
$uid = 2882341273;
$token = RtcTokenBuilder::buildTokenWithUid($appID, $appCertificate, $channelName, $uid, RtcTokenBuilder::RoleAttendee, $expiredTs);
$parser = AccessToken::initWithToken($token, $appCertificate, $channelName, $uid);
$privilegeKey = AccessToken::Privileges["kJoinChannel"];
assertEqual($parser->message->privileges[$privilegeKey], $expiredTs);
$userAccount = "test_user";
$token = RtmTokenBuilder::buildToken($appID, $appCertificate, $userAccount, RtmTokenBuilder::RoleRtmUser, $expiredTs);
$parser = AccessToken::initWithToken($token, $appCertificate, $channelName, $userAccount);
$privilegeKey = AccessToken::Privileges["kRtmLogin"];
assertEqual($parser->message->privileges[$privilegeKey], $expiredTs);
$appID = "";
//invalid values
$expected = "006970CA35de60c44645bbae8a215061b33IACw1o7htY6ISdNRtku3p9tjTPi0jCKf9t49UHJhzCmL6bdIfRAAAAAAEAABAAAAR/QQAAEAAQCvKDdW";
$builder = AccessToken::init($appID, $appCertificate, $channelName, $uid);
assertEqual($builder, NULL);
?>

View File

@@ -0,0 +1,47 @@
<?php
include "../src/DynamicKey5.php";
include "TestTool.php";
$appID = '970ca35de60c44645bbae8a215061b33';
$appCertificate = '5cfd2fd1755d40ecb72977518be15d3b';
$channelName = "7d72365eb983485397e3e3f9d460bdda";
$ts = 1446455472;
$randomInt = 58964981;
$uid = 2882341273;
$expiredTs = 1446455471;
function testRecordingKey($appID, $appCertificate, $channelName, $ts, $randomInt, $uid, $expiredTs)
{
$expected = "005AgAoADkyOUM5RTQ2MTg3QTAyMkJBQUIyNkI3QkYwMTg0MzhDNjc1Q0ZFMUEQAJcMo13mDERkW7roohUGGzOwKDdW9buDA68oN1YAAA==";
$actual = generateRecordingKey($appID, $appCertificate, $channelName, $ts, $randomInt, $uid, $expiredTs);
assertEqual($expected, $actual);
}
function testMediaChannelKey($appID, $appCertificate, $channelName, $ts, $randomInt, $uid, $expiredTs)
{
$expected = "005AQAoAEJERTJDRDdFNkZDNkU0ODYxNkYxQTYwOUVFNTM1M0U5ODNCQjFDNDQQAJcMo13mDERkW7roohUGGzOwKDdW9buDA68oN1YAAA==";
$actual = generateMediaChannelKey($appID, $appCertificate, $channelName, $ts, $randomInt, $uid, $expiredTs);
assertEqual($expected, $actual);
}
function testInChannelPermission($appID, $appCertificate, $channelName, $ts, $randomInt, $uid, $expiredTs)
{
global $NO_UPLOAD;
$noUpload = "005BAAoADgyNEQxNDE4M0FGRDkyOEQ4REFFMUU1OTg5NTg2MzA3MTEyNjRGNzQQAJcMo13mDERkW7roohUGGzOwKDdW9buDA68oN1YBAAEAAQAw";
$generatedNoUpload = generateInChannelPermissionKey($appID, $appCertificate, $channelName, $ts, $randomInt, $uid, $expiredTs, $NO_UPLOAD);
assertEqual($noUpload, $generatedNoUpload);
global $AUDIO_VIDEO_UPLOAD;
$audioVideoUpload = "005BAAoADJERDA3QThENTE2NzJGNjQwMzY5NTFBNzE0QkI5NTc0N0Q1QjZGQjMQAJcMo13mDERkW7roohUGGzOwKDdW9buDA68oN1YBAAEAAQAz";
$generatedAudioVideoUpload = generateInChannelPermissionKey($appID, $appCertificate, $channelName, $ts, $randomInt, $uid, $expiredTs, $AUDIO_VIDEO_UPLOAD);
assertEqual($audioVideoUpload, $generatedAudioVideoUpload);
}
testRecordingKey($appID, $appCertificate, $channelName, $ts, $randomInt, $uid, $expiredTs);
testMediaChannelKey($appID, $appCertificate, $channelName, $ts, $randomInt, $uid, $expiredTs);
testInChannelPermission($appID, $appCertificate, $channelName, $ts, $randomInt, $uid, $expiredTs);
?>

View File

@@ -0,0 +1,33 @@
<?php
include '../src/DynamicKey4.php';
include 'TestTool.php';
$appID = '970ca35de60c44645bbae8a215061b33';
$appCertificate = '5cfd2fd1755d40ecb72977518be15d3b';
$channelName = "7d72365eb983485397e3e3f9d460bdda";
$ts = 1446455472;
$randomInt = 58964981;
$uid = 2882341273;
$expiredTs = 1446455471;
function testRecordingKey($appID, $appCertificate, $channelName, $ts, $randomInt, $uid, $expiredTs)
{
$expected = '004e0c24ac56aae05229a6d9389860a1a0e25e56da8970ca35de60c44645bbae8a215061b3314464554720383bbf51446455471';
$actual = generateRecordingKey($appID, $appCertificate, $channelName, $ts, $randomInt, $uid, $expiredTs);
assertEqual($expected, $actual);
}
function testMediaChannelKey($appID, $appCertificate, $channelName, $ts, $randomInt, $uid, $expiredTs)
{
$expected = '004d0ec5ee3179c964fe7c0485c045541de6bff332b970ca35de60c44645bbae8a215061b3314464554720383bbf51446455471';
$actual = generateMediaChannelKey($appID, $appCertificate, $channelName, $ts, $randomInt, $uid, $expiredTs);
assertEqual($expected, $actual);
}
testRecordingKey($appID, $appCertificate, $channelName, $ts, $randomInt, $uid, $expiredTs);
testMediaChannelKey($appID, $appCertificate, $channelName, $ts, $randomInt, $uid, $expiredTs);
?>

View File

@@ -0,0 +1,16 @@
<?php
function assertEqual($expect, $actual)
{
if ($expect != $actual) {
echo("\n assert failed");
echo("\n expect:\n " . $expect);
echo("\n actual:\n " . $actual);
echo("\n");
} else {
echo("assert ok\n");
echo("\n");
}
}
?>