腾讯云即时通信 IM 服务端 SDK for PHP
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了腾讯云即时通信 IM 服务端 SDK for PHP相关的知识,希望对你有一定的参考价值。
使用本扩展前需要登录 即时通信 IM 控制台 创建应用,配置管理员、获取 app_id、Key 等关键信息更多请查看并熟读 即时通信 IM 服务端API , REST API 接口列表
一 腾讯云IM API(tp5通常放在extend目录下)
<?php
namespace tencentyunim;
/**
-
腾讯IM API
*/
class im{
private $sdkappid; // 创建应用时即时通信 IM 控制台分配的 SDKAppID
private $identifier; // 必须为 App 管理员帐号
private $key; // 私钥
private $usersig; // 签名
private $random; // 随机数
private $postfix; // url参数
public function __construct($sdkappid,$identifier,$key) {
$this->sdkappid = $sdkappid;
$this->identifier = $identifier;
$this->key = $key;
$this->usersig = $this->genSig($identifier);
$this->random = (int)$this->nonce_str();
$this->postfix = ‘?sdkappid=‘.$this->sdkappid.‘&identifier=‘.$this->identifier.‘&usersig=‘.$this->usersig.‘&random=‘.$this->random.‘&contenttype=json‘;
}
/**- 用于 url 的 base64 encode
- ‘+‘ => ‘*‘, ‘/‘ => ‘-‘, ‘=‘ => ‘_‘
- @param string $string 需要编码的数据
- @return string 编码后的base64串,失败返回false
- @throws Exception
/
private function base64_url_encode($string) {
static $replace = Array(‘+‘ => ‘‘, ‘/‘ => ‘-‘, ‘=‘ => ‘_‘);
$base64 = base64_encode($string);
if ($base64 === false) {
throw new Exception(‘base64_encode error‘);
}
return str_replace(array_keys($replace), array_values($replace), $base64);
}
/** - 用于 url 的 base64 decode
- ‘+‘ => ‘*‘, ‘/‘ => ‘-‘, ‘=‘ => ‘_‘
- @param string $base64 需要解码的base64串
- @return string 解码后的数据,失败返回false
- @throws Exception
/
private function base64_url_decode($base64) {
static $replace = Array(‘+‘ => ‘‘, ‘/‘ => ‘-‘, ‘=‘ => ‘_‘);
$string = str_replace(array_values($replace), array_keys($replace), $base64);
$result = base64_decode($string);
if ($result == false) {
throw new Exception(‘base64_url_decode error‘);
}
return $result;
}
/** - 使用 hmac sha256 生成 sig 字段内容,经过 base64 编码
- @param $identifier 用户名,utf-8 编码
- @param $curr_time 当前生成 sig 的 unix 时间戳
- @param $expire 有效期,单位秒
- @param $base64_userbuf base64 编码后的 userbuf
- @param $userbuf_enabled 是否开启 userbuf
- @return string base64 后的 sig
*/
private function hmacsha256($identifier, $curr_time, $expire, $base64_userbuf, $userbuf_enabled) {
$content_to_be_signed = "TLS.identifier:" . $identifier . " "
. "TLS.sdkappid:" . $this->sdkappid . " "
. "TLS.time:" . $curr_time . " "
. "TLS.expire:" . $expire . " ";
if (true == $userbuf_enabled) {
$content_to_be_signed .= "TLS.userbuf:" . $base64_userbuf . " ";
}
return base64_encode(hash_hmac( ‘sha256‘, $content_to_be_signed, $this->key, true));
}
/** - 生成签名。
- @param $identifier 用户账号
- @param int $expire 过期时间,单位秒,默认 180 天
- @param $userbuf base64 编码后的 userbuf
- @param $userbuf_enabled 是否开启 userbuf
- @return string 签名字符串
- @throws Exception
*/
private function __genSig($identifier, $expire, $userbuf, $userbuf_enabled) {
$curr_time = time();
$sig_array = Array(
‘TLS.ver‘ => ‘2.0‘,
‘TLS.identifier‘ => strval($identifier),
‘TLS.sdkappid‘ => intval($this->sdkappid),
‘TLS.expire‘ => intval($expire),
‘TLS.time‘ => intval($curr_time)
);
$base64_userbuf = ‘‘;
if (true == $userbuf_enabled) {
$base64_userbuf = base64_encode($userbuf);
$sig_array[‘TLS.userbuf‘] = strval($base64_userbuf);
}
$sig_array[‘TLS.sig‘] = $this->hmacsha256($identifier, $curr_time, $expire, $base64_userbuf, $userbuf_enabled);
if ($sig_array[‘TLS.sig‘] === false) {
throw new Exception(‘base64_encode error‘);
}
$json_str_sig = json_encode($sig_array);
if ($json_str_sig === false) {
throw new Exception(‘json_encode error‘);
}
$compressed = gzcompress($json_str_sig);
if ($compressed === false) {
throw new Exception(‘gzcompress error‘);
}
return $this->base64_url_encode($compressed);
}
/** - 生成签名
- @param $identifier 用户账号
- @param int $expire 过期时间,单位秒,默认 180 天
- @return string 签名字符串
- @throws Exception
/
public function genSig($identifier, $expire=6060*24) {
return $this->__genSig($identifier, $expire, ‘‘, false);
}
/** - 带 userbuf 生成签名。
- @param $identifier 用户账号
- @param int $expire 过期时间,单位秒,默认 180 天
- @param string $userbuf 用户数据
- @return string 签名字符串
- @throws Exception
*/
public function genSigWithUserBuf($identifier, $expire, $userbuf) {
return $this->__genSig($identifier, $expire, $userbuf, true);
}
/** - 验证签名。
- @param string $sig 签名内容
- @param string $identifier 需要验证用户名,utf-8 编码
- @param int $init_time 返回的生成时间,unix 时间戳
- @param int $expire_time 返回的有效期,单位秒
- @param string $userbuf 返回的用户数据
- @param string $error_msg 失败时的错误信息
- @return boolean 验证是否成功
- @throws Exception
*/
private function __verifySig($sig, $identifier, &$init_time, &$expire_time, &$userbuf, &$error_msg) {
try {
$error_msg = ‘‘;
$compressed_sig = $this->base64_url_decode($sig);
$pre_level = error_reporting(E_ERROR);
$uncompressed_sig = gzuncompress($compressed_sig);
error_reporting($pre_level);
if ($uncompressed_sig === false) {
throw new Exception(‘gzuncompress error‘);
}
$sig_doc = json_decode($uncompressed_sig);
if ($sig_doc == false) {
throw new Exception(‘json_decode error‘);
}
$sig_doc = (array)$sig_doc;
if ($sig_doc[‘TLS.identifier‘] !== $identifier) {
throw new Exception("identifier dosen‘t match");
}
if ($sig_doc[‘TLS.sdkappid‘] != $this->sdkappid) {
throw new Exception("sdkappid dosen‘t match");
}
$sig = $sig_doc[‘TLS.sig‘];
if ($sig == false) {
throw new Exception(‘sig field is missing‘);
}
$init_time = $sig_doc[‘TLS.time‘];
$expire_time = $sig_doc[‘TLS.expire‘];
$curr_time = time();
if ($curr_time > $init_time+$expire_time) {
throw new Exception(‘sig expired‘);
}
$userbuf_enabled = false;
$base64_userbuf = ‘‘;
if (isset($sig_doc[‘TLS.userbuf‘])) {
$base64_userbuf = $sig_doc[‘TLS.userbuf‘];
$userbuf = base64_decode($base64_userbuf);
$userbuf_enabled = true;
}
$sigCalculated = $this->hmacsha256($identifier, $init_time, $expire_time, $base64_userbuf, $userbuf_enabled);
if ($sig != $sigCalculated) {
throw new Exception(‘verify failed‘);
}
return true;
} catch (Exception $ex) {
$error_msg = $ex->getMessage();
return false;
}
}
/** - 带 userbuf 验证签名。
- @param string $sig 签名内容
- @param string $identifier 需要验证用户名,utf-8 编码
- @param int $init_time 返回的生成时间,unix 时间戳
- @param int $expire_time 返回的有效期,单位秒
- @param string $error_msg 失败时的错误信息
- @return boolean 验证是否成功
- @throws Exception
*/
public function verifySig($sig, $identifier, &$init_time, &$expire_time, &$error_msg) {
$userbuf = ‘‘;
return $this->__verifySig($sig, $identifier, $init_time, $expire_time, $userbuf, $error_msg);
}
/** - 验证签名
- @param string $sig 签名内容
- @param string $identifier 需要验证用户名,utf-8 编码
- @param int $init_time 返回的生成时间,unix 时间戳
- @param int $expire_time 返回的有效期,单位秒
- @param string $userbuf 返回的用户数据
- @param string $error_msg 失败时的错误信息
- @return boolean 验证是否成功
- @throws Exception
*/
public function verifySigWithUserBuf($sig, $identifier, &$init_time, &$expire_time, &$userbuf, &$error_msg) {
return $this->__verifySig($sig, $identifier, $init_time, $expire_time, $userbuf, $error_msg);
}
/****账号管理***/
/** - 创建IM用户
- [set_user description]
- @Author 念天地之悠悠
- @DateTime 2019-12-23
- @param [type] $uid [description] 用户id(用户名)
- @param [type] $nickname [description] 用户昵称
- @param [type] $img_url [description] 头像地址
*/
public function set_user($uid,$nickname,$img_url){
$url = ‘https://console.tim.qq.com/v4/im_open_login_svc/account_import‘.$this->postfix;
$list = [‘Identifier‘=>(string)$uid,‘Nick‘=>$nickname,‘FaceUrl‘=>$img_url];
$json = json_encode($list,JSON_UNESCAPED_UNICODE);
$info = $this->http_request($url,$json);
$info = json_decode($info,true);
return $info;
}
/** - 检查用户是否存在
- [verify_user description]
- @Author 念天地之悠悠
- @DateTime 2019-12-24
- @param [array] $uids [description] 用户id(用户名) 例如:[4,5]
- @return [type] [description]
*/
public function verify_user($uids){
$url = ‘https://console.tim.qq.com/v4/im_open_login_svc/account_check‘.$this->postfix;
$arr = [];
foreach ($uids as $key => $value) {
$arr[] = [‘UserID‘=>(string)$value];
}
$data = [‘CheckItem‘=>$arr];
$data = json_encode($data);
$info = $this->http_request($url,$data);
$info = json_decode($info,true);
return $info;
}
/** - 删除用户
- [del_user description]
- @Author 念天地之悠悠
- @DateTime 2019-12-24
- @param [array] $uids [description] 用户id(用户名) 例如:[4,5]
- @return [type] [description]
*/
public function del_user($uids){
$url = ‘https://console.tim.qq.com/v4/im_open_login_svc/account_delete‘.$this->postfix;
$arr = [];
foreach ($uids as $key => $value) {
$arr[] = [‘UserID‘=>(string)$value];
}
$data = [‘DeleteItem‘=>$arr];
$data = json_encode($data);
$info = $this->http_request($url,$data);
$info = json_decode($info,true);
return $info;
}
/** - 本接口适用于将 App 用户帐号的登录态(如 UserSig)失效。
- 例如,开发者判断一个用户为恶意帐号后,可以调用本接口将该用户当前的登录态失效,这样用户使用历史 UserSig 登录即时通信 IM 会失败。
- [kick_user description]
- @Author 念天地之悠悠
- @DateTime 2019-12-24
- @param [type] $uid [description] 用户id(用户名)
- @return [type] [description]
*/
public function kick_user($uid){
$url = ‘https://console.tim.qq.com/v4/im_open_login_svc/kick‘.$this->postfix;
$data = json_encode([‘Identifier‘=>(string)$uid]);
$info = $this->http_request($url,$data);
$info = json_decode($info,true);
return $info;
}
/****单聊消息管理***/
/** - 单发单聊消息
- [push_msg description]
- @Author 念天地之悠悠
- @DateTime 2019-12-24
- @param [type] $From_Account [description] 消息发送方 Identifier(用于指定发送消息方帐号)传空表示管理员发送信息
- @param [type] $To_Account [description] 消息接收方 Identifier
- @param [type] $MsgBody [description] 消息体
- @param [type] $SyncOtherMachine [description] 1:把消息同步到 From_Account 在线终端和漫游上;2:消息不同步至 From_Account
-
@return [type] [description]
*/
public function push_msg($From_Account=‘‘,$To_Account,$MsgBody,$SyncOtherMachine=1){
$url = ‘https://console.tim.qq.com/v4/openim/sendmsg‘.$this->postfix;
$data = [
‘SyncOtherMachine‘ => (int)$SyncOtherMachine,
‘To_Account‘ => (string)$To_Account,
‘MsgRandom‘ => (int)$this->nonce_str(8), // 随机数
‘MsgTimeStamp‘ => time(), // 时间戳
‘MsgBody‘ => [$MsgBody],
];if (!empty($From_Account)) {
$data[‘From_Account‘] = (string)$From_Account;
}
$data = json_encode($data,JSON_UNESCAPED_UNICODE);
$info = $this->http_request($url,$data);
$info = json_decode($info,true);
return $info;
}
/** - 批量单发消息
- [batch_sendmsg description]
- @Author 念天地之悠悠
- @DateTime 2019-12-25
- @param [type] $To_Account [description] 接收方列表 如[‘user1‘,‘user2‘]
- @param [type] $MsgBody [description] 消息体
- @param [type] $From_Account [description] 发送人uid
- @param integer $SyncOtherMachine [description] 1:把消息同步到 From_Account 在线终端和漫游上;2:消息不同步至 From_Account
- @return [type] [description]
*/
public function batch_sendmsg($To_Account,$MsgBody,$From_Account,$SyncOtherMachine=2){
$url = ‘https://console.tim.qq.com/v4/openim/batchsendmsg‘.$this->postfix;
$data = [
‘SyncOtherMachine‘ => $SyncOtherMachine,
"From_Account" => (string)$From_Account,
‘To_Account‘ => $To_Account,
‘MsgRandom‘ => (int)$this->nonce_str(8),
‘MsgBody‘ => [$MsgBody]
];
$data = json_encode($data,JSON_UNESCAPED_UNICODE);
$info = $this->http_request($url,$data);
$info = json_decode($info,true);
return $info;
}
/** - 撤回单聊消息
- [msg_withdraw description]
- @Author 念天地之悠悠
- @DateTime 2019-12-25
- @param [type] $From_Account [description] 消息发送方 UserID
- @param [type] $To_Account [description] 消息接收方 UserID
- @param [type] $MsgKey [description] 待撤回消息的唯一标识
- @return [type] [description]
*/
public function msg_withdraw($From_Account,$To_Account,$MsgKey){
$url = ‘https://console.tim.qq.com/v4/openim/admin_msgwithdraw‘.$this->postfix;
$data = [
‘From_Account‘ => (string)$From_Account,
‘To_Account‘ => (string)$To_Account,
‘MsgKey‘ => $MsgKey
];
$data = json_encode($data,JSON_UNESCAPED_UNICODE);
$info = $this->http_request($url,$data);
$info = json_decode($info,true);
return $info;
}
/** - 查询用户状态
- [query_state description]
- @Author 念天地之悠悠
- @DateTime 2019-12-25
- @param [type] $uids [description] 用户id集 例如 [‘user1‘,‘user0‘]
- @return [type] [description]
*/
public function query_state($uids){
$url = ‘https://console.tim.qq.com/v4/openim/querystate‘.$this->postfix;
foreach ($uids as $key => $value) {
$uids[$key] = (string)$value;
}
$data = [‘To_Account‘ => $uids];
$data = json_encode($data,JSON_UNESCAPED_UNICODE);
$info = $this->http_request($url,$data);
$info = json_decode($info,true);
return $info;
}
/****用户资料管理***/
/** - 获取用户信息
- [portrait_get description]
- @Author 念天地之悠悠
- @DateTime 2019-12-31
- @param [type] $uids [description] 用户id
- @return [type] [description]
*/
public function portrait_get($uids){
$url = ‘https://console.tim.qq.com/v4/profile/portrait_get‘.$this->postfix;
foreach ($uids as $key => $value) {
$uids[$key] = (string)$value;
}
// 加好友验证方式
// AllowType_Type_NeedConfirm:需要经过自己确认才能添加自己为好友
// AllowType_Type_AllowAny:允许任何人添加自己为好友
// AllowType_Type_DenyAny:不允许任何人添加自己为好友
// 所在地
// 长度不得超过16个字节,推荐用法如下:
// App 本地定义一套数字到地名的映射关系
// 后台实际保存的是4个 uint32_t 类型的数字
// 其中第一个 uint32_t 表示国家
// 第二个 uint32_t 用于表示省份
// 第三个 uint32_t 用于表示城市
// 第四个 uint32_t 用于表示区县
$data = [
‘To_Account‘ => $uids,
‘TagList‘ => [
‘Tag_Profile_IM_Nick‘, // 昵称
‘Tag_Profile_IM_Gender‘, // 性别 Gender_Type_Unknown 未设置 Gender_Type_Female 女 Gender_Type_Male 男
‘Tag_Profile_IM_BirthDay‘, // 生日 推荐用法:20190419
‘Tag_Profile_IM_Location‘, // 所在地
‘Tag_Profile_IM_SelfSignature‘, // 个性签名
‘Tag_Profile_IM_AllowType‘, // 加好友验证方式
‘Tag_Profile_IM_Language‘, // 语言
‘Tag_Profile_IM_Image‘, // 头像URL
‘Tag_Profile_IM_MsgSettings‘, // 消息设置 Bit0:置0表示接收消息,置1则不接收消息
‘Tag_Profile_IM_AdminForbidType‘, // 管理员禁止加好友标识 AdminForbid_Type_None允许 AdminForbid_Type_SendOut禁止
‘Tag_Profile_IM_Level‘, // 等级
‘Tag_Profile_IM_Role‘, // 角色
]
];
$data = json_encode($data,JSON_UNESCAPED_UNICODE);
$info = $this->http_request($url,$data);
$info = json_decode($info,true);
return $info;
}
/** - 设置用户资料
- [portrait_set description]
- @Author 念天地之悠悠
- @DateTime 2019-12-25
- @param [type] $From_Account [description] 需要设置该 Identifier 的资料
- @param [type] $ProfileItem [description] 待设置的用户的资料对象数组,数组中每一个对象都包含了 Tag 和 Value
- @return [type] [description]
*/
public function portrait_set($From_Account,$ProfileItem){
$url = ‘https://console.tim.qq.com/v4/profile/portrait_set‘.$this->postfix;
$data = [
‘From_Account‘ => (string)$From_Account,
‘ProfileItem‘ => $ProfileItem
];
$data = json_encode($data,JSON_UNESCAPED_UNICODE);
$info = $this->http_request($url,$data);
$info = json_decode($info,true);
return $info;
}
/****好友管理***/
/** - 添加好友
- [friend_add description]
- @Author 念天地之悠悠
- @DateTime 2019-12-25
- @param [type] $From_Account [description] 需要为该 UserID 添加好友
- @param [type] $To_Account [description] 好友的 UserID
- @param [type] $AddSource [description] 加好友来源字段 加好友来源的关键字是 android,则加好友来源字段是:AddSource_Type_Android
- @param [type] $Remark [description] 好友备注
- @param [type] $GroupName [description] 分组信息
- @param [type] $AddWording [description] 形成好友关系时的附言信息
- @param [type] $AddType [description] 加好友方式 Add_Type_Single 表示单向加好友 Add_Type_Both 表示双向加好友
- @param integer $ForceAddFlags [description] 管理员强制加好友标记:1表示强制加好友,0表示常规加好友方式
- @return [type] [description]
*/
public function friend_add($From_Account,$To_Account,$AddSource,$Remark,$GroupName,$AddWording=‘‘,$AddType=‘Add_Type_Both‘,$ForceAddFlags=1){
$url = ‘https://console.tim.qq.com/v4/sns/friend_add‘.$this->postfix;
$AddFriendItem[‘To_Account‘] = $To_Account;
$AddFriendItem[‘AddSource‘] = ‘AddSourceType‘.$AddSource;
if (!empty($Remark)) {
$AddFriendItem[‘Remark‘] = $Remark;
}
if (!empty($GroupName)) {
$AddFriendItem[‘GroupName‘] = $GroupName;
}
if (!empty($AddWording)) {
$AddFriendItem[‘AddWording‘] = $AddWording;
}
$data = [
‘From_Account‘ => (string)$From_Account,
‘AddFriendItem‘ => [$AddFriendItem],
‘AddType‘ => $AddType,
‘ForceAddFlags‘ => $ForceAddFlags
];
$data = json_encode($data,JSON_UNESCAPED_UNICODE);
$info = $this->http_request($url,$data);
$info = json_decode($info,true);
return $info;
}
/** - 删除好友
- [friend_delete description]
- @Author 念天地之悠悠
- @DateTime 2019-12-26
- @param [type] $From_Account [description] 发起用户
- @param [type] $To_Account [description] 被删用户数组
- @param string $DeleteType [description] 类型 Delete_Type_Both 双向删除 CheckResult_Type_Single 单向删除
- @return [type] [description]
*/
public function friend_delete($From_Account,$To_Account,$DeleteType=‘Delete_Type_Both‘){
$url = ‘https://console.tim.qq.com/v4/sns/friend_delete‘.$this->postfix;
$data = [
‘From_Account‘ => (string)$From_Account,
‘To_Account‘ => $To_Account,
‘DeleteType‘ => $DeleteType
];
$data = json_encode($data,JSON_UNESCAPED_UNICODE);
$info = $this->http_request($url,$data);
$info = json_decode($info,true);
return $info;
}
/** - 添加黑名单
- [black_list_add description]
- @Author 念天地之悠悠
- @DateTime 2019-12-26
- @param [type] $From_Account [description] 发起用户
- @param [type] $To_Account [description] 对象用户数组
- @return [type] [description]
*/
public function black_list_add($From_Account,$To_Account){
$url = ‘https://console.tim.qq.com/v4/sns/black_list_add‘.$this->postfix;
$data = [
‘From_Account‘ => (string)$From_Account,
‘To_Account‘ => $To_Account
];
$data = json_encode($data,JSON_UNESCAPED_UNICODE);
$info = $this->http_request($url,$data);
$info = json_decode($info,true);
return $info;
}
/** - 删除黑名单
- [black_list_delete description]
- @Author 念天地之悠悠
- @DateTime 2019-12-26
- @param [type] $From_Account [description] 发起用户
- @param [type] $To_Account [description] 对象用户数组
- @return [type] [description]
*/
public function black_list_delete($From_Account,$To_Account){
$url = ‘https://console.tim.qq.com/v4/sns/black_list_delete‘.$this->postfix;
$data = [
‘From_Account‘ => (string)$From_Account,
‘To_Account‘ => $To_Account
];
$data = json_encode($data,JSON_UNESCAPED_UNICODE);
$info = $this->http_request($url,$data);
$info = json_decode($info,true);
return $info;
}
/** - curl请求
- [http_request description]
- @Author 念天地之悠悠
- @DateTime 2019-02-21
- @param [type] $url [description] 请求地址
- @param [type] $data [description] 数据
- @param array $headers [description]
- @return [type] [description]
*/
public function http_request($url,$data = null,$headers=array()){
$curl = curl_init();
if( count($headers) >= 1 ){
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
}
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
if (!empty($data)){
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
return $output;
}
/** - 随机32位字符串 纯数字
- [nonce_str description]
- @Author 念天地之悠悠
- @DateTime 2019-12-23
- @return [type] [description]
*/
private function nonce_str($num=32){
$result = ‘‘;
$str = ‘0123456789‘;
for ($i = 0; $i < $num; $i++) {
$result .= $str[rand(0,9)];
}
return $result;
}
}
?>二 引入IM API,编写通讯接口
<?php
namespace appapicontroller;
use appcommoncontrollerBase;
use thinkValidate;
use thinkDb;
use tencentyunimim as Tim;
/**
- 通讯
*/
class Im extends Base{
/**- 单发消息
- [send_msg description]
- @Author 念天地之悠悠
- @DateTime 2019-12-25
- @return [type] [description]
*/
public function send_msg(){
$post_data = input(‘post.‘);
$config = config(‘site‘);
$im = new Tim($config[‘SdkAppid‘],$config[‘Identifier‘],$config[‘im_appkey‘]);
// MsgType 目前支持的消息对象包括:TIMTextElem(文本消息),TIMFaceElem(表情消息),TIMLocationElem(位置消息)
$MsgBody[‘MsgType‘] = $post_data[‘MsgType‘];
if ($post_data[‘MsgType‘] == ‘TIMTextElem‘) {
$MsgBody[‘MsgContent‘] = [‘Text‘=>$post_data[‘txt‘]];
}elseif ($post_data[‘MsgType‘] == ‘TIMFaceElem‘) {
$MsgBody[‘MsgContent‘] = [‘Index‘=>$post_data[‘Index‘],‘Data‘=>$post_data[‘Data‘]];
}elseif ($post_data[‘MsgType‘] == ‘TIMLocationElem‘) {
$MsgBody[‘MsgContent‘] = [
‘Desc‘ => $post_data[‘Desc‘],
‘Latitude‘ => $post_data[‘Latitude‘],
‘Longitude‘ => $post_data[‘Longitude‘]
];
}else{
return json(returnArr(2,‘‘,‘消息类型错误!‘));
}
$info = $im->push_msg($post_data[‘uid‘],$post_data[‘To_Account‘],$MsgBody,$post_data[‘SyncOtherMachine‘]);
if ($info[‘ErrorCode‘] == 0) {
$ret = returnArr(1,$info[‘MsgKey‘],‘发送成功!‘);
}else{
$ret = returnArr(0,‘‘,$info[‘ErrorInfo‘]);
}
return json($ret);
}
/** - 批量单发消息
- [batch_sendmsg description]
- @Author 念天地之悠悠
- @DateTime 2019-12-25
- @return [type] [description]
*/
public function batch_sendmsg(){
$post_data = input(‘post.‘);
$config = config(‘site‘);
$im = new Tim($config[‘SdkAppid‘],$config[‘Identifier‘],$config[‘im_appkey‘]);
// MsgType 目前支持的消息对象包括:TIMTextElem(文本消息),TIMFaceElem(表情消息),TIMLocationElem(位置消息)
$MsgBody[‘MsgType‘] = $post_data[‘MsgType‘];
if ($post_data[‘MsgType‘] == ‘TIMTextElem‘) {
$MsgBody[‘MsgContent‘] = [‘Text‘=>$post_data[‘txt‘]];
}elseif ($post_data[‘MsgType‘] == ‘TIMFaceElem‘) {
$MsgBody[‘MsgContent‘] = [‘Index‘=>$post_data[‘Index‘],‘Data‘=>$post_data[‘Data‘]];
}elseif ($post_data[‘MsgType‘] == ‘TIMLocationElem‘) {
$MsgBody[‘MsgContent‘] = [
‘Desc‘ => $post_data[‘Desc‘],
‘Latitude‘ => $post_data[‘Latitude‘],
‘Longitude‘ => $post_data[‘Longitude‘]
];
}else{
return json(returnArr(2,‘‘,‘消息类型错误!‘));
}
$users = explode(‘,‘, $post_data[‘To_Account‘]);
$info = $im->batch_sendmsg($users,$MsgBody,$post_data[‘uid‘]);
if ($info[‘ErrorCode‘] == 0) {
$ret = returnArr(1,$info[‘MsgKey‘],‘发送成功!‘);
}else{
$ret = returnArr(0,‘‘,$info[‘ErrorInfo‘]);
}
return json($ret);
}
/** - 撤回单聊信息
- [msg_withdraw description]
- @Author 念天地之悠悠
- @DateTime 2019-12-25
- @return [type] [description]
*/
public function msg_withdraw(){
$post_data = input(‘post.‘);
$config = config(‘site‘);
$im = new Tim($config[‘SdkAppid‘],$config[‘Identifier‘],$config[‘im_appkey‘]);
$info = $im->msg_withdraw($post_data[‘uid‘],$post_data[‘To_Account‘],$post_data[‘MsgKey‘]);
if ($info[‘ErrorCode‘] == 0) {
$ret = returnArr(1,‘‘,‘撤回成功!‘);
}else{
$ret = returnArr(0,‘‘,$info[‘ErrorInfo‘]);
}
return json($ret);
}
/** - 查询用户在线状态
- [query_state description]
- @Author 念天地之悠悠
- @DateTime 2019-12-25
- @return [type] [description]
*/
public function query_state(){
$post_data = input(‘post.‘);
$arr = explode(‘,‘, $post_data[‘uids‘]);
if (empty($arr)) {
$ret = returnArr(2,‘‘,‘获取查询用户失败!‘);
}else{
if (count($arr) > 500) {
$ret = returnArr(3,‘‘,‘最多查询500个用户!‘);
}else{
$config = config(‘site‘);
$im = new Tim($config[‘SdkAppid‘],$config[‘Identifier‘],$config[‘im_appkey‘]);
$info = $im->query_state($arr);
if ($info[‘ErrorCode‘] == 0) {
$ret = returnArr(1,$info[‘QueryResult‘],‘查询成功!‘);
}else{
$ret = returnArr(0,‘‘,$info[‘ErrorInfo‘]);
}
}
}
return json($ret);
}
/** - 获取用户资料
- [portrait_get description]
- @Author 念天地之悠悠
- @DateTime 2019-12-25
- @return [type] [description]
*/
public function portrait_get(){
$post_data = input(‘post.‘);
$arr = explode(‘,‘, $post_data[‘uids‘]);
if (empty($arr)) {
$ret = returnArr(2,‘‘,‘获取查询用户失败!‘);
}else{
if (count($arr) > 100) {
$ret = returnArr(3,‘‘,‘最多查询100个用户!‘);
}else{
$config = config(‘site‘);
$im = new Tim($config[‘SdkAppid‘],$config[‘Identifier‘],$config[‘im_appkey‘]);
$info = $im->portrait_get($arr);
if ($info[‘ErrorCode‘] == 0) {
$ret = returnArr(1,$info[‘UserProfileItem‘],‘查询成功!‘);
}else{
$ret = returnArr(0,‘‘,$info[‘ErrorInfo‘]);
}
}
}
return json($ret);
}
/** - 设置用户资料
- [portrait_set description]
- @Author 念天地之悠悠
- @DateTime 2019-12-25
- @return [type] [description]
*/
public function portrait_set(){
$post_data = input(‘post.‘);
$arr = json_decode($post_data[‘list‘],true);
if (empty($arr)) {
$ret = returnArr(2,‘‘,‘修改参数缺失!‘);
}else{
$config = config(‘site‘);
$im = new Tim($config[‘SdkAppid‘],$config[‘Identifier‘],$config[‘im_appkey‘]);
$info = $im->portrait_set($post_data[‘uid‘],$arr);
if ($info[‘ErrorCode‘] == 0) {
$ret = returnArr(1,‘‘,‘修改成功!‘);
}else{
$ret = returnArr(0,‘‘,$info[‘ErrorInfo‘]);
}
}
return json($ret);
}
/** - 添加好友
- [friend_add description]
- @Author 念天地之悠悠
- @DateTime 2019-12-25
- @return [type] [description]
*/
public function friend_add(){
$post_data = input(‘post.‘);
$config = config(‘site‘);
$im = new Tim($config[‘SdkAppid‘],$config[‘Identifier‘],$config[‘im_appkey‘]);
$info = $im->friend_add($post_data[‘uid‘],$post_data[‘To_Account‘],$post_data[‘AddSource‘],$post_data[‘Remark‘],$post_data[‘GroupName‘],$post_data[‘AddWording‘],$post_data[‘AddType‘]);
if ($info[‘ErrorCode‘] == 0) {
$ret = returnArr(1,‘‘,‘添加成功!‘);
}else{
$ret = returnArr(0,‘‘,$info[‘ErrorInfo‘]);
}
return json($ret);
}
/** - 删除好友
- [friend_delete description]
- @Author 念天地之悠悠
- @DateTime 2019-12-26
- @return [type] [description]
*/
public function friend_delete(){
$post_data = input(‘post.‘);
$To_Account = explode(‘,‘, $post_data[‘To_Account‘]);
$config = config(‘site‘);
$im = new Tim($config[‘SdkAppid‘],$config[‘Identifier‘],$config[‘im_appkey‘]);
$info = $im->friend_delete($post_data[‘uid‘],$To_Account);
if ($info[‘ErrorCode‘] == 0) {
$ret = returnArr(1,$info[‘ResultItem‘],‘删除好友成功!‘);
}else{
$ret = returnArr(0,‘‘,$info[‘ErrorInfo‘]);
}
return json($ret);
}
/** - 加入黑名单
- [black_list_add description]
- @Author 念天地之悠悠
- @DateTime 2019-12-26
- @return [type] [description]
*/
public function black_list_add(){
$post_data = input(‘post.‘);
$To_Account = explode(‘,‘, $post_data[‘To_Account‘]);
$config = config(‘site‘);
$im = new Tim($config[‘SdkAppid‘],$config[‘Identifier‘],$config[‘im_appkey‘]);
$info = $im->black_list_add($post_data[‘uid‘],$To_Account);
if ($info[‘ErrorCode‘] == 0) {
$ret = returnArr(1,$info[‘ResultItem‘],‘成功!‘);
}else{
$ret = returnArr(0,‘‘,$info[‘ErrorInfo‘]);
}
return json($ret);
}
/** - 删除黑名单
- [black_list_delete description]
- @Author 念天地之悠悠
- @DateTime 2019-12-26
- @return [type] [description]
*/
public function black_list_delete(){
$post_data = input(‘post.‘);
$To_Account = explode(‘,‘, $post_data[‘To_Account‘]);
$config = config(‘site‘);
$im = new Tim($config[‘SdkAppid‘],$config[‘Identifier‘],$config[‘im_appkey‘]);
$info = $im->black_list_delete($post_data[‘uid‘],$To_Account);
if ($info[‘ErrorCode‘] == 0) {
$ret = returnArr(1,$info[‘ResultItem‘],‘成功!‘);
}else{
$ret = returnArr(0,‘‘,$info[‘ErrorInfo‘]);
}
return json($ret);
}
}
?>
以上是关于腾讯云即时通信 IM 服务端 SDK for PHP的主要内容,如果未能解决你的问题,请参考以下文章
新知实验室 - TRTC 实践音视频互动 Demo即时通信 IM 服务搭建
新知实验室 - TRTC 实践音视频互动 Demo即时通信 IM 服务搭建