当前位置:网站首页>PHP records the pitfalls encountered in the complete docking of Tencent cloud live broadcast and im live group chat
PHP records the pitfalls encountered in the complete docking of Tencent cloud live broadcast and im live group chat
2022-07-07 22:29:00 【Game programming】
Record a complete docking with Tencent cloud live And live chat room
/** * @param mixed $arg1 * @author xusir * @date: 2022/6/13 * @createTime: 14:13 * @remark: Open a live */ public function startLive(){ $post = $_POST; if(!$post['access_token'] || !$post['live_name'] || !$post['live_img']) return $this->asJson(['code'=>1,'msg'=>' Incomplete parameters ']); $time = date('Y-m-d H:i:s', strtotime('+365day')); $user = Db::name('wd_xcx_user')->where(['access_token'=>$post['access_token']])->find(); $streamName = $user['id']."zhibojian"; $push_url = self::getPushUrl($streamName,$time);// Streaming address $pull_url = self::getLivePullUrl($streamName,$time);// Streaming address $post['push_url'] = $push_url; $post['pull_url'] = $pull_url; $post['status'] = 1; $post['uniacid'] = 51; unset($post['suid']); $check = Db::name("wd_xcx_live_home")->where(['access_token'=>$post['access_token']])->find(); $groupId = $this->liveGroup($user['id']); if($check){// echo "<pre>";// var_dump($groupId);exit; $post['group_id'] = $groupId['GroupId']; $res = Db::name('wd_xcx_live_home')->where(['access_token'=>$post['access_token']])->update($post); if($res !=false){ $data['live_id'] = $check['id']; $data['group_id'] = $groupId['GroupId']; return $this->asJson(['code'=>0,'msg'=>' Create success ','data'=>$data]); }else{ return $this->asJson(['code'=>1,'msg'=>' Failed to create the live room ']); } } $live_id = Db::name('wd_xcx_live_home')->insertGetId($post); if($live_id){ $data['live_id'] = $live_id; $data['group_id'] = $groupId['GroupId']; return $this->asJson(['code'=>0,'msg'=>' Create success ','data'=>$data]); }else{ return $this->asJson(['code'=>1,'msg'=>' Failed to create the live room ']); } } /** * Get the streaming address * @param $streamName Fill in the custom stream name StreamName, for example :liveteststream. It can be understood as a unique identifier * * @return string */ private static function getPushUrl($streamName,$time) {// $streamName = mt_rand(0000,9999); $live = Db::name('wd_xcx_live_set')->where('uniacid',51)->find(); $key = $live['push_key']; //key Push the watershed name for the configuration key, You can go to Tencent console -> Domain name management -> management -> Push stream configuration Inside, you can see the Lord key $domain = $live['push_url'];// Your streaming domain name // $time = config('live.time');// Expiration time , Set it up by yourself example :c $txTime = strtoupper(base_convert(strtotime($time), 10, 16)); //txSecret = MD5( KEY + streamName + txTime ) $txSecret = md5($key . $streamName . $txTime); $ext_str = "?" . http_build_query(array( "txSecret" => $txSecret, "txTime" => $txTime )); return "rtmp://" . $domain . "/live/" . $streamName . (isset($ext_str) ? $ext_str : ""); } /** * obtain Pull flow Address * If you don't pass key And expiration time , Will return without chain url * * @param $streamName : The unique stream name that you use to distinguish different streaming addresses * * @return String url */ public static function getLivePullUrl($streamName,$time) { $live = Db::name('wd_xcx_live_set')->where('uniacid',51)->find(); $domain = $live['pull_url'];// ditto $key = $live['play_key'];// ditto // $time = config('live.time');// ditto $txTime = strtoupper(base_convert(strtotime($time), 10, 16)); //txSecret = MD5( KEY + streamName + txTime ) $txSecret = md5($key . $streamName . $txTime); $ext_str = "?" . http_build_query(array( "txSecret" => $txSecret, "txTime" => $txTime )); return "http://" . $domain . "/live/" . $streamName . '.flv' . (isset($ext_str) ? $ext_str : ""); }/** * @param mixed $arg1 * @author xusir * @date: 2022/6/13 * @createTime: 17:43 * @remark: Get the details of the live room */ public function getLivesDetail(){ if(!$_GET['id']) return $this->asJson(['code'=>1,'msg'=>' Incomplete parameters ']); $id = $_GET['id']; $access_token = $_GET['access_token']; $lives = Db::name('wd_xcx_live_home')->where(['id'=>$id])->find(); // Join the group chat // $user = Db::name('wd_xcx_user')->where(['access_token'=>$_GET['access_token']])->find();// $this->addGroup($lives['group_id'],$user['id']); $lives['anchor'] = Db::name('wd_xcx_user')->where(['access_token'=>$lives['access_token']])->field('id,nickname,avatar')->find(); $lives['userList'] = $lives['group_id']?$this->getGroupPeoples($lives['group_id']):[]; $lives['is_follow'] = Db::name('wd_xcx_follow_live')->where(['access_token'=>$access_token,'live_id'=>$lives['id']])->find()?true:false;// $lives['user_id'] = $user['id']; return $this->asJson(['code'=>0,'msg'=>'success','lives'=>$lives]); } /** * @param mixed $arg1 * @author xusir * @date: 2022/6/20 * @createTime: 10:52 * @remark: Send messages within the Group */ public function sendMsg(){ $get = $_POST; if(!$get['access_token'] || !$get['group_id'] || !$get['content']) return $this->asJson(['code'=>1,'msg'=>' Incomplete parameters ']); $user = Db::name('wd_xcx_user')->where(['access_token'=>$get['access_token']])->find(); $data = [ 'GroupId'=>$get['group_id'], 'From_Account'=>(string)$user['id'], 'text'=>$get['content'], ]; $im = new Im(); $res = $im->sendMsg($data); if($res['ActionStatus']=="OK" && $res['ErrorCode']==0){ return $this->asJson(['code'=>0,'msg'=>' Send successfully ']); }else{ return $this->asJson(['code'=>1,'msg'=>$res['ErrorInfo']]); } } /** * @param mixed $arg1 * @author xusir * @date: 2022/6/20 * @createTime: 11:21 * @remark: Get people in the Group */ public function getGroupPeople(){ $group_id = $_GET["group_id"]; if(!$group_id) return $this->asJson(['code'=>1,'msg'=>" Incomplete parameters "]); $im = new Im(); $res = $im->getGroupInfo($group_id); if($res['ActionStatus']=="OK" || $res['ErrorCode']==0){ $ids = []; foreach($res['MemberList'] as $k=>$v){ array_push($ids,$v['Member_Account']); } $ids = implode(',',$ids); $where['id'] =['in',$ids]; $userList = Db::name('wd_xcx_user')->where($where)->field('id,nickname,avatar')->select(); $data['users'] = $userList; $data['users_num'] = $res['MemberNum']; return $this->asJson(['code'=>0,'msg'=>'success','data'=>$data]); }else{ return $this->asJson(['code'=>1,'msg'=>$res['ErrorInfo']]); } } /** * @param mixed $arg1 * @author xusir * @date: 2022/6/20 * @createTime: 11:53 * @remark: Get the group members of the live room */ public function getGroupPeoples($group_id){// $group_id = "@TGS#aCDB6TOI2"; $im = new Im(); $res = $im->getGroupInfo($group_id); if($res['ActionStatus']=="OK" || $res['ErrorCode']==0){ $ids = []; foreach($res['MemberList'] as $k=>$v){ array_push($ids,$v['Member_Account']); } $ids = implode(',',$ids); $where['id'] =['in',$ids]; $userList = Db::name('wd_xcx_user')->where($where)->field('id,nickname,avatar')->select(); $data['users'] = $userList; $data['users_num'] = $res['MemberNum']; return $data; }else{ return $res['ErrorInfo']; } } /** * @param mixed $arg1 * @author xusir * @date: 2022/6/16 * @createTime: 10:48 * @remark: Create a live studio group */ public function liveGroup($id){ // Create a live studio group IM Create groups $data_ = [ 'Owner_Account'=>$id,// Group leader userid 'GroupName' => " Chat groups ", ]; $im = new Im(); // Create groups $create_group = $im->createGroup($data_); if($create_group['ErrorCode'] !== 0){ return ['code'=>1,'msg'=>$create_group['ErrorInfo']]; }else{ return ['code'=>0,'msg'=>'success','GroupId'=>$create_group['GroupId']]; } }
im.php
<?phpnamespace app\api\controller;use Decode\Decode\Decode;use phpmail\Phpmailer;use think\Cache;use think\Controller;use think\Db;use think\Log;use think\Session;use think\Request;use think\Exception;use think\cache\driver\Redis;use Aliyun\Core\Config;use Aliyun\Core\Profile\DefaultProfile;use Aliyun\Core\DefaultAcsClient;use Aliyun\Api\Sms\Request\V20170525\SendSmsRequest;class Im extends Controller{ public static $identifier = "administrator"; public static $sdkappid = "";//im sdkappid public static $appsecret = "";//Im Signature /** * @param mixed $arg1 * @author xusir * @date: 2022/6/19 * @createTime: 16:56 * @remark: Get live broadcast im sign */ public function getSion(){ include_once "TLSSigAPIv2.php";// Signature generation $TLSSigAPIv2 = new TLSSigAPIv2(self::$sdkappid,false); // var_dump(1);die; $TLSSigAPIv2 = new TLSSigAPIv2(self::$sdkappid,self::$appsecret); return $TLSSigAPIv2->genUserSig(self::$identifier); } public function getImSion($user_id){ include_once "TLSSigAPIv2.php";// Signature generation $TLSSigAPIv2 = new TLSSigAPIv2(self::$sdkappid,false); // var_dump(1);die; $TLSSigAPIv2 = new TLSSigAPIv2(self::$sdkappid,self::$appsecret); return $TLSSigAPIv2->genUserSig($user_id); } /** * @param mixed $arg1 * @author xusir * @date: 2022/6/19 * @createTime: 17:52 * @remark:32 Bit random number */ function randomsum($sum){ $z=""; for($i=0;$i<$sum/4;$i++){ $z .=rand(1000,9999); } return $z; } /** * @param mixed $arg1 * @author xusir * @date: 2022/6/19 * @createTime: 17:52 * @remark: Generate complete request address */ public function getUrl($url) { $new_url = $url.http_build_query(array( "sdkappid" => self::$sdkappid, "identifier" => self::$identifier, "usersig" => $this->getSion(), 'random' => $this->randomsum(32), 'contenttype' => 'json' )); return $new_url; } /** * @param mixed $arg1 * @author xusir * @date: 2022/6/19 * @createTime: 18:05 * @remark: Registered account */ public function account_import($accountData) { $url = "https://console.tim.qq.com/v4/im_open_login_svc/account_import?"; $url = $this->getUrl($url); $data = [ "UserID" => (string)$accountData['userId'], "Nick" => $accountData['nickname'], "FaceUrl" => $accountData['avatar'], ]; // var_dump($data);die; $s = $this->curl_post($url,$data); Log::record($s,'info'); return json_decode($s,true); } /** * @param mixed $arg1 * @author xusir * @date: 2022/6/19 * @createTime: 18:06 * @remark: Delete the account */ public function account_delete($DeleteItem) { $url = "https://console.tim.qq.com/v4/im_open_login_svc/account_delete?"; $url = $this->getUrl($url); $data = [ "DeleteItem" => $DeleteItem ]; // echo( json_encode($data)); $s = $this->curl_post($url,$data); return $s; } /** * @param mixed $arg1 * @author xusir * @date: 2022/6/19 * @createTime: 18:07 * @remark: Check account number */ public function account_check($CheckItem) { $url = "https://console.tim.qq.com/v4/im_open_login_svc/account_check?"; $url = $this->getUrl($url); $data = [ "CheckItem" => $CheckItem ]; // echo( json_encode($data)); $s = $this->curl_post($url,$data); return $s; } /** * @param mixed $arg1 * @author xusir * @date: 2022/6/19 * @createTime: 18:07 * @remark: Check the online status of the account */ public function querystate($To_Account ,$IsNeedDetail) { $url = "https://console.tim.qq.com/v4/im_open_login_svc/account_check?"; $url = $this->getUrl($url); $data = [ "IsNeedDetail" => $IsNeedDetail, "To_Account" => $To_Account ]; // echo( json_encode($data)); $s = $this->curl_post($url,$data); return $s; } /** * @param mixed $arg1 * @author xusir * @date: 2022/6/16 * @createTime: 10:55 * @remark: Tencent cloud creates a group */ public function createGroup($data){ $url = 'https://console.tim.qq.com/v4/group_open_http_svc/create_group?'; $url = $this->getUrl($url); $data=[ "Owner_Account"=> (string)$data['Owner_Account']?:'', "Type"=> "AVChatRoom", "Name"=> $data['GroupName'], ]; // "Owner_Account"=> $Owner_Account, // Of the group leader UserId( optional ) // "Type"=> "Public", // Group type :Private/Public/ChatRoom/AVChatRoom // "Name"=> $TestGroup, // Group name ( Required ) // "Introduction"=> $Introduction, // Group Introduction ( optional ) // "Notification"=> $Notification, // Group announcement ( optional ) // "FaceUrl"=>$FaceUrl, // Group heads URL( optional ) // "MaxMemberCount"=> 500, // Maximum number of group members ( optional ) // "ApplyJoinOption"=> "FreeAccess" // How to apply for group addition ( optional ) $request = $this->curl_post($url, $data); return json_decode($request,true); } /** * @param mixed $arg1 * @author xusir * @date: 2022/6/19 * @createTime: 18:09 * @remark: Get the number of live group online */ public function get_online_member_num($GroupId) { // Set management element $data=[ "GroupId"=>$GroupId, // Group to operate ( Required ) ]; $url = "https://console.tim.qq.com/v4/group_open_http_svc/get_online_member_num?"; $url = $this->getUrl($url); // var_dump($data);die; $s = $this->curl_post($url,$data); return $s; } /** * @param mixed $arg1 * @author xusir * @date: 2022/6/19 * @createTime: 18:09 * @remark: Add group members */ public function add_group_member($accountList) { $url = "https://console.tim.qq.com/v4/group_open_http_svc/add_group_member?"; $url = $this->getUrl($url); $data=[ "GroupId"=> $accountList['GroupId'], "Silence"=>1, "MemberList"=>$accountList['MemberList'], ]; $s = $this->curl_post($url,$data); return $s; } /** * @param mixed $arg1 * @author xusir * @date: 2022/6/19 * @createTime: 18:10 * @remark: Delete group members */ public function delete_group_member($GroupId,$MemberList) { $url = "https://console.tim.qq.com/v4/group_open_http_svc/delete_group_member?"; $url = $this->getUrl($url); $data=[ "GroupId"=> $GroupId, "Silence"=> 1, "MemberToDel_Account"=> $MemberList, ]; $s = $this->curl_post($url,$data); return json_decode($s,true); } /** * @param mixed $arg1 * @author xusir * @date: 2022/6/20 * @createTime: 09:47 * @remark: Send ordinary messages within the Group */ public function sendMsg($sendArr){ $url = "https://console.tim.qq.com/v4/group_open_http_svc/send_group_msg?"; $url = $this->getUrl($url); $data=[ "GroupId"=> $sendArr['GroupId'], "Random"=> $this->randomsum(32), "From_Account"=> $sendArr['From_Account'],// Give a person "MsgBody"=> [[ "MsgType"=>'TIMTextElem', "MsgContent"=>[ 'Text'=>$sendArr['text'] ], ]],// Give a person ]; $s = $this->curl_post($url,$data); return json_decode($s,true); } /** * @param mixed $arg1 * @author xusir * @date: 2022/6/20 * @createTime: 11:35 * @remark: Get group member information */ public function getGroupInfo($GroupId){ $url = "https://console.tim.qq.com/v4/group_open_http_svc/get_group_member_info?"; $url = $this->getUrl($url); $data=[ "GroupId"=> $GroupId, "Limit"=> 100, "Offset"=>0 ]; $s = $this->curl_post($url,$data); return json_decode($s,true); } /** * @param mixed $arg1 * @author xusir * @date: 2022/6/20 * @createTime: 09:56 * @remark:im Callback */ public function callBack(){// $post = $_POST; $json_params = file_get_contents("php://input"); Log::write(" Callback ".$json_params); $data = json_decode($json_params);// if($post['CallbackCommand']==" Group.CallbackBeforeApplyJoinGroup"){ return $this->asJson(['ActionStatus'=>"OK",'ErrorInfo'=>'','ErrorCode'=>0]);// } } function curl_post($url,$data){ // Simulate submit data function $data = json_encode($data); $curl = curl_init(); curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); //HTTP Browser access version curl_setopt($curl, CURLOPT_HEADER, false); // Header information curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // The returned contents are stored as variables curl_setopt($curl, CURLOPT_URL, $url); // Visit website curl_setopt($curl, CURLOPT_POST, true); //post request curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Request data curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,false); // Check the source of the certificate curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // Check... From the certificate SSL Whether the encryption algorithm exists $result = curl_exec($curl); // Grab URL And pass it on to the browser curl_close($curl); // Close the current curl return $result; }}
notes : Tencent live group The server is not supported api Withdraw from a group Pull group messages And join the Group Need to go through Tencent sdk To operate
Live group does not support group message roaming , For front-end docking, please refer to the official website group function :
https://cloud.tencent.com/document/product/269/43002
author : I have never been to the overhanging mountain -
Game programming , A game development favorite ~
If the picture is not displayed for a long time , Please use Chrome Kernel browser .
边栏推荐
- 三元表达式、各生成式、匿名函数
- 双塔模型的最强出装,谷歌又开始玩起“老古董”了?
- Aspose. Word operation word document (I)
- Main functions of OS, Sys and random Standard Libraries
- Programming mode - table driven programming
- php 记录完整对接腾讯云直播以及im直播群聊 所遇到的坑
- Two methods of calling WCF service by C #
- 谈谈制造企业如何制定敏捷的数字化转型策略
- How does win11 unblock the keyboard? Method of unlocking keyboard in win11
- 微服务架构开源框架详情介绍
猜你喜欢
ByteDance senior engineer interview, easy to get started, fluent
How to realize the movement control of characters in horizontal game
Matplotlib quick start
Build your own website (18)
Record a garbled code during servlet learning
双塔模型的最强出装,谷歌又开始玩起“老古董”了?
Display optimization when the resolution of easycvr configuration center video recording plan page is adjusted
Application practice | the efficiency of the data warehouse system has been comprehensively improved! Data warehouse construction based on Apache Doris in Tongcheng digital Department
How to judge whether the input content is "number"
Remember an experience of using selectmany
随机推荐
【Azure微服务 Service Fabric 】因证书过期导致Service Fabric集群挂掉(升级无法完成,节点不可用)
Implementation method of data platform landing
MIT6.S081-Lab9 FS [2021Fall]
Aspose. Word operation word document (I)
Kaggle-Titanic
. Net automapper use
大数据开源项目,一站式全自动化全生命周期运维管家ChengYing(承影)走向何方?
OpenGL job - texture
谈谈制造企业如何制定敏捷的数字化转型策略
Revit secondary development - Hide occlusion elements
Px4 autonomous flight
Overseas agent recommendation
How to close eslint related rules
How does win11 time display the day of the week? How does win11 display the day of the week today?
变量与常量
Revit secondary development - modify wall thickness
Vs custom template - take the custom class template as an example
UWA Q & a collection
Typeorm automatically generates entity classes
Get the week start time and week end time of the current date