当前位置:网站首页>php 记录完整对接腾讯云直播以及im直播群聊 所遇到的坑

php 记录完整对接腾讯云直播以及im直播群聊 所遇到的坑

2022-07-07 21:43:00 游戏编程

记录一次完整对接腾讯云直播 以及直播聊天室

/**     * @param mixed $arg1     * @author xusir     * @date: 2022/6/13     * @createTime: 14:13     * @remark:开启直播     */    public function startLive(){       $post = $_POST;       if(!$post['access_token'] || !$post['live_name'] || !$post['live_img']) return $this->asJson(['code'=>1,'msg'=>'参数不全']);        $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);//推流地址        $pull_url = self::getLivePullUrl($streamName,$time);//推流地址        $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'=>'创建成功','data'=>$data]);             }else{                 return $this->asJson(['code'=>1,'msg'=>'直播间创建失败']);             }        }        $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'=>'创建成功','data'=>$data]);        }else{            return $this->asJson(['code'=>1,'msg'=>'直播间创建失败']);        }    } /**     * 获取推流地址     * @param $streamName 填写自定义的流名称 StreamName,例如:liveteststream。可以理解为唯一标识     *     * @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为配置推流域名主key,可以去腾讯控制台->域名管理->管理->推流配置 里面可以看到主key        $domain = $live['push_url'];//您的推流域名//        $time = config('live.time');//过期时间,自行设置 例: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 : "");    }    /**     * 获取 拉流 地址     * 如果不传key和过期时间,将返回不含防盗链的url     *     * @param $streamName : 您用来区别不同推流地址的唯一流名称     *     * @return String url     */    public static function getLivePullUrl($streamName,$time) {        $live = Db::name('wd_xcx_live_set')->where('uniacid',51)->find();        $domain = $live['pull_url'];//同上        $key = $live['play_key'];//同上//        $time = config('live.time');//同上        $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:获取直播间详情     */    public function getLivesDetail(){        if(!$_GET['id']) return $this->asJson(['code'=>1,'msg'=>'参数不全']);        $id = $_GET['id'];        $access_token = $_GET['access_token'];        $lives = Db::name('wd_xcx_live_home')->where(['id'=>$id])->find();        //加入群聊//        $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:群组内发送消息     */    public function sendMsg(){        $get = $_POST;        if(!$get['access_token'] || !$get['group_id'] || !$get['content']) return $this->asJson(['code'=>1,'msg'=>'参数不全']);        $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'=>'发送成功']);         }else{             return $this->asJson(['code'=>1,'msg'=>$res['ErrorInfo']]);         }    }    /**     * @param mixed $arg1     * @author xusir     * @date: 2022/6/20     * @createTime: 11:21     * @remark:获取群内人员     */    public function getGroupPeople(){        $group_id = $_GET["group_id"];        if(!$group_id) return $this->asJson(['code'=>1,'msg'=>"参数不全"]);        $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:获取直播间群成员     */    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:创建直播间群组     */    public function liveGroup($id){        //            创建直播间群组   IM创建群组        $data_ = [            'Owner_Account'=>$id,//群主userid            'GroupName' => "聊天群组",        ];        $im = new Im();        //            创建群组        $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 签名    /**     * @param mixed $arg1     * @author xusir     * @date: 2022/6/19     * @createTime: 16:56     * @remark:获取直播im sign     */    public function getSion(){        include_once "TLSSigAPIv2.php";//签名生成        $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";//签名生成        $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位随机数     */    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:生成完整请求地址     */    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:注册账号     */    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:删除账号     */    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:查询账号     */    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:查询账号在线状态     */    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:腾讯云创建群组     */    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, // 群主的 UserId(选填)        //       "Type"=> "Public", // 群组类型:Private/Public/ChatRoom/AVChatRoom        //       "Name"=> $TestGroup, // 群名称(必填)        //   "Introduction"=> $Introduction, // 群简介(选填)        //   "Notification"=> $Notification, // 群公告(选填)        //   "FaceUrl"=>$FaceUrl, // 群头像 URL(选填)        //   "MaxMemberCount"=> 500, // 最大群成员数量(选填)        //   "ApplyJoinOption"=> "FreeAccess"  // 申请加群处理方式(选填)        $request = $this->curl_post($url, $data);        return json_decode($request,true);    }    /**     * @param mixed $arg1     * @author xusir     * @date: 2022/6/19     * @createTime: 18:09     * @remark:获取直播群在线人数     */    public function get_online_member_num($GroupId) {        //   设置管理元        $data=[            "GroupId"=>$GroupId, // 要操作的群组(必填)        ];        $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:增加群成员     */    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:删除群成员     */    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:群组内发送普通消息     */    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'],//发送人            "MsgBody"=> [[                "MsgType"=>'TIMTextElem',                "MsgContent"=>[                    'Text'=>$sendArr['text']                ],            ]],//发送人        ];        $s = $this->curl_post($url,$data);        return json_decode($s,true);    }    /**     * @param mixed $arg1     * @author xusir     * @date: 2022/6/20     * @createTime: 11:35     * @remark:获取群组成员信息     */    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回调     */    public  function callBack(){//        $post = $_POST;        $json_params = file_get_contents("php://input");        Log::write("回调".$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){ // 模拟提交数据函数        $data  = json_encode($data);        $curl = curl_init();        curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);    //HTTP浏览器访问版本        curl_setopt($curl, CURLOPT_HEADER, false);                          //头部信息        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);                   //返回的内容作为变量储存        curl_setopt($curl, CURLOPT_URL, $url);                              //访问网址        curl_setopt($curl, CURLOPT_POST, true);                             //post请求        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);                      //请求数据        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,false);                   //对认证证书来源的检查        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);                  //从证书中检查SSL加密算法是否存在        $result = curl_exec($curl);                                         //抓取URL并把它传递给浏览器        curl_close($curl);                                                  //关闭当前curl        return $result;    }}

注释:腾讯直播群 不支持服务端api 退群 拉取群消息 以及加入群 需要通过腾讯sdk进行操作
直播群不支持群消息漫游,前端对接可参考官网群功能:
https://cloud.tencent.com/document/product/269/43002
作者:未曾去过倒悬山-

游戏编程,一个游戏开发收藏夹~

如果图片长时间未显示,请使用Chrome内核浏览器。

原网站

版权声明
本文为[游戏编程]所创,转载请带上原文链接,感谢
https://www.233tw.com/php/134413