ServerAPI.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. <?php
  2. /**
  3. * 网易云信server API 简单实例
  4. * Class ServerAPI
  5. * @author liuxuanlin
  6. * @created date 2020-09-21
  7. *
  8. *
  9. ***/
  10. class ServerAPI
  11. {
  12. public $AppKey; //开发者平台分配的AppKey
  13. public $AppSecret; //开发者平台分配的AppSecret,可刷新
  14. public $Nonce; //随机数(最大长度128个字符)
  15. public $CurTime; //当前UTC时间戳,从1970年1月1日0点0 分0 秒开始到现在的秒数(String)
  16. public $CheckSum; //SHA1(AppSecret + Nonce + CurTime),三个参数拼接的字符串,进行SHA1哈希计算,转化成16进制字符(String,小写)
  17. const HEX_DIGITS = "0123456789abcdef";
  18. /**
  19. * 参数初始化
  20. * @param $AppKey
  21. * @param $AppSecret
  22. * @param $RequestType [选择php请求方式,fsockopen或curl,若为curl方式,请检查php配置是否开启]
  23. */
  24. public function __construct($AppKey, $AppSecret, $RequestType = 'curl')
  25. {
  26. $this->AppKey = $AppKey;
  27. $this->AppSecret = $AppSecret;
  28. $this->RequestType = $RequestType;
  29. }
  30. /**
  31. * API checksum校验生成
  32. * @param void
  33. * @return $CheckSum(对象私有属性)
  34. */
  35. public function checkSumBuilder()
  36. {
  37. //此部分生成随机字符串
  38. $hex_digits = self::HEX_DIGITS;
  39. $this->Nonce;
  40. for ($i = 0; $i < 128; $i++) { //随机字符串最大128个字符,也可以小于该数
  41. $this->Nonce .= $hex_digits[rand(0, 15)];
  42. }
  43. $this->CurTime = (string) (time()); //当前时间戳,以秒为单位
  44. $join_string = $this->AppSecret . $this->Nonce . $this->CurTime;
  45. $this->CheckSum = sha1($join_string);
  46. //print_r($this->CheckSum);
  47. }
  48. /**
  49. * 将json字符串转化成php数组
  50. * @param $json_str
  51. * @return $json_arr
  52. */
  53. public function json_to_array($json_str)
  54. {
  55. if (is_array($json_str) || is_object($json_str)) {
  56. $json_str = $json_str;
  57. } else if (is_null(json_decode($json_str))) {
  58. $json_str = $json_str;
  59. } else {
  60. $json_str = strval($json_str);
  61. $json_str = json_decode($json_str, true);
  62. }
  63. $json_arr = array();
  64. foreach ($json_str as $k => $w) {
  65. if (is_object($w)) {
  66. $json_arr[$k] = $this->json_to_array($w); //判断类型是不是object
  67. } else if (is_array($w)) {
  68. $json_arr[$k] = $this->json_to_array($w);
  69. } else {
  70. $json_arr[$k] = $w;
  71. }
  72. }
  73. return $json_arr;
  74. }
  75. /**
  76. * 使用CURL方式发送post请求
  77. * @param $url [请求地址]
  78. * @param $data [array格式数据]
  79. * @return $请求返回结果(array)
  80. */
  81. public function postDataCurl($url, $data)
  82. {
  83. $this->checkSumBuilder(); //发送请求前需先生成checkSum
  84. $timeout = 5000;
  85. $http_header = array(
  86. 'AppKey:' . $this->AppKey,
  87. 'Nonce:' . $this->Nonce,
  88. 'CurTime:' . $this->CurTime,
  89. 'CheckSum:' . $this->CheckSum,
  90. 'Content-Type:application/x-www-form-urlencoded;charset=utf-8',
  91. );
  92. //print_r($http_header);
  93. // $postdata = '';
  94. $postdataArray = array();
  95. foreach ($data as $key => $value) {
  96. array_push($postdataArray, $key . '=' . urlencode($value));
  97. }
  98. $postdata = join('&', $postdataArray);
  99. // var_dump($postdata);
  100. $ch = curl_init();
  101. curl_setopt($ch, CURLOPT_URL, $url);
  102. curl_setopt($ch, CURLOPT_POST, 1);
  103. curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
  104. curl_setopt($ch, CURLOPT_HEADER, false);
  105. curl_setopt($ch, CURLOPT_HTTPHEADER, $http_header);
  106. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //处理http证书问题
  107. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  108. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  109. $result = curl_exec($ch);
  110. if (false === $result) {
  111. $result = curl_errno($ch);
  112. }
  113. curl_close($ch);
  114. return $this->json_to_array($result);
  115. }
  116. /**
  117. * 使用FSOCKOPEN方式发送post请求
  118. * @param $url [请求地址]
  119. * @param $data [array格式数据]
  120. * @return $请求返回结果(array)
  121. */
  122. public function postDataFsockopen($url, $data)
  123. {
  124. $this->checkSumBuilder(); //发送请求前需先生成checkSum
  125. $postdata = '';
  126. foreach ($data as $key => $value) {
  127. $postdata .= ($key . '=' . urlencode($value) . '&');
  128. }
  129. // building POST-request:
  130. $URL_Info = parse_url($url);
  131. if (!isset($URL_Info["port"])) {
  132. $URL_Info["port"] = 80;
  133. }
  134. $request = '';
  135. $request .= "POST " . $URL_Info["path"] . " HTTP/1.1\r\n";
  136. $request .= "Host:" . $URL_Info["host"] . "\r\n";
  137. $request .= "Content-type: application/x-www-form-urlencoded;charset=utf-8\r\n";
  138. $request .= "Content-length: " . strlen($postdata) . "\r\n";
  139. $request .= "Connection: close\r\n";
  140. $request .= "AppKey: " . $this->AppKey . "\r\n";
  141. $request .= "Nonce: " . $this->Nonce . "\r\n";
  142. $request .= "CurTime: " . $this->CurTime . "\r\n";
  143. $request .= "CheckSum: " . $this->CheckSum . "\r\n";
  144. $request .= "\r\n";
  145. $request .= $postdata . "\r\n";
  146. //print_r($request);
  147. $fp = fsockopen($URL_Info["host"], $URL_Info["port"]);
  148. fputs($fp, $request);
  149. $result = '';
  150. while (!feof($fp)) {
  151. $result .= fgets($fp, 128);
  152. }
  153. fclose($fp);
  154. $str_s = strpos($result, '{');
  155. $str_e = strrpos($result, '}');
  156. $str = substr($result, $str_s, $str_e - $str_s + 1);
  157. //print_r($result);
  158. return $this->json_to_array($str);
  159. }
  160. /**
  161. * 创建云信id
  162. * @param $accid 网易云通信ID
  163. * @param $name 云通信ID昵称
  164. */
  165. public function createAccid($accid, $name)
  166. {
  167. $url = 'https://api.netease.im/nimserver/user/create.action';
  168. $data = array(
  169. 'accid' => $accid,
  170. 'name' => $name,
  171. );
  172. if ($this->RequestType == 'curl') {
  173. $result = $this->postDataCurl($url, $data);
  174. } else {
  175. $result = $this->postDataFsockopen($url, $data);
  176. }
  177. return $result;
  178. }
  179. /**
  180. * 发送普通消息
  181. * @param $from 发送者accid
  182. * @param $ope 0:点对点个人消息,1:群消息(高级群),其他返回414
  183. * @param $to ope==0是表示accid即用户id,ope==1表示tid即群id
  184. * @return $type 消息类型
  185. * @return $body 最大长度5000字符,JSON格式
  186. * @return $option 发消息时特殊指定的行为选项,JSON格式
  187. * @return $pushcontent 推送文案,最长500个字符
  188. * @return $payload 必须是JSON,不能超过2k字符
  189. * @return $ext 开发者扩展字段,长度限制1024字符
  190. */
  191. public function sendMessage($from, $ope, $to, $type, $body, $option, $pushcontent, $payload, $ext)
  192. {
  193. $url = 'https://api.netease.im/nimserver/msg/sendMsg.action';
  194. $data = array(
  195. 'from' => $from,
  196. 'ope' => $ope,
  197. 'to' => $to,
  198. 'type' => $type,
  199. 'body' => json_encode($body),
  200. 'option' => json_encode($option),
  201. 'pushcontent' => $pushcontent,
  202. 'payload' => json_decode($payload),
  203. 'ext' => json_decode($ext),
  204. );
  205. if ($this->RequestType == 'curl') {
  206. $result = $this->postDataCurl($url, $data);
  207. } else {
  208. $result = $this->postDataFsockopen($url, $data);
  209. }
  210. return $result;
  211. }
  212. /**
  213. * 批量发送
  214. * @param $fromAccid 发送者accid
  215. * @param $toAccids ["aaa","bbb"](JSONArray对应的accid,如果解析出错,会报414错误),限500人
  216. * @return $type 消息类型
  217. * @return $body 最大长度5000字符,JSON格式
  218. * @return $option 发消息时特殊指定的行为选项,JSON格式
  219. * @return $pushcontent 推送文案,最长500个字符
  220. * @return $payload 必须是JSON,不能超过2k字符
  221. * @return $ext 开发者扩展字段,长度限制1024字符
  222. */
  223. public function sendBatchMessage($fromAccid, $toAccids, $type, $body, $option, $pushcontent, $payload, $ext)
  224. {
  225. $url = 'https://api.netease.im/nimserver/msg/sendBatchMsg.action';
  226. $data = array(
  227. 'fromAccid' => $fromAccid,
  228. 'toAccids' => json_encode($toAccids),
  229. 'type' => $type,
  230. 'body' => json_encode($body),
  231. 'option' => json_encode($option),
  232. 'pushcontent' => $pushcontent,
  233. 'payload' => json_decode($payload),
  234. 'ext' => json_decode($ext),
  235. );
  236. if ($this->RequestType == 'curl') {
  237. $result = $this->postDataCurl($url, $data);
  238. } else {
  239. $result = $this->postDataFsockopen($url, $data);
  240. }
  241. return $result;
  242. }
  243. /**
  244. * 发送短信验证码
  245. * @param $templateid [模板编号(由客服配置之后告知开发者)]
  246. * @param $mobile [目标手机号]
  247. * @param $deviceId [目标设备号,可选参数]
  248. * @return $codeLen [验证码长度,范围4~10,默认为4]
  249. */
  250. public function sendSmsCode($templateid, $mobile, $deviceId = '', $codeLen)
  251. {
  252. $url = 'https://api.netease.im/sms/sendcode.action';
  253. $data = array(
  254. 'templateid' => $templateid,
  255. 'mobile' => $mobile,
  256. 'deviceId' => $deviceId,
  257. 'codeLen' => $codeLen,
  258. );
  259. if ($this->RequestType == 'curl') {
  260. $result = $this->postDataCurl($url, $data);
  261. } else {
  262. $result = $this->postDataFsockopen($url, $data);
  263. }
  264. return $result;
  265. }
  266. /**
  267. * 发送模板短信
  268. * @param $templateid [模板编号(由客服配置之后告知开发者)]
  269. * @param $mobiles [验证码]
  270. * @param $params [短信参数列表,用于依次填充模板,JSONArray格式,如["xxx","yyy"];对于不包含变量的模板,不填此参数表示模板即短信全文内容]
  271. * @return $result [返回array数组对象]
  272. */
  273. public function sendSMSTemplate($templateid, $mobiles = array(), $params = '')
  274. {
  275. $url = 'https://api.netease.im/sms/sendtemplate.action';
  276. $data = array(
  277. 'templateid' => $templateid,
  278. 'mobiles' => json_encode($mobiles),
  279. 'params' => json_encode($params),
  280. );
  281. if ($this->RequestType == 'curl') {
  282. $result = $this->postDataCurl($url, $data);
  283. } else {
  284. $result = $this->postDataFsockopen($url, $data);
  285. }
  286. return $result;
  287. }
  288. /**
  289. * 刷新token
  290. */
  291. public function refreshToken($accid)
  292. {
  293. $url = 'https://api.netease.im/nimserver/user/refreshToken.action';
  294. $data = array(
  295. 'accid' => $accid,
  296. );
  297. if ($this->RequestType == 'curl') {
  298. $result = $this->postDataCurl($url, $data);
  299. } else {
  300. $result = $this->postDataFsockopen($url, $data);
  301. }
  302. return $result;
  303. }
  304. /**
  305. * 创建聊天室
  306. */
  307. public function chatroomCreate($accid, $name)
  308. {
  309. $url = 'https://api.netease.im/nimserver/chatroom/create.action';
  310. $data = array(
  311. 'creator' => $accid,
  312. 'name' => $name,
  313. );
  314. if ($this->RequestType == 'curl') {
  315. $result = $this->postDataCurl($url, $data);
  316. } else {
  317. $result = $this->postDataFsockopen($url, $data);
  318. }
  319. return $result;
  320. }
  321. //查询聊天室信息
  322. public function chatroomget($roomid)
  323. {
  324. $url = 'https://api.netease.im/nimserver/chatroom/get.action';
  325. }
  326. /**
  327. * 根据accid获取聊天室roomid
  328. */
  329. public function queryUserRoomIds($accid)
  330. {
  331. $url = 'https://api.netease.im/nimserver/chatroom/queryUserRoomIds.action';
  332. $data = array(
  333. 'creator' => $accid,
  334. );
  335. if ($this->RequestType == 'curl') {
  336. $result = $this->postDataCurl($url, $data);
  337. } else {
  338. $result = $this->postDataFsockopen($url, $data);
  339. }
  340. return $result;
  341. }
  342. /**
  343. * 获取聊天室地址
  344. */
  345. public function chatroomRequestAddr($roomid, $accid)
  346. {
  347. $url = 'https://api.netease.im/nimserver/chatroom/requestAddr.action';
  348. $data = [
  349. 'roomid' => $roomid,
  350. 'accid' => $accid,
  351. ];
  352. if ($this->RequestType == 'curl') {
  353. $result = $this->postDataCurl($url, $data);
  354. } else {
  355. $result = $this->postDataFsockopen($url, $data);
  356. }
  357. return $result;
  358. }
  359. /**
  360. * 为项目人员创建token
  361. */
  362. public function gettokenforapp($userinfo)
  363. {
  364. $id = $userinfo['id']; //accid
  365. $name = $userinfo['name'];
  366. $result = $this->createAccid($id, $name);
  367. $code = $result['code'];
  368. $token = '';
  369. switch ($code) {
  370. case '200':
  371. //新建用户成功
  372. $data = $result['info'];
  373. $token = $data['token'];
  374. break;
  375. case '414':
  376. //用户已存在 重置token
  377. $result = $this->refreshToken($id);
  378. $code = $result['code'];
  379. if (200 != $code) {
  380. //报错
  381. }
  382. $data = $result['info'];
  383. $token = $data['token'];
  384. break;
  385. default:
  386. //报错
  387. $desc = $result['desc'];
  388. exit("网络异常-" . $desc);
  389. break;
  390. }
  391. return $token;
  392. }
  393. /**
  394. * 为项目获取聊天室信息
  395. */
  396. public function getroomidforapp($userinfo)
  397. {
  398. $id = $userinfo['id']; //accid
  399. $name = $userinfo['name'];
  400. $type = $userinfo['type'];
  401. $roomid = $_SESSION['roomid'];
  402. try {
  403. if (1 == $type) {
  404. //可创建聊天室用户
  405. $result = $this->queryUserRoomIds($id);
  406. if (200 != $result['code']) {
  407. //排除无 聊天室状态
  408. $has = false;
  409. if (!$has) {
  410. //创建聊天室
  411. $result = $this->chatroomCreate($id);
  412. if (200 != $result['code']) {
  413. //聊天室创建失败
  414. throw new Exception("Error Processing Request", 1);
  415. }
  416. }
  417. throw new Exception("Error Processing Request", 1);
  418. }
  419. $rootlist = $result['desc']['roomids'];
  420. $roomid = $rootlist[0];
  421. }
  422. return false;
  423. } catch (\Exception $th) {
  424. }
  425. }
  426. }