123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452 |
- <?php
- /**
- * 网易云信server API 简单实例
- * Class ServerAPI
- * @author liuxuanlin
- * @created date 2020-09-21
- *
- *
- ***/
- class ServerAPI
- {
- public $AppKey; //开发者平台分配的AppKey
- public $AppSecret; //开发者平台分配的AppSecret,可刷新
- public $Nonce; //随机数(最大长度128个字符)
- public $CurTime; //当前UTC时间戳,从1970年1月1日0点0 分0 秒开始到现在的秒数(String)
- public $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',
- );
- //print_r($http_header);
- // $postdata = '';
- $postdataArray = array();
- foreach ($data as $key => $value) {
- array_push($postdataArray, $key . '=' . urlencode($value));
- }
- $postdata = join('&', $postdataArray);
- // var_dump($postdata);
- $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 = '';
- foreach ($data as $key => $value) {
- $postdata .= ($key . '=' . urlencode($value) . '&');
- }
- // 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);
- //print_r($result);
- return $this->json_to_array($str);
- }
- /**
- * 创建云信id
- * @param $accid 网易云通信ID
- * @param $name 云通信ID昵称
- */
- public function createAccid($accid, $name)
- {
- $url = 'https://api.netease.im/nimserver/user/create.action';
- $data = array(
- 'accid' => $accid,
- 'name' => $name,
- );
- if ($this->RequestType == 'curl') {
- $result = $this->postDataCurl($url, $data);
- } else {
- $result = $this->postDataFsockopen($url, $data);
- }
- return $result;
- }
- /**
- * 发送普通消息
- * @param $from 发送者accid
- * @param $ope 0:点对点个人消息,1:群消息(高级群),其他返回414
- * @param $to ope==0是表示accid即用户id,ope==1表示tid即群id
- * @return $type 消息类型
- * @return $body 最大长度5000字符,JSON格式
- * @return $option 发消息时特殊指定的行为选项,JSON格式
- * @return $pushcontent 推送文案,最长500个字符
- * @return $payload 必须是JSON,不能超过2k字符
- * @return $ext 开发者扩展字段,长度限制1024字符
- */
- public function sendMessage($from, $ope, $to, $type, $body, $option, $pushcontent, $payload, $ext)
- {
- $url = 'https://api.netease.im/nimserver/msg/sendMsg.action';
- $data = array(
- 'from' => $from,
- 'ope' => $ope,
- 'to' => $to,
- 'type' => $type,
- 'body' => json_encode($body),
- 'option' => json_encode($option),
- 'pushcontent' => $pushcontent,
- 'payload' => json_decode($payload),
- 'ext' => json_decode($ext),
- );
- if ($this->RequestType == 'curl') {
- $result = $this->postDataCurl($url, $data);
- } else {
- $result = $this->postDataFsockopen($url, $data);
- }
- return $result;
- }
- /**
- * 批量发送
- * @param $fromAccid 发送者accid
- * @param $toAccids ["aaa","bbb"](JSONArray对应的accid,如果解析出错,会报414错误),限500人
- * @return $type 消息类型
- * @return $body 最大长度5000字符,JSON格式
- * @return $option 发消息时特殊指定的行为选项,JSON格式
- * @return $pushcontent 推送文案,最长500个字符
- * @return $payload 必须是JSON,不能超过2k字符
- * @return $ext 开发者扩展字段,长度限制1024字符
- */
- public function sendBatchMessage($fromAccid, $toAccids, $type, $body, $option, $pushcontent, $payload, $ext)
- {
- $url = 'https://api.netease.im/nimserver/msg/sendBatchMsg.action';
- $data = array(
- 'fromAccid' => $fromAccid,
- 'toAccids' => json_encode($toAccids),
- 'type' => $type,
- 'body' => json_encode($body),
- 'option' => json_encode($option),
- 'pushcontent' => $pushcontent,
- 'payload' => json_decode($payload),
- 'ext' => json_decode($ext),
- );
- if ($this->RequestType == 'curl') {
- $result = $this->postDataCurl($url, $data);
- } else {
- $result = $this->postDataFsockopen($url, $data);
- }
- return $result;
- }
- /**
- * 发送短信验证码
- * @param $templateid [模板编号(由客服配置之后告知开发者)]
- * @param $mobile [目标手机号]
- * @param $deviceId [目标设备号,可选参数]
- * @return $codeLen [验证码长度,范围4~10,默认为4]
- */
- public function sendSmsCode($templateid, $mobile, $deviceId = '', $codeLen)
- {
- $url = 'https://api.netease.im/sms/sendcode.action';
- $data = array(
- 'templateid' => $templateid,
- 'mobile' => $mobile,
- 'deviceId' => $deviceId,
- 'codeLen' => $codeLen,
- );
- if ($this->RequestType == 'curl') {
- $result = $this->postDataCurl($url, $data);
- } else {
- $result = $this->postDataFsockopen($url, $data);
- }
- return $result;
- }
- /**
- * 发送模板短信
- * @param $templateid [模板编号(由客服配置之后告知开发者)]
- * @param $mobiles [验证码]
- * @param $params [短信参数列表,用于依次填充模板,JSONArray格式,如["xxx","yyy"];对于不包含变量的模板,不填此参数表示模板即短信全文内容]
- * @return $result [返回array数组对象]
- */
- public function sendSMSTemplate($templateid, $mobiles = array(), $params = '')
- {
- $url = 'https://api.netease.im/sms/sendtemplate.action';
- $data = array(
- 'templateid' => $templateid,
- 'mobiles' => json_encode($mobiles),
- 'params' => json_encode($params),
- );
- if ($this->RequestType == 'curl') {
- $result = $this->postDataCurl($url, $data);
- } else {
- $result = $this->postDataFsockopen($url, $data);
- }
- return $result;
- }
- /**
- * 刷新token
- */
- public function refreshToken($accid)
- {
- $url = 'https://api.netease.im/nimserver/user/refreshToken.action';
- $data = array(
- 'accid' => $accid,
- );
- if ($this->RequestType == 'curl') {
- $result = $this->postDataCurl($url, $data);
- } else {
- $result = $this->postDataFsockopen($url, $data);
- }
- return $result;
- }
- /**
- * 创建聊天室
- */
- public function chatroomCreate($accid, $name)
- {
- $url = 'https://api.netease.im/nimserver/chatroom/create.action';
- $data = array(
- 'creator' => $accid,
- 'name' => $name,
- );
- if ($this->RequestType == 'curl') {
- $result = $this->postDataCurl($url, $data);
- } else {
- $result = $this->postDataFsockopen($url, $data);
- }
- return $result;
- }
- //查询聊天室信息
- public function chatroomget($roomid)
- {
- $url = 'https://api.netease.im/nimserver/chatroom/get.action';
- }
- /**
- * 根据accid获取聊天室roomid
- */
- public function queryUserRoomIds($accid)
- {
- $url = 'https://api.netease.im/nimserver/chatroom/queryUserRoomIds.action';
- $data = array(
- 'creator' => $accid,
- );
- if ($this->RequestType == 'curl') {
- $result = $this->postDataCurl($url, $data);
- } else {
- $result = $this->postDataFsockopen($url, $data);
- }
- return $result;
- }
- /**
- * 获取聊天室地址
- */
- public function chatroomRequestAddr($roomid, $accid)
- {
- $url = 'https://api.netease.im/nimserver/chatroom/requestAddr.action';
- $data = [
- 'roomid' => $roomid,
- 'accid' => $accid,
- ];
- if ($this->RequestType == 'curl') {
- $result = $this->postDataCurl($url, $data);
- } else {
- $result = $this->postDataFsockopen($url, $data);
- }
- return $result;
- }
- /**
- * 为项目人员创建token
- */
- public function gettokenforapp($userinfo)
- {
- $id = $userinfo['id']; //accid
- $name = $userinfo['name'];
- $result = $this->createAccid($id, $name);
- $code = $result['code'];
- $token = '';
- switch ($code) {
- case '200':
- //新建用户成功
- $data = $result['info'];
- $token = $data['token'];
- break;
- case '414':
- //用户已存在 重置token
- $result = $this->refreshToken($id);
- $code = $result['code'];
- if (200 != $code) {
- //报错
- }
- $data = $result['info'];
- $token = $data['token'];
- break;
- default:
- //报错
- $desc = $result['desc'];
- exit("网络异常-" . $desc);
- break;
- }
- return $token;
- }
- /**
- * 为项目获取聊天室信息
- */
- public function getroomidforapp($userinfo)
- {
- $id = $userinfo['id']; //accid
- $name = $userinfo['name'];
- $type = $userinfo['type'];
- $roomid = $_SESSION['roomid'];
- try {
- if (1 == $type) {
- //可创建聊天室用户
- $result = $this->queryUserRoomIds($id);
- if (200 != $result['code']) {
- //排除无 聊天室状态
- $has = false;
- if (!$has) {
- //创建聊天室
- $result = $this->chatroomCreate($id);
- if (200 != $result['code']) {
- //聊天室创建失败
- throw new Exception("Error Processing Request", 1);
- }
- }
- throw new Exception("Error Processing Request", 1);
- }
- $rootlist = $result['desc']['roomids'];
- $roomid = $rootlist[0];
- }
- return false;
- } catch (\Exception $th) {
- }
- }
- }
|