Common.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. <?php
  2. namespace app\controller\api;
  3. use app\service\ConfServiceFacade;
  4. use laytp\library\Random;
  5. use laytp\library\UploadDomain;
  6. use plugin\ali_oss\service\Oss;
  7. use plugin\qiniu_kodo\service\Kodo;
  8. use laytp\library\Tree;
  9. use laytp\controller\Api;
  10. use plugin\ali_sms\service\AliSmsServiceFacade;
  11. use app\service\api\MiniappServiceFacade;
  12. use think\facade\Env;
  13. use think\facade\Filesystem;
  14. /**
  15. * 公用接口
  16. * @ApiWeigh (100)
  17. */
  18. class Common extends Api
  19. {
  20. public $noNeedLogin = ['template','upload','sendMobileCode','checkMobileCode','qrcodePath'];
  21. public $noNeedCheckSign = [];
  22. public function template()
  23. {
  24. global $_GPC;
  25. $template = [];
  26. $where = ['status'=>1,'uniacid'=>$_GPC['uniacid']];
  27. $order = ['sort' => 'DESC','id'=>'DESC'];
  28. $template['banner'] = \app\model\Banner::where($where)->order($order)->with(['img_file'])->select();
  29. $template['hot'] = \app\model\Hot::orderRaw("rand() , id desc")->where($where)->limit(3)->select();
  30. $template['mode'] = \app\model\Mode::where($where)->order($order)->with('img_file')->select();
  31. // $sourceData =\app\model\Template::where($where)->order($order);
  32. // $menuTreeObj = Tree::instance();
  33. // $menuTreeObj->init($sourceData->select()->toArray());
  34. // $data = $menuTreeObj->getRootTrees();
  35. // $template['template_tree'] = $data;
  36. $template['template'] = \app\model\Template::order($order)->where([['uniacid','=',$_GPC['uniacid']],['status','=',1],['pid','<>',0]])->order($order)->limit(4)->select();
  37. return $this->success('数据获取成功', $template);
  38. }
  39. /*@formatter:off*/
  40. /**
  41. * @ApiTitle (文件上传)
  42. * @ApiSummary (文件上传,兼容阿里云OSS、七牛云KODO和本地上传,自行在接口中传递参数选择上传方式,阿里云OSS和七牛云KODO需要后端安装相应插件)
  43. * @ApiMethod (POST)
  44. * @ApiRoute (/api.common/upload)
  45. * @ApiHeaders (name="token", type="string", required="true", description="用户登录后得到的Token")
  46. * @ApiParams (name="file", type="file", required="true", description="文件")
  47. * @ApiParams (name="upload_type", type="string", required="false", description="上传方式,允许为空,local=本地上传,ali-oss=阿里云OSS上传,qiniu-kodo=七牛云KODO上传,默认为local", sample="avatar")
  48. * @ApiParams (name="upload_dir", type="string", required="false", description="上传目录,允许为空", sample="avatar")
  49. * @ApiReturnParams (name="code", type="integer", description="错误码.0=没有错误,表示操作成功;1=常规错误码,客户端仅需提示msg;其他错误码与具体业务相关,其他错误码举例:10401。前端需要跳转至登录界面。")
  50. * @ApiReturnParams (name="msg", type="string", description="返回描述")
  51. * @ApiReturnParams (name="time", type="integer", description="请求时间,Unix时间戳,单位秒")
  52. * @ApiReturnParams (name="data", type="null", description="null")
  53. * @ApiReturn
  54. ({
  55. 'code':0,
  56. 'msg':'上传成功',
  57. 'time':'15632654875',
  58. 'data':null
  59. })
  60. */
  61. /*@formatter:on*/
  62. public function upload()
  63. {
  64. global $_GPC;
  65. try {
  66. $uploadType = $this->request->param('upload_type', 'local');
  67. if (!in_array($uploadType, ['local', 'ali-oss', 'qiniu-kodo'])) {
  68. return $this->error($uploadType . '上传方式未定义');
  69. }
  70. $file = $this->request->file('file'); // 获取上传的文件
  71. if (!$file) {
  72. return $this->error('上传失败,请选择需要上传的文件');
  73. }
  74. $fileExt = strtolower($file->getOriginalExtension());
  75. $uploadDomain = new UploadDomain();
  76. if (!$uploadDomain->check($file->getOriginalName(), $file->getSize(), $fileExt,true)) {
  77. return $this->error($uploadDomain->getError());
  78. }
  79. $saveName = date("Ymd") . "/" . md5(uniqid(mt_rand())) . ".{$fileExt}";
  80. /**
  81. * 不能以斜杆开头
  82. * - 因为OSS存储时,不允许以/开头
  83. */
  84. $uploadDir = $this->request->param('dir');
  85. $object = $uploadDir ? $uploadDir . '/' . $saveName : $saveName;//设置了上传目录的上传文件名
  86. $filePath = $object; //保存到lt_files中的path
  87. //如果上传的是图片,验证图片的宽和高
  88. $accept = $this->request->param('accept');
  89. if ($accept == "image") {
  90. $width = $this->request->param('width');
  91. $height = $this->request->param('height');
  92. if ($width || $height) {
  93. $imageInfo = getimagesize($file->getFileInfo());
  94. if (($width && $imageInfo[0] > $width) || ($height && $imageInfo[1] > $height)) {
  95. return $this->error('上传失败,图片尺寸要求宽:' . $width . 'px,高:' . $height . 'px,实际上传文件[ ' . $file->getOriginalName() . ' ]的尺寸为宽' . $imageInfo[0] . 'px,高:' . $imageInfo[1] . 'px');
  96. }
  97. }
  98. }
  99. $inputValue = "";
  100. //上传至七牛云
  101. if ($uploadType == 'qiniu-kodo') {
  102. if(ConfServiceFacade::get('plugin.qiniu_kodo.switch') != 1){
  103. return $this->error('未开启七牛云KODO存储,请到七牛云KODO配置中开启');
  104. }
  105. $kodoConf = [
  106. 'accessKey' => ConfServiceFacade::get('plugin.qiniu_kodo.accessKeyID'),
  107. 'secretKey' => ConfServiceFacade::get('plugin.qiniu_kodo.secretKey'),
  108. 'bucket' => ConfServiceFacade::get('plugin.qiniu_kodo.bucket'),
  109. 'domain' => ConfServiceFacade::get('plugin.qiniu_kodo.domain'),
  110. ];
  111. $kodo = Kodo::instance();
  112. $kodoRes = $kodo->upload($file->getPathname(), $object, $kodoConf);
  113. if ($kodoRes) {
  114. $inputValue = $kodoRes;
  115. } else {
  116. return $this->error($kodo->getError());
  117. }
  118. }
  119. //上传至阿里云
  120. if ($uploadType == 'ali-oss') {
  121. if(ConfServiceFacade::get('plugin.ali_oss.switch') != 1){
  122. return $this->error('未开启阿里云OSS存储,请到阿里云OSS配置中开启');
  123. }
  124. $ossConf = [
  125. 'accessKeyID' => ConfServiceFacade::get('plugin.ali_oss.accessKeyID'),
  126. 'accessKeySecret' => ConfServiceFacade::get('plugin.ali_oss.accessKeySecret'),
  127. 'bucket' => ConfServiceFacade::get('plugin.ali_oss.bucket'),
  128. 'endpoint' => ConfServiceFacade::get('plugin.ali_oss.endpoint'),
  129. 'domain' => ConfServiceFacade::get('plugin.ali_oss.domain'),
  130. ];
  131. $oss = Oss::instance();
  132. $ossUploadRes = $oss->upload($file->getPathname(), $object, $ossConf);
  133. if ($ossUploadRes) {
  134. $inputValue = $ossUploadRes;
  135. } else {
  136. return $this->error($oss->getError());
  137. }
  138. }
  139. //本地上传
  140. if ($uploadType == 'local') {
  141. $uploadDir = ltrim('/', $uploadDir);
  142. $saveName = Filesystem::putFileAs('/' . $uploadDir, $file, '/' . $object);
  143. $filePath = $saveName;
  144. $staticDomain = Env::get('domain.static');
  145. if ($staticDomain) {
  146. $inputValue = $staticDomain . '/storage/' . $saveName;
  147. } else {
  148. $inputValue = request()->domain() . STATIC_PATH . '/storage/' . $saveName;
  149. }
  150. }
  151. //将inputValue存入lt_files表中
  152. $filesModel = new \app\model\Files();
  153. $fileId = $filesModel->insertGetId([
  154. 'category_id' => (int)$this->request->param('file_category_id', 0),
  155. 'name' => $file->getOriginalName(),
  156. 'file_type' => $this->request->param('accept'),
  157. 'path' => $filePath,
  158. 'upload_type' => $uploadType,
  159. 'size' => $file->getSize(),
  160. 'ext' => $file->getExtension(),
  161. 'create_admin_user_id' => 0,
  162. 'update_admin_user_id' => 0,
  163. 'create_time' => date('Y-m-d H:i:s'),
  164. 'update_time' => date('Y-m-d H:i:s'),
  165. 'uniacid' =>$_GPC['uniacid']
  166. ]);
  167. return $this->success('上传成功', [
  168. 'id' => $fileId,
  169. 'path' => $inputValue,
  170. 'name' => $file->getOriginalName(),
  171. ]);
  172. } catch (\Exception $e) {
  173. return $this->exceptionError($e);
  174. }
  175. }
  176. /*@formatter:off*/
  177. /**
  178. * @ApiTitle (发送手机验证码)
  179. * @ApiSummary (发送手机验证码)
  180. * @ApiMethod (POST)
  181. * @ApiRoute (/api.common/sendMobileCode)
  182. * @ApiHeaders (name="token", type="string", required="true", description="用户登录后得到的Token")
  183. * @ApiParams (name="mobile", type="string", required="true", description="手机号码")
  184. * @ApiParams (name="event", type="string", required="true", sample="reg_login",description="事件名称,reg_login=使用手机号+验证码的方式进行注册或登录")
  185. * @ApiReturnParams (name="code", type="integer", required="true", sample="0")
  186. * @ApiReturnParams (name="msg", type="string", required="true", sample="返回成功")
  187. * @ApiReturnParams (name="time", type="integer", description="请求时间,Unix时间戳,单位秒")
  188. * @ApiReturnParams (name="data", type="null", description="只会返回null")
  189. * @ApiReturn
  190. ({
  191. "code": 1,
  192. "msg": "发送失败,触发分钟级流控Permits:1",
  193. "time": 1584667483,
  194. "data": null
  195. })
  196. */
  197. /*@formatter:on*/
  198. public function sendMobileCode(){
  199. // $aliSmsStatus = ConfServiceFacade::groupGet('ali_sms.conf');
  200. // if(!$aliSmsStatus){
  201. // return $this->error('请先到插件市场安装阿里云手机短信插件,并进行相关配置');
  202. // }
  203. $post['mobile'] = $this->request->post('mobile');
  204. $post['event'] = $this->request->post('event');
  205. $validate = new \plugin\ali_sms\validate\Send();
  206. if(!$validate->check($post)) return $this->error('发送失败,'.$validate->getError());
  207. if(AliSmsServiceFacade::send($post['mobile'],$post['event'],['code'=>Random::numeric()])){
  208. return $this->success('发送成功');
  209. }else{
  210. return $this->error('发送失败,'.AliSmsServiceFacade::getError());
  211. }
  212. }
  213. public function checkMobileCode(){
  214. $posts['mobile'] = $this->request->post('mobile');
  215. $posts['event'] = $this->request->post('event');
  216. $posts['code'] = $this->request->post('code');
  217. $check = AliSmsServiceFacade::checkCode($posts['mobile'],$posts['event'],$posts['code']);
  218. if($check){
  219. return $this->success('验证成功');
  220. }else{
  221. return $this->error('验证失败,'.AliSmsServiceFacade::getError());
  222. }
  223. }
  224. public function qrcodePath()
  225. {
  226. global $_GPC;
  227. $platform = $this->request->header('platform');
  228. // print_r($platform);
  229. $spm = $this->request->param('spm',0);
  230. if($platform == 'wxOfficialAccount' || $platform == 'H5'){
  231. $link = request()->domain().SURL . 'h5/?uniacid=' . $_GPC['uniacid'] .'&spm='.$spm;
  232. }elseif($platform == 'wxMiniProgram'){
  233. $conf = ConfServiceFacade::groupGet('system.miniapp', true);
  234. if(!$conf['appid'] || !$conf['appsecret']){
  235. return $this->error('操作失败');
  236. }
  237. $app = MiniappServiceFacade::option();
  238. $response = $app->app_code->getUnlimit('?uniacid='.$_GPC['uniacid'].'&spm='.$spm, [
  239. 'page' =>'pages/index/index',
  240. 'width' => 600
  241. ]);
  242. if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
  243. $time = time();
  244. $filename = $response->saveAs(IA_ROOT_WK.'/public/static/storage/qrcode/', $time.'appcode.png');
  245. }
  246. $link = request()->domain() . STATIC_PATH . '/storage/qrcode/' . $time.'appcode.png';
  247. }
  248. return $this->success('获取成功',$link);
  249. }
  250. }