网易云信IMweb版集成实现(PHP直接上码)

首先去网易云信官网下载web版的demo,

下面链接地址: https://github.com/netease-im/NIM_Web_Demo

嵌入到你自己使用的框架中(这里使用的是TP5)

AppKey = Config::get('on_server.AppKey'); //你的Appkey
        $this->AppSecret = Config::get('on_server.AppSecret'); //你的AppSecret
        $this->yxsdk = new yunxinServerApi($this->AppKey,$this->AppSecret,'curl');
        $this->codeMsg = require APP_PATH.'common/yxsdk/code_msg.php';  //这是code状态表
    }

    public function index(){
        return view("webdemo/im/login");
    }

    public function reg(){
        return view("webdemo/im/register");
    }

    public function main(){
        return view("webdemo/im/main");
    }

    public function cloudMsg(){
        return view("webdemo/im/cloudMsg");
    }

    public function createTeam(){
        return view("webdemo/im/createTeam");
    }

    public function teamInfo(){
        return view("webdemo/im/teamInfo");
    }

    public function teamMember(){
        return view("webdemo/im/teamMember");
    }

    public function speakBan(){
        return view("webdemo/im/speakBan");
    }

    public function netcall_meeting(){
        return view("webdemo/im/netcall_meeting");
    }

    public function selectCallMethod(){
        return view("webdemo/im/selectCallMethod");
    }
...

以上的页面都是会展示出来的,在webdemo下面的im文件夹下,

另外需要注意的是:需要手动修改HTML中资源文件地址

PS:js中包含很多图片地址需要自己去修改,才不会显示不正常

网易云信IMweb版集成实现(PHP直接上码)_第1张图片

如果需要对云信上面的数据进行本地操作,就需要用到各种云信提供的对应的api以及文档

地址: https://dev.yunxin.163.com/docs/product/IM%E5%8D%B3%E6%97%B6%E9%80%9A%E8%AE%AF/%E6%9C%8D%E5%8A%A1%E7%AB%AFAPI%E6%96%87%E6%A1%A3/%E6%8E%A5%E5%8F%A3%E6%A6%82%E8%BF%B0

以修改用户名片为例:

网易云信IMweb版集成实现(PHP直接上码)_第2张图片网易云信IMweb版集成实现(PHP直接上码)_第3张图片

api:

AppKey = $AppKey;
        $this->AppSecret = $AppSecret;
        $this->RequestType = $RequestType;
    }


    /**
     * API checksum校验生成
     * @param  void
     * @return $CheckSum(对象私有属性)
     */
    public function checkSumBuilder(){
        //此部分生成随机字符串
        $hex_digits = self::HEX_DIGITS;
        $this->Nonce;
        for($i=0;$i<128;$i++){			//随机字符串最大128个字符,也可以小于该数
            $this->Nonce.= $hex_digits[rand(0,15)];
        }
        $this->CurTime = (string)(time());	//当前时间戳,以秒为单位

        $join_string = $this->AppSecret.$this->Nonce.$this->CurTime;
        $this->CheckSum = sha1($join_string);
        //print_r($this->CheckSum);
    }


    /**
     * 将json字符串转化成php数组
     * @param  $json_str
     * @return $json_arr
     */
    public function json_to_array($json_str){
        if(is_array($json_str) || is_object($json_str)){
            $json_str = $json_str;
        }else if(is_null(json_decode($json_str))){
            $json_str = $json_str;
        }else{
            $json_str =  strval($json_str);
            $json_str = json_decode($json_str,true);
        }
        $json_arr=array();
        foreach($json_str as $k=>$w){
            if(is_object($w)){
                $json_arr[$k]= $this->json_to_array($w); //判断类型是不是object
            }else if(is_array($w)){
                $json_arr[$k]= $this->json_to_array($w);
            }else{
                $json_arr[$k]= $w;
            }
        }
        return $json_arr;
    }


    /**
     * 使用CURL方式发送post请求
     * @param  $url     [请求地址]
     * @param  $data    [array格式数据]
     * @return $请求返回结果(array)
     */
    public function postDataCurl($url,$data){
        $this->checkSumBuilder();       //发送请求前需先生成checkSum

        $timeout = 5000;
        $http_header = array(
            'AppKey:'.$this->AppKey,
            'Nonce:'.$this->Nonce,
            'CurTime:'.$this->CurTime,
            'CheckSum:'.$this->CheckSum,
            'Content-Type:application/x-www-form-urlencoded;charset=utf-8'
        );

        $postdataArray = array();
        foreach ($data as $key=>$value){
            array_push($postdataArray, $key.'='.urlencode($value));
        }
        $postdata = join('&', $postdataArray);

        $ch = curl_init();
        curl_setopt ($ch, CURLOPT_URL, $url);
        curl_setopt ($ch, CURLOPT_POST, 1);
        curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata);
        curl_setopt ($ch, CURLOPT_HEADER, false );
        curl_setopt ($ch, CURLOPT_HTTPHEADER,$http_header);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER,false); //处理http证书问题
        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);

        $result = curl_exec($ch);
        if (false === $result) {
            $result =  curl_errno($ch);
        }
        curl_close($ch);

        return $this->json_to_array($result) ;
    }


    /**
     * 使用FSOCKOPEN方式发送post请求
     * @param  $url     [请求地址]
     * @param  $data    [array格式数据]
     * @return $请求返回结果(array)
     */
    public function postDataFsockopen($url,$data){
        $this->checkSumBuilder();       //发送请求前需先生成checkSum

        // $postdata = '';
        $postdataArray = array();
        foreach ($data as $key=>$value){
            array_push($postdataArray, $key.'='.urlencode($value));
            // $postdata.= ($key.'='.urlencode($value).'&');
        }
        $postdata = join('&', $postdataArray);
        // building POST-request:
        $URL_Info=parse_url($url);
        if(!isset($URL_Info["port"])){
            $URL_Info["port"]=80;
        }
        $request = '';
        $request.="POST ".$URL_Info["path"]." HTTP/1.1\r\n";
        $request.="Host:".$URL_Info["host"]."\r\n";
        $request.="Content-type: application/x-www-form-urlencoded;charset=utf-8\r\n";
        $request.="Content-length: ".strlen($postdata)."\r\n";
        $request.="Connection: close\r\n";
        $request.="AppKey: ".$this->AppKey."\r\n";
        $request.="Nonce: ".$this->Nonce."\r\n";
        $request.="CurTime: ".$this->CurTime."\r\n";
        $request.="CheckSum: ".$this->CheckSum."\r\n";
        $request.="\r\n";
        $request.=$postdata."\r\n";

        // print_r($request);
        $fp = fsockopen($URL_Info["host"],$URL_Info["port"]);
        fputs($fp, $request);
        $result = '';
        while(!feof($fp)) {
            $result .= fgets($fp, 128);
        }
        fclose($fp);

        $str_s = strpos($result,'{');
        $str_e = strrpos($result,'}');
        $str = substr($result, $str_s,$str_e-$str_s+1);
        return $this->json_to_array($str);
    }


    /**
     * 使用CURL方式发送post请求(JSON类型)
     * @param  $url 	[请求地址]
     * @param  $data    [array格式数据]
     * @return $请求返回结果(array)
     */
    public function postJsonDataCurl($url,$data){
        $this->checkSumBuilder();		//发送请求前需先生成checkSum

        $timeout = 5000;
        $http_header = array(
            'AppKey:'.$this->AppKey,
            'Nonce:'.$this->Nonce,
            'CurTime:'.$this->CurTime,
            'CheckSum:'.$this->CheckSum,
            'Content-Type:application/json;charset=utf-8'
        );

        $postdata = json_encode($data);

        $ch = curl_init();
        curl_setopt ($ch, CURLOPT_URL, $url);
        curl_setopt ($ch, CURLOPT_POST, 1);
        curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata);
        curl_setopt ($ch, CURLOPT_HEADER, false );
        curl_setopt ($ch, CURLOPT_HTTPHEADER,$http_header);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER,false); //处理http证书问题
        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);

        $result = curl_exec($ch);
        if (false === $result) {
            $result =  curl_errno($ch);
        }
        curl_close($ch);
        return $this->json_to_array($result) ;
    }


    /**
     * 使用FSOCKOPEN方式发送post请求(json)
     * @param  $url     [请求地址]
     * @param  $data    [array格式数据]
     * @return $请求返回结果(array)
     */
    public function postJsonDataFsockopen($url, $data){
        $this->checkSumBuilder();       //发送请求前需先生成checkSum

        $postdata = json_encode($data);

        // building POST-request:
        $URL_Info=parse_url($url);
        if(!isset($URL_Info["port"])){
            $URL_Info["port"]=80;
        }
        $request = '';
        $request.="POST ".$URL_Info["path"]." HTTP/1.1\r\n";
        $request.="Host:".$URL_Info["host"]."\r\n";
        $request.="Content-type: application/json;charset=utf-8\r\n";
        $request.="Content-length: ".strlen($postdata)."\r\n";
        $request.="Connection: close\r\n";
        $request.="AppKey: ".$this->AppKey."\r\n";
        $request.="Nonce: ".$this->Nonce."\r\n";
        $request.="CurTime: ".$this->CurTime."\r\n";
        $request.="CheckSum: ".$this->CheckSum."\r\n";
        $request.="\r\n";
        $request.=$postdata."\r\n";

        print_r($request);
        $fp = fsockopen($URL_Info["host"],$URL_Info["port"]);
        fputs($fp, $request);
        $result = '';
        while(!feof($fp)) {
            $result .= fgets($fp, 128);
        }
        fclose($fp);

        $str_s = strpos($result,'{');
        $str_e = strrpos($result,'}');
        $str = substr($result, $str_s,$str_e-$str_s+1);
        return $this->json_to_array($str);
    }


    /**
     * 创建云信ID
     * 1.第三方帐号导入到云信平台;
     * 2.注意accid,name长度以及考虑管理秘钥token
     * @param  $accid     [云信ID,最大长度32字节,必须保证一个APP内唯一(只允许字母、数字、半角下划线_、@、半角点以及半角-组成,不区分大小写,会统一小写处理)]
     * @param  $name      [云信ID昵称,最大长度64字节,用来PUSH推送时显示的昵称]
     * @param  $props     [json属性,第三方可选填,最大长度1024字节]
     * @param  $icon      [云信ID头像URL,第三方可选填,最大长度1024]
     * @param  $token     [云信ID可以指定登录token值,最大长度128字节,并更新,如果未指定,会自动生成token,并在创建成功后返回]
     * @return $result    [返回array数组对象]
     */
    public function userRegistrId($accid,$name='',$props='{}',$icon='',$token=''){
        $url = 'https://api.netease.im/nimserver/user/create.action';
        $data= array(
            'accid' => $accid,
            'name'  => $name,
            'props' => $props,
            'icon'  => $icon,
            'token' => $token
        );
        if($this->RequestType=='curl'){
            $result = $this->postDataCurl($url,$data);
        }else{
            $result = $this->postDataFsockopen($url,$data);
        }
        return $result;
    }


    /**
     * 获取用户名片
     * @param $accid
     * @return array
     */
    public function getUserInfo($accid){
        $url = 'https://api.netease.im/nimserver/user/getUinfos.action';
        $data = array(
            'accids' => json_encode($accid)
        );
        if($this->RequestType=='curl'){
            $result = $this->postDataCurl($url,$data);
        }else{
            $result = $this->postDataFsockopen($url,$data);
        }
        return $result;
    }

    /**
     * 更新用户名片
     * @param $accid
     * @return array
     */
    public function updateMyInfo($accid,$name='',$icon='',$sign='',$email='',$birth='',$mobile='',$gender=0){
        $url = 'https://api.netease.im/nimserver/user/updateUinfo.action';
        $data = array(
            'accid'=>$accid,
            'name'=>$name,
            'icon'=>$icon,
            'sign'=>$sign,
            'email'=>$email,
            'birth'=>$birth,
            'mobile'=>$mobile,
            'gender'=>$gender
        );

        if($this->RequestType=='curl'){
            $result = $this->postDataCurl($url,$data);
        }else{
            $result = $this->postDataFsockopen($url,$data);
        }
        return $result;
    }

}

需要其他操作,可以继续写在后面

code状态表:

 '操作成功',
    '201' => '客户端版本不对,需升级sdk',
    '301' => '被封禁',
    '302' => '用户名或密码错误',
    '315' => 'IP限制',
    '403' => '非法操作或没有权限',
    '404' => '对象不存在',
    '405' => '参数长度过长',
    '406' => '对象只读',
    '408' => '客户端请求超时',
    '413' => '验证失败(短信服务)',
    '414' => '参数错误',
    '415' => '客户端网络问题',
    '416' => '频率控制',
    '417' => '重复操作',
    '418' => '通道不可用(短信服务)',
    '419' => '数量超过上限',
    '422' => '账号被禁用',
    '431' => 'HTTP重复请求',
    '500' => '服务器内部错误',
    '503' => '服务器繁忙',
    '508' => '消息撤回时间超限',
    '509' => '无效协议',
    '514' => '服务不可用',
    '998' => '解包错误',
    '999' => '打包错误',
    /*群相关错误码*/
    '801' => '群人数达到上限',
    '802' => '没有权限',
    '803' => '群不存在',
    '804' => '用户不在群',
    '805' => '群类型不匹配',
    '806' => '创建群数量达到限制',
    '807' => '群成员状态错误',
    '808' => '申请成功',
    '809' => '已经在群内',
    '810' => '邀请成功',
    /*音视频、白板通话相关错误码*/
    '9102' => '通道失效',
    '9103' => '已经在他端对这个呼叫响应过了',
    '11001' => '通话不可达,对方离线状态',
    /*聊天室相关错误代码*/
    '13001' => 'IM主连接状态异常',
    '13002' => '聊天室状态异常',
    '13003' => '账号在黑名单中,不允许进入聊天室',
    '13004' => '在禁言列表中,不允许发言',
    '13005' => '用户的聊天室昵称、头像或成员扩展字段被反垃圾',
    /*特定业务相关错误码*/
    '10431' => '输入email不是邮箱',
    '10432' => '输入mobile不是手机号码',
    '10433' => '注册输入的两次密码不相同',
    '10434' => '企业不存在',
    '10435' => '登陆密码或帐号不对',
    '10436' => 'app不存在',
    '10437' => 'email已注册',
    '10438' => '手机号已注册',
    '10441' => 'app名字已经存在'
];

只需要用ajax提交数据到控制器:

$.post(
                        "地址",
                        $("form").serialize(),
                        function(res){
                            if(res.code == 2){
                                layer.msg(res.msg,{time:9000},function(){
                                    return top.location = "{:url('index/index')}";
                                });

                            }else{
                                return layer.msg(res.msg);
                            }
                        }, 'json');

控制器方法(记得在顶部引入,构造函数中实例化等操作):

//**************统一成云信参数
                $accid = $data['account'];
                $name = $data['username'];
                $sign = $data['sign'];
                $email = $data['email'];
                $birth = $data['birth'];
                $icon = $data['icon'];                
                $mobile = $data['mobile'];                
                $gender = $data['gender'];
                $res = $this->yxsdk->updateMyInfo($accid,$name,$icon,$sign,$email,$birth,$mobile,$gender);
                // code = 200 修改成功
                if($res['code'] != 200){
                    echo json_encode(array('code'=>0,'msg'=>'云信服务器个人名片修改失败!'));
                }

最后的效果图

网易云信IMweb版集成实现(PHP直接上码)_第4张图片

自己马克一下...

你可能感兴趣的:(网易云信IM)