【PHP】接入環信建立羣組和IM用戶

 

序言

在環信的文檔中介紹,能夠看到是沒有PHP的sdk的,那麼就須要我們本身簡單的封裝一下。我這裏使用的是TP5php

環信素材準備

(1)註冊完以後會建立一個IM應用ajax

 

 

(2)建立成功會有這下圖這樣的一個展現json

 

(3)點擊一下會有詳細信息數組

使用箭頭標註的就是我們須要的信息,記錄下來緩存

 

項目搭建

(1)目錄結構app

 

(2)建立配置文件system.phpcomposer

 

(3)第三方庫準備,安裝guzzle庫函數

把guzzlehttp/guzzle:6.0放到composer.json中測試

 

而後執行composer updatethis

 

這樣vendor就有了

 

base文件代碼編寫

(1)建立base文件

a、這裏是Base文件的引入的外部文件和聲明的變量

cache是用來緩存token的

config是用來獲取配置文件的信息的

其餘的都是第三方庫須要引入的文件

 

b、這裏是一個構造函數跟一個獲取基礎請求url的方法

這裏就不作介紹了

 

c、這裏是獲取token的一個request的方法

第59行就是使用了guzzle的client類庫,這裏是進行請求獲取token的

 

 d、這裏是從服務端獲取token

在94行就是使用了上邊的request的請求方法來發起請求

 

e、這裏是項目中使用token的處理

token是有有效期的,因此咱們不可能用一次token就從服務端獲取一下,因此就有了getToken這個方法來使用緩存的判斷來實現token在有效期限以內從緩存讀取數據

 

f、這個方法是用來調用環信的接口封裝的請求

能夠發現這個方法跟上邊的那個request的方法很類似,由於獲取token時是不須要給header中加入token的這個參數的,可是在調用接口就須要加入這個header,因此也就這一點區別

 

 

Error文件代碼

這個文件主要就是作一個簡單的異常處理

 

user文件代碼

這個文件就是咱們調用base文件的方法來實現功能需求的文件了

a、下來咱們建立一個用戶

用戶名爲user789   暱稱爲 你好我是咔咔

 

測試成功,那麼其餘的接口也是同樣,只須要把參數寫對就能夠了

 

 

源碼

base.php

<?php

namespace app\huanxin\controller;

use think\Cache;
use think\config;
use think\Controller;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

class Base extends Controller
{
    protected $orgname;
    protected $appname;
    protected $client_ID;
    protected $client_Secret;
    protected $request_url;


    /**
     * author:咔咔
     *
     * Base constructor.
     */
    public function __construct()
    {
        parent::__construct();
        $this->orgname       = config::get('system.orgname');
        $this->appname       = config::get('system.appname');
        $this->client_ID     = config::get('system.client_ID');
        $this->client_Secret = config::get('system.client_Secret');
        $this->request_url   = 'https://a1.easemob.com/';
    }

    /**
     * author:咔咔
     *
     * 基礎請求地址
     * @return string
     */
    public function baseUrl()
    {
        return $this->request_url . $this->orgname . '/' . $this->appname . '/';
    }

    /**
     * author:咔咔
     *
     * 獲取token請求
     * @param $method   請求方式
     * @param array $params  請求參數
     * @param $options
     * @return array|mixed
     * @throws Error
     */
    public function request($method, $url, $params = [], $options = [])
    {
        $config = ['base_uri' => $this->baseUrl()];
        $client = new Client($config);
        $header = [
            'Content-Type' => 'application/json',
            'Accept'       => 'application/json',
        ];
        $data = ['connect_timeout' => 30, 'headers' => $header];
        if ($method == 'GET') {
            $data['query'] = $params;
        } else {
            $data['json'] = $params;
        }
        $options && $data = array_merge($data, $options);
        $body = [];
        try {
            $res = $client->request($method, $url, $data);
            $body = \GuzzleHttp\json_decode($res->getBody()->getContents(), 1);
        } catch (RequestException $e) {
            throw new Error($e->getMessage(), -1);
        }
        return $body;
    }

    /**
     * author:咔咔
     *
     * 從服務端獲取token
     * @throws Error
     */
    public function getTokenFromServer()
    {
        $data   = [
            'grant_type'    => 'client_credentials',
            'client_id'     => $this->client_ID ,
            'client_secret' => $this->client_Secret
        ];
        $result = $this->request('POST', 'token', $data);
        return $result;
    }

    /**
     * author:咔咔
     *
     * 獲取token並存入緩存
     */
    public function getToken ()
    {
        $token = Cache::get('token');
        if(empty($token)){
            $result = $this->getTokenFromServer();
            # 減去1500秒防止偏差
            Cache::set('token',$result['access_token'],$result['expires_in']-1500);
            return $result['access_token'];
        }
        return $token;
    }

    /**
     * author:咔咔
     *
     * 功能請求
     * @param $method
     * @param array $params
     * @param $options
     * @return array|mixed
     * @throws Error
     */
    protected function _request($method, $url, $params = [], $options = [])
    {
        $client = new Client();
        $header = [
            'Content-Type' => 'application/json',
            'Accept'       => 'application/json',
        ];
        $token                   = $this->getToken();
        $header['Authorization'] = "Bearer ${token}";
        $data = ['connect_timeout' => 30, 'headers' => $header];
        if ($method == 'GET') {
            $data['query'] = $params;
        } else {
            $data['json'] = $params;
        }
        $options && $data = array_merge($data, $options);
        $body = [];
        try {
            $res = $client->request($method, $url, $data);
            $body = \GuzzleHttp\json_decode($res->getBody()->getContents(), true);
        } catch (RequestException $e) {
            $info = \GuzzleHttp\json_decode($e->getResponse()->getBody()->getContents(), 1);
            throw new Error($info['error'], -1);
        }
        return $body;
    }

}

error.php

<?php

namespace app\huanxin\controller;

use Exception;

class Error extends \Exception
{
    public function __construct($message = "", $code = 0, Exception $previous = null)
    {
        parent::__construct($this->_getMessage($message), $code, $previous);
    }

    // TODO 異常信息過濾
    private function _getMessage($msg)
    {
        $message = $msg;

        return $message;
    }
}

user.php

<?php

namespace app\huanxin\controller;

class User extends Base
{
    /**
     * author:咔咔
     *
     * 測試
     */
    public function index ()
    {
        $groupname = '我是咔咔';
        $desc = '王者榮耀羣';
        $public = true;
        $maxusers = 200;
        $members_only = false;
        $allowinvites = true;
        $owner = 'user1';
        $members = [];
        $data = $this->setGroup($groupname,$desc,$public,$maxusers,$members_only,$allowinvites,$owner,$members);
        dump($data);die;
    }
    /**
     * author:咔咔
     *
     * 獲取token
     */
    public function token()
    {
        $data = $this->getToken();
        if(!$data){
            return show(400,'獲取失敗');
        }
        return show(200,'獲取成功',$data);
    }
    /**
     * author:咔咔
     *
     * 註冊Im用戶
     */
    public function setUser ()
    {
        $params = [
            'username' => 'user789',
            'password' => '123456',
            'nickname' => '你好我是咔咔'
        ];

        # 生成IM用戶
        $result = $this->_request('POST', $this->baseUrl().'users', $params, $options = null);
        # 成功參數裏邊會有username做爲標識
        $name = $result['entities'][0]['username'];
        if(!$name){
            return ajaxReturn(ERROR);
        }
        return ajaxReturn(SUCCESS,$result);
    }

    /**
     * author:咔咔
     * @param $groupname   	羣組名稱,此屬性爲必須的
     * @param $desc         羣組描述,此屬性爲必須的
     * @param $public       是不是公開羣,此屬性爲必須的
     * @param $maxusers     羣組成員最大數(包括羣主),值爲數值類型,默認值200,最大值2000,此屬性爲可選的
     * @param $members_only 加入羣是否須要羣主或者羣管理員審批,默認是false
     * @param $allowinvites 是否容許羣成員邀請別人加入此羣。 true:容許羣成員邀請人加入此羣,false:只有羣主或者管理員才能夠往羣里加人
     * @param $owner        羣組的管理員,此屬性爲必須的
     * @param $members   	羣組成員,此屬性爲可選的,可是若是加了此項,數組元素至少一個(注:羣主user1不須要寫入到members裏面)
     */

    /**
        參數案例
        $groupname = '我是咔咔';
        $desc = '王者榮耀羣';
        $public = true;
        $maxusers = 200;
        $members_only = false;
        $allowinvites = true;
        $owner = 'user1';
        $members = ["7899","user789"];
     */

    public function setGroup ($groupname,$desc,$public,$maxusers,$members_only,$allowinvites,$owner,$members)
    {
        $params = [
            'groupname'        => $groupname,
            'desc'             => $desc,
            'public'           => $public,
            'maxusers'         => $maxusers,
            'members_only'     => $members_only,
            'allowinvites'     => $allowinvites,
            'owner'            => $owner,
            'members'          => $members
        ];
        $result = $this->_request('POST', $this->baseUrl().'chatgroups', $params, $options = null);
        $name = $result['data']['groupid'];
        if(!$name){
            return ajaxReturn(ERROR);
        }
        return ajaxReturn(SUCCESS,$result);
    }
}
相關文章
相關標籤/搜索