环信服务端(php)YII

来源:互联网 发布:爱新觉罗知乎 编辑:程序博客网 时间:2024/05/17 08:09
<?php/** * 环信接口 * @author baijinfeng * */class EHuan extends CApplicationComponent{      /**    * 客户端id    * @var unknown    */   public $client_id = NULL;      /**    * 客户端秘钥    * @var unknown    */   public $client_secret = NULL;      /**    * 环新注册的ORG Name    * @var unknown    */   public $org_name = NULL;      /**    * 环信注册的APP Name    * @var unknown    */   public $app_name = NULL;   /**     * 服务器地址     */   public $host = NULL;      /**    * 请求地址    * @var unknown    */   public $url = NULL;      /**    *     */   public function init()   {      $this->url = $this->host . '/' . $this->org_name . '/' . $this->app_name . '/';   }            /**    * 注册用户    * @param $string $username 用户名    * @param string  $password 密码    */   public function registerUser($username, $password)   {      $token = $this->getToken();      $header[] = "Authorization:Bearer ".$token;      $body = array('username' => $username, 'password' => $password);      $result = $this->curl($this->url.'users', 'POST', $header, $body);      return $result;   }      /**    * 批量注册用户    * @param array $data array('username'=>,    */   public function registerUsers($data)   {      $token = $this->getToken();      $header[] = "Authorization:Bearer ".$token;      $result = $this->curl($this->url.'users', 'POST', $header, $data);      return $result;   }      /**    * 创建群    * @param array $data 群的信息 name(群名称)  creater必须有    * @param array $members 群成员    * @return string 群id    */   public function createGroup($data=array(), $members=array())   {      if (!isset($data['name']) || !isset($data['creater']) || empty($members))         return false;      $body = array(         "groupname" => $data['name'],         "desc" => isset($data['desc']) ? $data['desc'] : $data['name'],         // "public" => isset($data['public']) ? $data['public'] : true,         "public" => array_key_exists("public", $data) ? $data["public"] : true,         "maxusers" => isset($data['maxusers']) ? $data['maxusers'] : 300,         "approval" => false,         "owner" => $data['creater'],         "members" => $members      );      $token = $this->getToken();      $header[] = "Authorization:Bearer ".$token;      Yii::log($this->url.'users', 'info');      Yii::log($token);      $result = $this->curl($this->url.'chatgroups', 'POST', $header, $body);      Yii::log(json_encode($result));      if (!empty($result))         return $result['data']['groupid'];      else         return 0;   }      /**    * 修改群组信息    * {    *     "groupname":"testrestgrp12", //群组名称    *  "description":"update groupinfo", //群组描述    *  "maxusers":300, //群组成员最大数(包括群主), 值为数值类型    * }    */   public function updateGroup($hx_gid, $group_info)   {      $token = $this->getToken();      $header[] = "Authorization:Bearer ".$token;      $result = $this->curl($this->url."chatgroups/".$hx_gid, 'PUT', $header, $group_info);      return $result;   }   /**    * 群组转让    */   public function changeGroupOwner($hx_gid, $new_owner)   {      $token = $this->getToken();      $header[] = "Authorization:Bearer ".$token;      $result = $this->curl($this->url."chatgroups/".$hx_gid, 'PUT', $header, array("newowner"=>$new_owner));      return $result;   }   /**    * 查询用户    */   public function getUser($hx_uid)   {      $token = $this->getToken();      $header[] = "Authorization:Bearer ".$token;      $result = $this->curl($this->url.'users/'.$hx_uid);      return $result;   }   /**    * 创建群(新版)    * @param array $data 群的信息 name(群名称)  creater必须有    * @param array $members 群成员    * @return string 群id    */   public function createGroupNew($data=array(), $members=array())   {      if (!isset($data['name']) || !isset($data['creater']) || empty($members))         return false;      $body = array(         "groupname" => $data['name'],         "desc" => isset($data['desc']) ? $data['desc'] : $data['name'],         "public" => array_key_exists("public", $data) ? $data["public"] : true,         "maxusers" => isset($data['maxusers']) ? $data['maxusers'] : 300,         "approval" => false,         "owner" => $data['creater'],         "members" => $members      );      $token = $this->getToken();      $header[] = "Authorization:Bearer ".$token;      $result = $this->curl($this->url.'chatgroups', 'POST', $header, $body);      return $result;   }   /**    * 入群(单人)    *  @param unknown $groupId 环信群id    *  @param string $memberId 用户在环信的id    */   public function groupAddUser($groupId, $member)   {      $token = $this->getToken();      $header[] = "Authorization:Bearer ".$token;      $url = $this->url . 'chatgroups/' . $groupId . '/users/' . $member;      $result = $this->curl($url, 'POST', $header);      return $result;   }      /**    * 入群(批量)    * @param unknown $groupId 换信群id    * @param unknown $membersId     */   public function groupAddUsers($groupId, $members=array())   {      $token = $this->getToken();      $header[] = "Authorization:Bearer ".$token;      $url = $this->url . 'chatgroups/' . $groupId . '/users';      $result = $this->curl($url, 'POST', $header, array('usernames' => $members));      return $result;   }      /**    * 移群(单人)    */   public function groupRemoveUser($groupId, $member)   {      $token = $this->getToken();      $header[] = "Authorization:Bearer ".$token;      $url = $this->url . 'chatgroups/' . $groupId . '/users/' . $member;      $result = $this->curl($url, 'DELETE', $header);      return $result;   }      /**    * 批量移除(环新没有提供API)    * @param unknown $groupId    * @param unknown $members    * @return boolean    */   public function groupRemoveUsers($groupId, $members=array())   {      if (empty($members))         return false;      $token = $this->getToken();      $header[] = "Authorization:Bearer ".$token;      foreach ($members as $member)      {         $url = $this->url . 'chatgroups/' . $groupId . '/users/' . $member;         $result = $this->curl($url, 'DELETE', $header);      }      return true;   }      /**    * 批量删除群成员    *     */   public function groupDeleteUsers($groupId, $members=array())   {      $token = $this->getToken();      $header[] = "Authorization:Bearer ".$token;      $members = implode(',', $members);      $url = $this->url.'chatgroups/'.$groupId.'/users/'.$members;      $result = $this->curl($url, 'DELETE', $header);      return $result;   }   /**    * 删除群    */   public function groupDelete($groupId)   {      $token = $this->getToken();      $header[] = "Authorization:Bearer ".$token;      $url = $this->url . 'chatgroups/' . $groupId;      $result = $this->curl($url, 'DELETE', $header);      return $result;   }         /**    * 发送文本消息    * @param $to 接受用户环信id    * @param $from 发送的用户环信id    * @param $content 发送内容    * @param $option array 自定义属性    */   public function sendTextMsg($to, $content, $from, $option=array())   {      $token = $this->getToken();      $header[] = "Authorization:Bearer ".$token;      $body = array(         'target_type' => 'users',         'target' => !is_array($to) ? array($to) : $to,         'msg' => array(            'type' => 'txt',            'msg' => $content         ),         'from' => $from,      );      if (!empty($option))         $body['ext'] = $option;      $url = $this->url . 'messages/';      $result = $this->curl($url, 'POST', $header, $body);      return $result;   }      /**    * 给群发消息    */   public function sendGroupMsg($to, $content, $from, $option=array())   {      $token = $this->getToken();      $header[] = "Authorization:Bearer ".$token;      $body = array(         'target_type' => 'chatgroups',         'target' => !is_array($to) ? array($to) : $to,         'msg' => array(               'type' => 'txt',               'msg' => $content         ),         'from' => $from,      );      if (!empty($option))         $body['ext'] = $option;      $url = $this->url . 'messages/';      $result = $this->curl($url, 'POST', $header, $body);      return $result;   }      /**    * 发送透传消息    * @param $to 接受信息的用户huanxin_id    * @param $action 透传消息 用来区分各操作, newfriend(新好友)    * @param $from    * @param $option 自定义的属性    */   public function sendThroughMsg($to,$action,$from,$option=array())   {      Yii::log('sendThroughMessage');      $token = $this->getToken();      $header[] = "Authorization:Bearer ".$token;      $body = array(            'target_type' => 'users',            'target' => !is_array($to) ? array($to) : $to,            'msg' => array(                  'type' => 'cmd',                  "action" => $action            ),            'from' => $from,      );      if (!empty($option))         $body['ext'] = $this->int2String($option);      $url = $this->url . 'messages/';      Yii::log(print_r($body, true));      $result = $this->curl($url, 'POST', $header, $body);      return $result;   }         /**    * 发送消息    */   private function sendMsg($targetType='users', $to)   {                     }   /**    * 获取token    * @todo cache    */   private function getToken()   {      $key = EKeys::tokenCache();      $token = Yii::app()->redis->get($key);      $token = null;      if (!empty($token)){         Yii::log("从缓存中获取环信token");         return $token;      }      else       {         Yii::log("未从缓存中获取环信token,请求环信");         $body = array(            'grant_type' => 'client_credentials',            'client_id' => $this->client_id,            'client_secret' => $this->client_secret         );         $tokenInfo = $this->curl($this->url . 'token', 'POST', array(), $body);         if (!empty($tokenInfo))         {            // 缓存            Yii::app()->redis->setex($key, $tokenInfo['expires_in']-120, $tokenInfo['access_token']);            return $tokenInfo['access_token'];         }      }   }      /**    *     * @param unknown $data    */   private function buildPost($data)   {//        foreach ($data as $key => $value)//        {//           $join[] = "$key=$value";//        }//        return join('&', $join);      return json_encode($data);   }      /**    * 发送请求    * @param unknown $url    * @param unknown $option    * @param number $header    * @param string $type    */   private function curl($url, $type='POST', $header=0, $data=NULL)   {      $curl = curl_init();      curl_setopt($curl, CURLOPT_URL, $url);      curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); // 对认证证书来源的检查      curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); // 从证书中检查SSL加密算法是否存在      curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)' ); // 模拟用户使用的浏览器            curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环      if($header)         curl_setopt($curl, CURLOPT_HTTPHEADER, $header); // 设置HTTP头      curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回      curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $type);            if (!empty($data))      {         curl_setopt($curl, CURLOPT_POST, 1);         curl_setopt($curl, CURLOPT_POSTFIELDS, $this->buildPost($data));      }      $result = curl_exec($curl);      if (!empty($result))      {         // 请求成功         return json_decode($result, true);      }      else       {         // 请求失败         $error = curl_getinfo($curl, CURLINFO_HTTP_CODE);      }   }   private function int2String($params)   {      foreach($params as &$v){         if(is_numeric($v))            $v = "{$v}";      }      return $params;   }   }

阅读全文
1 0
原创粉丝点击