1. 程式人生 > >網易雲信IMweb版整合實現(PHP直接上碼)

網易雲信IMweb版整合實現(PHP直接上碼)

首先去網易雲信官網下載web版的demo,

下面連結地址: https://github.com/netease-im/NIM_Web_Demo

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

<?php
namespace app\web\controller;
use think\Controller;
use app\common\yxsdk\yunxinServerApi;  //這裡是api  需求要對雲信上的資料進行修改
use think\Config;
use think\Cookie;
use think\Db;
use think\Session;
use think\Cache;
use think\Request;

class Index extends Controller
{
    private $yxsdk;
    private $AppKey;
    private $AppSecret;

    public function _initialize(){
        // 例項雲信的庫  去官網註冊會生成key和secret
        $this->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中包含很多圖片地址需要自己去修改,才不會顯示不正常

如果需要對雲信上面的資料進行本地操作,就需要用到各種雲信提供的對應的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

以修改使用者名稱片為例:

api:

<?php
namespace app\common\yxsdk;
use think\Controller;

/**
 * 網易雲 SDK
 * Class yunxinServerApi
 * @package app\common\yxsdk
 */
Class yunxinServerApi extends Controller
{

    private $AppKey;                //開發者平臺分配的AppKey
    private $AppSecret;             //開發者平臺分配的AppSecret,可重新整理
    private $Nonce;					//隨機數(最大長度128個字元)
    private $CurTime;             	//當前UTC時間戳,從1970年1月1日0點0 分0 秒開始到現在的秒數(String)
    private $CheckSum;				//SHA1(AppSecret + Nonce + CurTime),三個引數拼接的字串,進行SHA1雜湊計算,轉化成16進位制字元(String,小寫)
    const   HEX_DIGITS = "0123456789abcdef";

    /**
     * 引數初始化
     * @param $AppKey
     * @param $AppSecret
     * @param $RequestType [選擇php請求方式,fsockopen或curl,若為curl方式,請檢查php配置是否開啟]
     */
    public function __construct($AppKey, $AppSecret, $RequestType='curl'){
        $this->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狀態表:

<?php

return [
    '200' => '操作成功',
    '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'=>'雲信伺服器個人名片修改失敗!'));
                }

最後的效果圖

自己馬克一下...