Common.php 12 KB

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