ApiController.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. <?php
  2. /**
  3. * 对外接口
  4. * User: solu
  5. * Date: 2019/4/16
  6. * Time: 11:23 AM
  7. */
  8. class ApiController extends BaseController {
  9. /**
  10. * 创建群
  11. * @author solu
  12. * @param $args
  13. * @return array
  14. */
  15. public function actionCreateGroup($args) {
  16. $rules = [
  17. 'creator' => ['int', 'desc' => '创建者id'],
  18. 'group_title' => ['string', 'desc' => '群标题'],
  19. 'timestamp' => ['int', 'desc' => '时间戳(秒'],
  20. 'sign' => ['string', 'desc' => '签名'],
  21. ];
  22. Param::checkParam2($rules, $args);
  23. $group_id = 0;
  24. try {
  25. $args = $this->_valid($args);
  26. $sess = (new GroupInfo())->create($args);
  27. $group_id = intval($sess['session_id']);
  28. } catch (Exception $e) {
  29. Response::error($e->getCode(), $e->getMessage());
  30. }
  31. return compact('group_id');
  32. }
  33. /**
  34. * 删除群
  35. * @author solu
  36. * @param $args
  37. */
  38. public function actionDiscardGroup($args) {
  39. $rules = [
  40. 'creator' => ['int', 'desc' => '创建者id'],
  41. 'group_id' => ['int', 'desc' => '群标id'],
  42. 'timestamp' => ['int', 'desc' => '时间戳(秒'],
  43. 'sign' => ['string', 'desc' => '签名'],
  44. ];
  45. Param::checkParam2($rules, $args);
  46. try {
  47. $args = $this->_valid($args);
  48. (new GroupInfo())->discard($args['creator'], $args['group_id']);
  49. } catch (Exception $e) {
  50. Response::error($e->getCode(), $e->getMessage());
  51. }
  52. }
  53. /**
  54. * 校验参数
  55. * @author solu
  56. * @param $args
  57. * @return mixed
  58. * @throws Exception
  59. */
  60. private function _valid($args) {
  61. $creator = $args['creator'];
  62. if (!$creator) {
  63. throw new Exception("miss creator", CODE_PARAM_ERROR);
  64. }
  65. $apiToken = (new TableHelper('user_info', 'dw_chat'))->getOne(['user_id' => $creator], ['_field' => 'api_token']);
  66. if (!$apiToken) {
  67. throw new Exception('miss api token', CODE_NO_PERMITION);
  68. }
  69. $sign = arrayPop($args, 'sign');
  70. $mySign = $this->_sign($args, $apiToken);
  71. if ($sign !== $mySign) {
  72. throw new Exception('sign error', CODE_NO_PERMITION);
  73. }
  74. $timestamp = arrayPop($args, 'timestamp');
  75. if (time() - 60 > $timestamp) {
  76. throw new Exception('timeout', CODE_PARAM_ERROR);
  77. }
  78. return $args;
  79. }
  80. private function _sign($data, $token) {
  81. ksort($data);
  82. $param = http_build_query($data);
  83. $param = str_replace('%2A', '*', $param);
  84. $str = "token={$token}{$param}";
  85. return md5($str);
  86. }
  87. }