User.php 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | [ WE CAN DO IT MORE SIMPLE ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2018-2020 rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Author: TABLE ME
  8. // +----------------------------------------------------------------------
  9. // | Date: 2020-08-25 17:23
  10. // +----------------------------------------------------------------------
  11. declare (strict_types=1);
  12. namespace app\api\controller;
  13. use app\BaseController;
  14. use app\model\api\User as UserModel;
  15. use app\model\api\UserDetail as UserDetailModel;
  16. use app\model\api\ServiceType as ServiceTypeModel;
  17. use app\model\api\InfoAudit;
  18. use app\model\api\TypeAudit;
  19. use app\model\api\UserAudit;
  20. use app\model\api\ServiceType;
  21. use app\model\api\ServiceLabel as ServiceLabelModel;
  22. use app\model\api\ServiceTimeType;
  23. use app\model\api\City as CityModel;
  24. use app\model\api\Sys as SysModel;
  25. use app\model\api\ShowTemplate;
  26. use app\model\api\ShowTemplateOrder;
  27. use app\model\api\UserShowTemplate;
  28. use app\model\api\UserWorkType;
  29. use app\model\api\PayTrade as PayTradeModel;
  30. use app\api\controller\pub;
  31. use app\Request;
  32. use library\services\UtilService;
  33. use library\utils\QRcodeComm;
  34. use library\utils\Qiniu;
  35. use library\utils\IdentityCard;
  36. use library\utils\WxpayV2 as wxpayApi;
  37. use think\db\exception\DbException;
  38. use library\lib\weixina;
  39. use think\facade\Db;
  40. use think\Image;
  41. use think\Route;
  42. use think\Collection;
  43. class User extends BaseController
  44. {
  45. /**
  46. * 获取用户详情
  47. * @param Request $request
  48. */
  49. public function userInfo(Request $request){
  50. //资料审核信息
  51. $infoAuditData = (new InfoAudit)->where("uid",$request->user["uid"])->order("id desc")->find();
  52. $userAuditData = (new UserAudit)->where("uid",$request->user["uid"])->order("id desc")->find();
  53. $typeAuditData = (new TypeAudit)->where("uid",$request->user["uid"])->order("id desc")->find();
  54. $data = [];
  55. $data['uid'] = $request->user['uid'];
  56. $data['nickname'] = $request->user['nickname'];
  57. $data['mobile'] = $request->user['mobile'];
  58. $data['avatar'] = $request->user['avatar'];
  59. $data['name'] = $request->user['name'];
  60. $data['sex'] = $request->user['sex'];
  61. $data['type'] = $request->user['type'];//用户类型
  62. $data['type_name'] = "";//用户类型名称
  63. $data['work_type_id'] = $request->user['work_type_id'];//用户职称类型
  64. $data['work_type_title'] = $request->user['work_type_title'];//用户职称类型名称
  65. $data['card_look_count'] = $request->user['card_look_count'];//用户名片浏览次数
  66. $data['info_audit_status'] = empty($infoAuditData)?-2:$infoAuditData["status"];
  67. $data['user_audit_status'] = empty($userAuditData)?-2:$userAuditData["status"];
  68. $data['type_audit_status'] = empty($typeAuditData)?-2:$typeAuditData["status"];
  69. //资料通过需要重新提交认证
  70. if(!empty($infoAuditData) && !empty($typeAuditData)){
  71. if($infoAuditData["status"]==1 && $typeAuditData["status"]==1 && $infoAuditData["admin_time"]>$typeAuditData["admin_time"]){
  72. $data['type_audit_status'] = -3;
  73. }
  74. }
  75. $data['show_template_code'] = "";
  76. $data['show_template_id'] = "";
  77. $tmpData = (new UserShowTemplate)
  78. ->field("t.id,t.code,t.title,t.is_init,b.is_default")
  79. ->alias("b")
  80. ->join("show_template t","t.id = b.show_template_id","left")
  81. ->where("b.uid",$request->user['uid'])
  82. ->order("b.is_default","desc")
  83. ->order("b.id","desc")
  84. ->find();
  85. if(!empty($tmpData)){
  86. $data['show_template_code'] = $tmpData["code"];
  87. $data['show_template_id'] = $tmpData["id"];
  88. $data['show_template_init'] = $tmpData["is_init"];
  89. $data['show_template_default'] = $tmpData["is_default"];
  90. }
  91. return app('json')->success($data);
  92. }
  93. /**
  94. * 获取用户子级列表
  95. * @param Request $request
  96. */
  97. public function getChildList(Request $request){
  98. $post = UtilService::getMore([
  99. ['page', 1],
  100. ['pageSize', 50],
  101. ], $request);
  102. $post["pageSize"] = $post["pageSize"]>50 ? 50 : (int)$post["pageSize"];
  103. $post["page"] = $post["page"]<=0 ? 1 : (int)$post["page"];
  104. $post["parent_uid"]= $request->user["uid"];
  105. $data = (new UserModel)->getDataList($post,"u.uid,u.mobile,u.nickname,u.avatar");
  106. $list = $data["list"];
  107. foreach ($list as &$item) {
  108. $userInfo = $this->getUserInfo($item["uid"]);
  109. $item["is_type_audit"] = $userInfo["is_type_audit"];
  110. $item["ancestral_place"] = $userInfo["ancestral_place"];
  111. $item["auth_info"] = $userInfo["auth_info"];
  112. $item["user_work_type_id"] = $userInfo["user_work_type_id"];
  113. }
  114. $data["list"] = $list;
  115. return app('json')->success($data);
  116. }
  117. /**
  118. * 获取用户总邀请人数排行榜
  119. * @param Request $request
  120. */
  121. public function getInviterRanking(Request $request)
  122. {
  123. $time = $request->param('time');
  124. $times = $request->param('times');
  125. $users = (new UserModel())
  126. ->where('parent_uid', '<>', 0)
  127. ->where('regtime', '>=', $time)
  128. ->where('regtime', '<=', $times)
  129. ->field('parent_uid as uid, count(*) as invite_count')
  130. ->group('parent_uid')
  131. ->order('invite_count', 'desc')
  132. ->select();
  133. $rankList = [];
  134. foreach ($users as $key => $value) {
  135. $userInfo = (new UserModel)->where('uid', $value['uid'])->find();
  136. if (!$userInfo['nickname']) {
  137. continue;
  138. }
  139. $auth = (new InfoAudit)->where('uid', $value['uid'])->find();
  140. $user_work_type_title = (new UserWorkType)->where('id', $auth['user_work_type_id'])->find();
  141. if ($auth) {
  142. $auth_info = $auth->toArray();
  143. } else {
  144. $auth_info = null;
  145. }
  146. $rankList[] = [
  147. 'rank' => $key + 1,
  148. 'uid' => $value['uid'],
  149. 'nickname' => $userInfo['nickname'],
  150. 'avatar' => $userInfo['avatar'],
  151. 'invite_count' => $value['invite_count'],
  152. 'is_type_audit' => $auth && $auth['status'] == 1 ? 1 : 0,
  153. 'ancestral_place' => $auth ? $auth['ancestral_place'] : '',
  154. 'auth_info' => $auth_info,
  155. 'user_work_type_id' => $user_work_type_title['title'],
  156. ];
  157. }
  158. $inviteCount = array_column($rankList, 'invite_count');
  159. $uid = array_column($rankList, 'uid');
  160. array_multisort($inviteCount, SORT_DESC, $uid, SORT_ASC, $rankList);
  161. $data['list'] = $rankList;
  162. return app('json')->success($data);
  163. }
  164. /**
  165. * 设置用户信息
  166. * @param Request $request
  167. */
  168. public function setUserInfo(Request $request){
  169. $post = UtilService::getMore([
  170. ['avatar',''],
  171. ['nickname',''],
  172. ['name',''],
  173. // ['mobile',''],
  174. ['sex', ''],
  175. ],$request);
  176. $save=[];
  177. if(!empty($post["avatar"])){
  178. $save["avatar"] = $post["avatar"];
  179. }
  180. if(!empty($post["nickname"])){
  181. $save["nickname"] = $post["nickname"];
  182. }
  183. if(!empty($post["name"])){
  184. $save["name"] = $post["name"];
  185. }
  186. // if(!empty($post["mobile"])){
  187. // if(is_mobile($post["mobile"])){
  188. // return app("json")->fail("请输入正确的手机号码");
  189. // }
  190. // $save["mobile"] = $post["mobile"];
  191. // }
  192. if(in_array((string)$post["sex"],["0","1","2"])){
  193. $save["sex"] = (int)$post["sex"];
  194. }
  195. if(empty($save)){
  196. return app("json")->fail("提交数据为空");
  197. }
  198. //是否需要审核
  199. $isInfoAudit = 0;
  200. if($isInfoAudit==0){
  201. $r = (new UserModel)->where("uid",$request->user["uid"])->update($save);
  202. if(!$r){
  203. return app("json")->fail("提交数据为空");
  204. }
  205. }else{
  206. $data = (new UserAudit)->where("uid",$request->user["uid"])->order("id desc")->find();
  207. if(!empty($data) && $data["status"]==0){
  208. return app('json')->fail("资料审核中,请勿重复提交");
  209. }
  210. $save["uid"] = $request->user["uid"];
  211. $save["status"] = 0;
  212. $r = (new UserAudit)->insert($save);
  213. if(!$r){
  214. return app("json")->fail("提交数据为空");
  215. }
  216. }
  217. return app("json")->success("提交成功");
  218. }
  219. /**
  220. * 绑定手机号
  221. * @param Request $request
  222. */
  223. public function bindMobile(Request $request){
  224. [$code] = UtilService::getMore([
  225. ['code', '', 'empty', 'code参数错误'],
  226. ], $request, true);
  227. if(!empty($request->user['mobile'])){
  228. return app('json')->fail("当前账户已绑定过手机号码");
  229. }
  230. $weixinA = new weixina();
  231. $data=$weixinA->getPhoneNumber($code);//新版
  232. if(empty($data) || empty($data['purePhoneNumber'])) {
  233. return app('json')->fail("绑定失败,请重新绑定01".$weixinA->error);
  234. }
  235. $save=[
  236. // "countryCode"=>empty($data['countryCode'])?"":$data['countryCode'],
  237. "mobile"=>$data['purePhoneNumber'],
  238. ];
  239. // if($request->user["nickname"]=="微信用户"){
  240. // $save["nickname"] = $data['purePhoneNumber'];
  241. // }
  242. $r = (new UserModel)->where('uid', $request->user['uid'])->update($save);
  243. if(!$r){
  244. return app('json')->fail("绑定失败,请重新绑定02");
  245. }
  246. $result = [];
  247. $result['nickname'] = $request->user['nickname'];
  248. $result['avatar'] = $request->user['avatar'];
  249. return app('json')->success($result);
  250. }
  251. /**
  252. * 获取名片信息
  253. * @param Request $request
  254. */
  255. public function getUserCardInfo(Request $request){
  256. $data = (new InfoAudit)->getItem(["uid"=>$request->user["uid"],"status"=>1]);
  257. if(empty($data)){
  258. return app('json')->fail("您还没有通过名片信息审核");
  259. }
  260. $typeData = (new TypeAudit)->where("uid",$request->user["uid"])->order("id","desc")->find();
  261. $data["is_type_audit"] = (empty($typeData) || $typeData["status"]!=1)?0:1;
  262. return app('json')->success($data);
  263. }
  264. /**
  265. * 提交资料审核
  266. * @param Request $request
  267. */
  268. public function subInfoAudit(Request $request){
  269. $data = (new InfoAudit)->where("uid",$request->user["uid"])->order("id desc")->find();
  270. if(!empty($data) && $data["status"]==0){
  271. return app('json')->fail("资料审核中,请勿重复提交");
  272. }
  273. $post = UtilService::getMore([
  274. ['avatar',''],
  275. ['name','','empty','请输入真实姓名'],
  276. ['mobile','','is_moblie','请输入正确的手机号码'],
  277. ['idcard','','empty','请输入正确的身份证号码'],
  278. ['birthday',''],
  279. ['service_type',''],
  280. ['service_price',''],
  281. ['service_min_price',''],
  282. ['service_max_price',''],
  283. ['service_area',[]],
  284. ['service_project',[]],
  285. ['service_intro_content',''],
  286. ['service_intro_imgs',[]],
  287. ['service_audit_imgs',[]],//此处为我的证书
  288. ['service_imgs',[]],//我的服务照片
  289. ['service_count',0],
  290. ['work_year',''],
  291. ['ancestral_place',''],
  292. ['education',''],
  293. ['minority',''],
  294. ['is_china',1],
  295. ['user_work_type_id','0'],//服务职称
  296. ['service_label',[]],//服务标签
  297. ],$request);
  298. if(!IdentityCard::isValid($post["idcard"])){
  299. return app('json')->fail("请输入正确的身份证号码");
  300. }
  301. $save=[];
  302. $save["avatar"] = empty($post["avatar"]) ? "" : $post["avatar"];
  303. $save["name"] = empty($post["name"]) ? "" : $post["name"];
  304. $save["mobile"] = empty($post["mobile"]) ? "" : $post["mobile"];
  305. $save["idcard"] = empty($post["idcard"]) ? "" : $post["idcard"];
  306. $save["service_count"] = $post['service_count'];
  307. // $save["birthday"] = empty($post["birthday"])? 0 : strtotime($post["birthday"]);
  308. $save["constellation"] = IdentityCard::get_starsign($post["idcard"]);//星座
  309. $save["twelve"] = IdentityCard::get_zodiac($post["idcard"]);//星座
  310. $save["birthday"] = strtotime(IdentityCard::get_birthday($post["idcard"]));
  311. //服务类型
  312. if(!empty($post["service_type"])){
  313. $timeTypeData = (new ServiceTimeType)->where("code",$post["service_type"])->where("status",1)->select();
  314. if(empty($timeTypeData)){
  315. return app('json')->fail("服务时长类型不存在");
  316. }
  317. $save["service_type"] = $post["service_type"];
  318. }
  319. //服务价格区间
  320. // $save["service_price"] = empty($post["service_price"]) ? "" : $post["service_price"];
  321. $save["service_min_price"] = empty($post["service_min_price"]) ? 0 : $post["service_min_price"];
  322. $save["service_max_price"] = empty($post["service_max_price"]) ? 0 : $post["service_max_price"];
  323. //服务区域
  324. $cityModel = new CityModel();
  325. if(!empty($post["service_area"]) && is_array($post["service_area"])){
  326. $saveAre=[];
  327. foreach($post["service_area"] as $v){
  328. $stc = str_replace(['省','市','区','县'],['','','',''],$v);
  329. $str = str_replace(['辖'],['市辖'],$stc);
  330. $arr = explode(",",$str);
  331. $city_id = $cityModel->where('merger_name','like',"%".$arr[1].",".$arr[2])->value('id');
  332. if(!$city_id) $city_id = $cityModel->where('merger_name','like',"%".$arr[0].",".$arr[1])->value('id');
  333. $saveAre[] = $city_id;
  334. }
  335. if(!empty($saveAre)){
  336. $save["service_area"] = implode(",", $saveAre);
  337. }
  338. }
  339. // //服务区域
  340. // $cityModel = new CityModel();
  341. // if(!empty($post["service_area"]) && is_array($post["service_area"])){
  342. // $saveAre=[];
  343. // foreach($post["service_area"] as $v){
  344. // @file_put_contents('dub.txt','1');
  345. // $arr = explode(",",$v);
  346. // $str1 = $arr[0].','.$arr[1];
  347. // @file_put_contents('dub.txt','2');
  348. // $stc = str_replace(['省','市','区','县'],['','','',''],$str1);
  349. // $str2 = $stc.",".$arr[2]!='市辖区'?str_replace(['省','市','区','县'],['','','',''],$arr[2]):'市辖区';
  350. // $arr3 = explode(",",$str2);
  351. // $city_id = $cityModel->where('merger_name','like',"%".$arr3[1].",".$arr3[2])->value('id');
  352. // @file_put_contents('dub.txt','3');
  353. // if(!$city_id)
  354. // {
  355. // $city_id = $cityModel->where('merger_name','like',"%".$arr3[0].",".$arr3[1])->value('id');
  356. // $city_id1 = $cityModel->where('merger_name','like',"%".$arr3[0].",".$arr3[1])->value('city_id');
  357. // $city_id2 = $cityModel->where('parent_id',$city_id1)->where('name','市辖区')->value('id');
  358. // if($city_id2>0) $city_id= $city_id2;
  359. // }
  360. // @file_put_contents('dub.txt','4');
  361. // $saveAre[] = $city_id;
  362. //
  363. // }
  364. // if(!empty($saveAre)){
  365. // $save["service_area"] = implode(",", $saveAre);
  366. // }
  367. // }
  368. //服务内容
  369. $serviceTypeModel = new ServiceTypeModel();
  370. if(!empty($post["service_project"]) && is_array($post["service_project"])){
  371. $saveCon=[];
  372. foreach($post["service_project"] as $k=>$v){
  373. if(empty(trim($v))){
  374. continue;
  375. }
  376. $itemData = $serviceTypeModel->where("id",(int)$v)->where("status",1)->find();
  377. if(!empty($itemData)){
  378. $saveCon[]=$itemData["id"];
  379. }
  380. }
  381. if(!empty($saveCon)){
  382. $save["service_project"] = implode(",", $saveCon);
  383. }
  384. }
  385. //服务标签
  386. $save["service_label"]="";
  387. $labelData = (new ServiceLabelModel)->getColumnList("id","id",$post["service_label"]);
  388. if(!empty($labelData)){
  389. $save["service_label"] = implode(",", $labelData);
  390. }
  391. $save["service_intro_content"] = empty($post["service_intro_content"])? "" : $post["service_intro_content"];
  392. $save["service_intro_imgs"] = empty($post["service_intro_imgs"]) ? "" : implode(",", $post["service_intro_imgs"]);
  393. $save["service_audit_imgs"] = empty($post["service_audit_imgs"]) ? "" : implode(",", $post["service_audit_imgs"]);
  394. $save["service_imgs"] = empty($post["service_imgs"]) ? "" : implode(",", $post["service_imgs"]);//我的服务展示
  395. $save['work_year'] = empty($post["work_year"]) ? "": $post["work_year"];
  396. $save['ancestral_place'] = empty($post["ancestral_place"])? "": $post["ancestral_place"];
  397. $save['education'] = empty($post["education"]) ? "": $post["education"];
  398. $save['minority'] = empty($post["minority"]) ? "": $post["minority"];
  399. $save["status"] = 1;
  400. $save["time"] = time();
  401. $save["uid"] = $request->user["uid"];
  402. $save['is_china'] = $post["is_china"];
  403. //服务职称
  404. $save["user_work_type_id"] = empty($post["user_work_type_id"]) ? 0: (int)$post["user_work_type_id"];
  405. if($save["user_work_type_id"]>0 && (new UserWorkType)->where("id",$post["user_work_type_id"])->where("status",1)->count()<=0){
  406. return app('json')->fail("当前类型不能选择");
  407. }
  408. //生成编码
  409. $r = (new InfoAudit)->insertGetId($save);
  410. if (!$r) {
  411. return app('json')->fail("系统错误");
  412. }
  413. $exist = (new InfoAudit)->where('uid', $save['uid'])->find();
  414. if ($exist && !empty($exist['no'])) {
  415. $no = $exist['no'];
  416. } else {
  417. $id = str_pad($r, 5, "0", STR_PAD_LEFT);
  418. $no = "MYJ" . date("ym") . $id;
  419. }
  420. (new InfoAudit)->where("id", $r)->update(["no" => $no]);
  421. (new InfoAudit)->where("id", $r)->update(["status" => 1]);
  422. return app('json')->success("提交成功,数据已通过审核");
  423. }
  424. /**
  425. * 平台认证
  426. * @param Request $request
  427. */
  428. public function subTypeAudit(Request $request){
  429. $data = (new TypeAudit)->where("uid",$request->user["uid"])->order("id desc")->find();
  430. if(!empty($data) && $data["status"]==0){
  431. return app('json')->fail("平台审核中,请勿重复提交");
  432. }
  433. $post = UtilService::getMore([
  434. ['service_audit_imgs',[],"empty","请上传服务认证截图"],
  435. ['store_name','','',''],
  436. ],$request);
  437. $save=[];
  438. $save["service_audit_imgs"] = is_array($post["service_audit_imgs"]) ? implode(",", $post["service_audit_imgs"]) : "";
  439. $save["store_name"] = empty($post["store_name"]) ? "" : $post["store_name"];
  440. $save["status"] = 0;
  441. $save["time"] = time();
  442. $save["uid"] = $request->user["uid"];
  443. if(empty($save["service_audit_imgs"])){
  444. return app('json')->fail("请上传服务认证截图");
  445. }
  446. $r = (new TypeAudit)->insertGetId($save);
  447. if(!$r){
  448. return app('json')->fail("系统错误");
  449. }
  450. $no = "CERT-".date("YmdHis")."-".$r;
  451. (new TypeAudit)->where("id",$r)->update(["no"=>$no]);
  452. return app('json')->success("提交成功,请耐心等待审核");
  453. }
  454. /**
  455. * 模板订单提交[第一步]
  456. * @param Request $request
  457. */
  458. public function subShowTemplateOrder(Request $request){
  459. [$id,$pay_type] = UtilService::getMore([
  460. ['id','','empty','参数错误'],
  461. ['pay_type','','empty','请选择支付方式'],
  462. ],$request,true);
  463. if(!in_array($pay_type,["wxpay","balance"])){
  464. return app('json')->fail('不支持该支付方式!');
  465. }
  466. $weixinConfig = (new SysModel)->getWeixinConfig();
  467. // if(empty($weixinConfig)){
  468. // return app('json')->fail('支付配置为空!');
  469. // }
  470. //缓存
  471. $redis = \think\facade\Cache::store('redis');
  472. $key = 'show_template_order_sub_' . $request->user['uid'];
  473. $bool = $redis->handler()->exists($key);
  474. if ($bool) {
  475. return app('json')->fail('请务重复操作,请稍等在重试!');
  476. }
  477. $redis->set($key,1,5);//5秒缓存
  478. $proData = (new ShowTemplate)->where("id",$id)->where("status",1)->find();
  479. if(empty($proData)){
  480. return app('json')->fail("当前模板已下架");
  481. }
  482. $proData = $proData->toArray();
  483. $count = (new UserShowTemplate)->where("uid",$request->user['uid'])->where("show_template_id",$id)->count();
  484. if($count>0){
  485. return app('json')->fail("您已购买过当前模板");
  486. }
  487. //验证
  488. $orderCount = (new ShowTemplateOrder)->where("uid",$request->user['uid'])->where("show_template_id",$id)->where("status",1)->count();
  489. if($orderCount>0){
  490. return app('json')->fail("您已下单该模板,请勿重复下单");
  491. }
  492. $price = floatval($proData["price"]);
  493. // if($price<0.01){
  494. // return app('json')->fail("模板信息错误");
  495. // }
  496. $allMoney = $price;//订单商品费用
  497. $total_money = $allMoney;//订单总费用
  498. $payMoney = $total_money;//订单需支付费用
  499. $payMoney = $payMoney <= 0 ? 0 : $payMoney;
  500. $nowTime = time();
  501. //余额支付验证
  502. if($pay_type=="balance" && $payMoney > $request->user["money"]){
  503. return app('json')->fail("当前余额不足");
  504. }
  505. //主订单数据
  506. $save=[];
  507. $save['uid'] = $request->user['uid'];
  508. $save['order_id'] = makeOrderId($request->user['uid'],"ST");
  509. $save['pay_type'] = $pay_type;//
  510. $save['total_money'] = $total_money;//订单总金额
  511. $save['all_money'] = $allMoney;//商品中金额
  512. $save['pay_money'] = $payMoney;//实际支付金额
  513. $save['balance'] = 0;//余额支付了多少(目前不用)
  514. $save['status'] = $payMoney <= 0 ? 1 : 0;
  515. $save['pay_time'] = $payMoney <= 0 ? time() : 0;
  516. $save['time'] = $nowTime;
  517. $save['show_template_id'] = $proData["id"];
  518. $save['show_template_title'] = $proData["title"];;
  519. $save['show_template_price'] = $proData["price"];
  520. $save['show_template_img'] = empty($proData["imgs"]) ? "" : explode(",", $proData["imgs"])[0];
  521. $save['show_template_code'] = $proData["code"];
  522. //余额实时支付
  523. if($pay_type=="balance"){
  524. $save['status'] = 1;
  525. $save['pay_time'] = time();
  526. }
  527. try{
  528. Db::startTrans();
  529. $o_id = (new ShowTemplateOrder)->insertGetId($save);
  530. if(empty($o_id)){
  531. return app('json')->fail("订单提交失败");
  532. }
  533. //不需要支付
  534. if($payMoney<=0 && $save['status']==1){
  535. //验证并绑定当前模板
  536. (new UserShowTemplate)->userBindTemp($save["show_template_id"],$save['uid']);
  537. Db::commit();
  538. return app("json")->success(["order_id"=>$save['order_id'],"money"=>$payMoney,"status"=>$save['status']]);
  539. }
  540. //余额支付
  541. if($pay_type=="balance"){
  542. //验证并绑定当前模板
  543. (new UserShowTemplate)->userBindTemp($save["show_template_id"],$save['uid']);
  544. //修改用户余额
  545. $res = (new UserDetailModel)->balancePay($request->user["uid"],$payMoney,"show_temp_pay",["to_id"=>$o_id]);
  546. if(!$res){
  547. Db::rollback();
  548. return app('json')->fail("余额支付失败");
  549. }
  550. Db::commit();
  551. return app("json")->success(["order_id"=>$save['order_id'],"money"=>$payMoney,"status"=>$save['status']]);
  552. }
  553. //微信支付
  554. if(empty($request->user['openid'])){
  555. Db::rollback();
  556. return app('json')->fail('用户还未绑定微信!');
  557. }
  558. //清理之前支付凭证 || 防止重复购买
  559. $payTrade = (new PayTradeModel)
  560. ->where("uid",$request->user["uid"])
  561. ->where("o_id",$o_id)
  562. ->where("type","temp")
  563. ->where("status",0)
  564. ->where("time","<",time() - 7*24*60*60)
  565. ->select()
  566. ->toArray();
  567. $wxpay = new wxpayApi();
  568. // $wxpay = new wxpayApi($weixinConfig);
  569. foreach ($payTrade as $v) {
  570. // if($v['pay_type'] == 'wxpay') {
  571. // $result = $wxpay->closeOrder($v['pay_no']);
  572. // }
  573. (new PayTradeModel)->where("id",$v['id'])->where("status",0)->delete();
  574. }
  575. $mtime = microtime(true)*10000;
  576. $payOn = "T".date("Ymd").$mtime .rand(100,999) . $request->user['uid'];
  577. $out_trade_no="";
  578. $payType = $save["pay_type"];
  579. //添加交易记录
  580. $trade = [
  581. 'uid' => $request->user['uid'],
  582. 'o_id' => $o_id,
  583. 'order_id' =>$save["order_id"],
  584. 'pay_no' => $payOn,
  585. 'out_trade_no' => empty($out_trade_no) ? $payOn : $out_trade_no,
  586. 'pay_type' => $payType,
  587. 'money' => $payMoney,
  588. 'type' => 'temp',
  589. 'd_json' => serialize(['orderId'=>$save["order_id"],"give_score"=>0]),
  590. 'time' => time(),
  591. 'status' => 0,
  592. ];
  593. $r=(new PayTradeModel)->insert($trade);
  594. if(!$r){
  595. Db::rollback();
  596. return app('json')->fail('支付信息获取失败!');
  597. }
  598. $clictip = get_client_ip();
  599. if(empty($clictip)){
  600. $clictip = $request->ip();
  601. }
  602. $payData = $wxpay->wxmpPay([
  603. 'body' => "微信小程序购买模板",
  604. 'out_trade_no' => $payOn,
  605. 'total' => $payMoney,
  606. 'openid' => $request->user['openid'],
  607. 'payer_client_ip' => $clictip,
  608. ]);
  609. if(empty($payData)){
  610. Db::rollback();
  611. return app('json')->fail($wxpay->errorMsg);
  612. }
  613. Db::commit();
  614. $redis->delete($key);
  615. return app('json')->success([
  616. 'jsApiParameters'=> $payData,
  617. 'pay_no' => $payOn,
  618. 'order_id' => $save["order_id"],
  619. "status" => $save['status'],
  620. "money" => $payMoney,
  621. ]);
  622. } catch (DbException $db){
  623. Db::rollback();
  624. return app('json')->fail("订单生成失败");
  625. }
  626. }
  627. /**
  628. * 获取模板购买订单详情
  629. * @param Request $request
  630. */
  631. public function payShowTemplateOrderInfo(Request $request){
  632. [$order_id] = UtilService::getMore([
  633. ['order_id','','empty','参数错误'],
  634. ],$request,true);
  635. $data = (new ShowTemplateOrder)
  636. ->field("order_id,total_money,all_money,pay_money,status,time")
  637. ->where("order_id",$order_id)
  638. ->where("uid",$request->user["uid"])
  639. ->find();
  640. if(empty($data)){
  641. return app('json')->fail('信息不存在!');
  642. }
  643. $data=$data->toArray();
  644. if($data["status"]==0 && $data["time"]<time() - 30*60){
  645. (new ShowTemplateOrder)->where("id",$data["id"])->where("uid",$request->user["uid"])->update(["status"=>-1]);
  646. $data["status"]==-1;
  647. }
  648. $data["time"] = date("Y-m-d H:i:s",$data["time"]);
  649. return app('json')->success($data);
  650. }
  651. /**
  652. * 用户模板列表
  653. * @param Request $request
  654. */
  655. public function userShowTemplateList(Request $request){
  656. $post = UtilService::getMore([
  657. ['page', 1],
  658. ['pageSize', 50],
  659. ], $request);
  660. $post["pageSize"] = $post["pageSize"]>50 ? 50 : (int)$post["pageSize"];
  661. $post["page"] = $post["page"]<=0 ? 1 : (int)$post["page"];
  662. $where=[];
  663. $where[]=["ut.uid","=",$request->user["uid"]];
  664. $totalCount = (new UserShowTemplate)->alias("ut")->where($where)->count();
  665. $data=null;
  666. if($totalCount>0){
  667. $data = (new UserShowTemplate)
  668. ->field("ut.id,t.id as show_template_id,t.title,t.price,t.old_price,t.status,t.imgs,t.is_hot,t.is_recommend,t.code,look_count,t.real_sales,t.unreal_sales,ut.is_default")
  669. ->alias("ut")
  670. ->join("show_template t", "t.id = ut.show_template_id","left")
  671. ->where($where)
  672. ->order("ut.is_default", "desc")
  673. ->order("ut.id", "desc")
  674. ->page($post["page"], $post["pageSize"])
  675. ->select();
  676. foreach($data as $k=>$v){
  677. $data[$k]["is_use"] = 1;//是否已经购买或者可以使用
  678. $data[$k]["imgs"] = getImageAr($v["imgs"]);
  679. $data[$k]["img"] = empty($data[$k]["imgs"]) ? "" : $data[$k]["imgs"][0];
  680. $data[$k]["sales_count"] = $data[$k]["real_sales"] + $data[$k]["unreal_sales"];
  681. unset($data[$k]["real_sales"]);
  682. unset($data[$k]["unreal_sales"]);
  683. }
  684. }
  685. $data = empty($data)?[]:$data;
  686. return app('json')->success(["list" => $data, "pageSize" => $post["pageSize"],"page"=>$post["page"],"totalCount"=>$totalCount]);
  687. }
  688. /**
  689. * 设置默认模板
  690. * @param Request $request
  691. */
  692. public function setShowTemplate(Request $request) {
  693. [$show_template_id] = UtilService::getMore([
  694. ['show_template_id', '', 'empty', '参数错误'],
  695. ], $request, true);
  696. (new UserShowTemplate)->where("uid", $request->user["uid"])->where("is_default", 1)->update(["is_default" => 0]);
  697. (new UserShowTemplate)->where("uid", $request->user["uid"])->where("show_template_id", $show_template_id)->update(["is_default" => 1]);
  698. return app('json')->success("设置成功");
  699. }
  700. /**
  701. * 获取邀请海报小程序码
  702. * @param Request $request
  703. */
  704. public function getWxmpInviteQrcode(Request $request){
  705. $inviteData = (new SysModel)->getDataInfo("invite");
  706. $bgimg = $inviteData["img"];
  707. if(!empty($request->user["invite_img"])){
  708. return app('json')->success(["qrcode"=>$request->user["invite_img"],"bgimg"=>$bgimg]);
  709. }
  710. $weixinA = new weixina();
  711. // $data = $weixinA->getUnlimitedQRCode("pages/index/index","scene=".$request->user["uid"]);
  712. $data = $weixinA->getUnlimitedQRCode("pages/index/index",$request->user["uid"]);
  713. // var_dump($data);
  714. if(empty($data)){
  715. return app('json')->fail("小程序码获取失败".$weixinA->error);
  716. }
  717. $base64 = 'data:'.$data['contentType'].';base64,'.base64_encode($data['buffer']);
  718. $res = $this->uploadImageBase64("wximg",$base64,1);
  719. if($res["code"]!=1){
  720. return app('json')->fail($res["msg"]);
  721. }
  722. (new UserModel)->where("uid",$request->user["uid"])->update(["invite_img"=>$res["url"]]);
  723. return app('json')->success(["qrcode"=>$res["url"],"bgimg"=>$bgimg]);
  724. }
  725. // public function getWxmpInviteQrcode2(Request $request){
  726. //
  727. // //获取小程序码
  728. // $weixinA = new weixina();
  729. // $data = $weixinA->getUnlimitedQRCode("pages/index/index","scene=".$request->user["uid"]);
  730. // if(empty($data)){
  731. // return app('json')->fail("小程序码获取失败".$weixinA->error);
  732. // }
  733. // $base64 = 'data:'.$data['contentType'].';base64,'.base64_encode($data['buffer']);
  734. // $code = "temp";
  735. // $sysData = (new SysModel())->where("id",1)->find();
  736. // $uploadConfig = config('filesystem');
  737. // //验证base64格式
  738. // preg_match('/^(data:\s*image\/(\w+);base64,)/',$base64, $result);
  739. // if(!$result){
  740. // return ["code"=>-1,"msg"=>"base64格式格式错误"];
  741. // }
  742. // //验证图片后缀
  743. // if (!in_array($result[2], $uploadConfig['image']['ext'], true)) {
  744. // return ["code"=>-1,"msg"=>"不支持的图片格式"];
  745. // }
  746. // $rootPath = config('filesystem.disks.resource.root');
  747. // $hashName = $code.DIRECTORY_SEPARATOR.date('Ymd') . DIRECTORY_SEPARATOR . md5((string) microtime(true)).".".$result[2];
  748. // $filePath = $rootPath. DIRECTORY_SEPARATOR .$hashName;
  749. // $path = dirname($filePath);
  750. // // 检测目录
  751. // if (!is_dir($path)) {
  752. // if (!mkdir($path, 0777, true)) {
  753. // return ["code"=>-1,"msg"=>"生成目录失败"];
  754. // }
  755. // return ["code"=>-1,"msg"=>"上传目录不存在"];
  756. // }
  757. // //重名文件验证
  758. // if (is_file($filePath)) {
  759. // return ["code"=>-1,"msg"=>"文件已存在"];
  760. // }
  761. // if(!file_put_contents($filePath, base64_decode(str_replace($result[1], '', $base64)))){
  762. // return ["code"=>-1,"msg"=>"文件报错失败"];
  763. // }
  764. //
  765. // //获取海报背景
  766. // $inviteData = (new SysModel)->getDataInfo("invite");
  767. // if(empty($inviteData["img"])){
  768. // return ["code"=>-1,"msg"=>"海报背景不存在"];
  769. // }
  770. // $bgimg =explode("resource", $inviteData["img"])[1];
  771. // if(empty($bgimg)){
  772. // return ["code"=>-1,"msg"=>"海报背景不存在"];
  773. // }
  774. //
  775. // $savePath = $rootPath. DIRECTORY_SEPARATOR .$code.DIRECTORY_SEPARATOR.date('Ymd') . DIRECTORY_SEPARATOR . md5((string) microtime(true))."b".".jpg";
  776. //
  777. //
  778. //
  779. //
  780. // $bg = $rootPath.$bgimg;
  781. // $bgSize = getimagesize($bg);
  782. // $qrcodeSize = getimagesize($filePath);
  783. // $handle = Image::open($bg);
  784. // $handle->water($filePath,[($bgSize[0]-$qrcodeSize[0])/2,($bgSize[1]-$qrcodeSize[1])/2]);
  785. // $handle->save($savePath,"jpg",80);
  786. // $qiniu = new Qiniu;
  787. // $img_url = $qiniu->updateFile('img', $savePath, $savePath);
  788. // if (empty($img_url['url'])) {
  789. // return ["code"=>-1,"msg"=>"文件报错失败:".$qiniu->getError()];
  790. // }
  791. // @unlink($filePath);
  792. // @unlink($savePath);
  793. // return ["code"=>1,"url"=>str_replace("\\", "/", $img_url['url'])];
  794. // }
  795. //
  796. // public function checkImgPath(){
  797. //
  798. // }
  799. /**
  800. * 图片合成
  801. * @param type $bg
  802. * @param type $qrcode
  803. * @param type $savePath
  804. */
  805. public function createPosterImg($bg,$qrcode,$savePath){
  806. }
  807. /**
  808. * 获取小程序码
  809. * @param Request $request
  810. */
  811. public function getWxmpQrcode(Request $request){
  812. $weixinA = new weixina();
  813. $data = $weixinA->getUnlimitedQRCode("pages/index/index","a=1");
  814. if(empty($data)){
  815. return app('json')->fail("小程序码获取失败".$weixinA->error);
  816. }
  817. $base64 = 'data:'.$data['contentType'].';base64,'.base64_encode($data['buffer']);
  818. $res = $this->uploadImageBase64("wximg",$base64);
  819. if($res["code"]!=1){
  820. return app('json')->fail($res["msg"]);
  821. }
  822. return app('json')->success(["img"=>$res["data"]]);
  823. }
  824. /**
  825. *
  826. * @param Request $request
  827. */
  828. public function uploadBase64(Request $request){
  829. [$img,$code] = UtilService::getMore([
  830. ['img', '','empty',"请上传图片"],
  831. ['code', 'image'],
  832. ], $request,true);
  833. // $imgAr = explode("base64,",$img);
  834. // if(empty($imgAr)){
  835. // return app("json")->fail("请上传base64图片");
  836. // }
  837. // $imgBase64 = count($imgAr)==1?$imgAr[0]:$imgAr[1];
  838. // //判断字符串是否经过编码方法
  839. // if($imgBase64!=base64_encode(base64_decode($imgBase64))){
  840. // return app("json")->fail("请上传base64图片");
  841. // }
  842. // $base64 = "data:application/octet-stream;base64,".$imgBase64;//七牛
  843. $res = $this->uploadImageBase64($code,$img);
  844. if($res["code"]!=1){
  845. return app('json')->fail($res["msg"]);
  846. }
  847. return app('json')->success(["img"=>$res["data"]]);
  848. }
  849. /**
  850. * 图片上传
  851. * @param Request $request
  852. * @return type
  853. */
  854. public function upload(Request $request){
  855. $uploadConfig = config('filesystem');
  856. $sysData = (new SysModel())->where("id",1)->find();
  857. $file = $request->file('file');
  858. $code = $request->post("code","image");
  859. if(empty($file)) {
  860. return app('json')->fail("未上传文件");
  861. }
  862. $size = $file->getSize();
  863. if(!empty($size) && $size>$uploadConfig["image"]["size"]*1024*1024){
  864. return app('json')->fail("图片不能超过{$uploadConfig["image"]["size"]}M");
  865. }
  866. if(!in_array($code, $uploadConfig['image']['path'])){
  867. return app('json')->fail("上传路径错误");
  868. }
  869. $ext = $file->extension();
  870. if(!in_array($ext, $uploadConfig['image']['ext'])){
  871. return app('json')->fail("图片类型错误");
  872. }
  873. $upPath = \think\facade\Filesystem::disk('resource')->putFile( $code, $file);
  874. if(!$upPath){
  875. return app('json')->fail("上传失败01");
  876. }
  877. $savePath = $sysData['system_url'].'/resource/' . $upPath;
  878. $imgUrl = str_replace("\\", "/", $savePath);
  879. return app('json')->success(['img'=>$imgUrl,'size'=>$size]);
  880. }
  881. /**
  882. * 视频上传
  883. * @param Request $request
  884. * @return type
  885. */
  886. public function uploadVideo(Request $request){
  887. $uploadConfig = config('filesystem');
  888. $sysData = (new SysModel())->where("id",1)->find();
  889. $file = $request->file('file');
  890. $code = $request->post("code","video");
  891. if(empty($file)) {
  892. return app('json')->fail("未上传文件");
  893. }
  894. if(!in_array($code, $uploadConfig['video']['path'])){
  895. return app('json')->fail("上传路径错误");
  896. }
  897. $ext = $file->extension();
  898. if(!in_array($ext, $uploadConfig['video']['ext'])){
  899. return app('json')->fail("视频类型错误");
  900. }
  901. $upPath = \think\facade\Filesystem::disk('resource')->putFile( $code, $file);
  902. if(!$upPath){
  903. return app('json')->fail("上传失败01");
  904. }
  905. $savePath = $sysData['system_url'].'/resource/' . $upPath;
  906. $imgUrl = str_replace("\\", "/", $savePath);
  907. return app('json')->success(['video'=>$imgUrl]);
  908. }
  909. /**
  910. * base64文件上传
  911. * @param type $code
  912. * @param type $base64
  913. */
  914. public function uploadImageBase64($code,$base64,$isQiniu=0){
  915. $sysData = (new SysModel())->where("id",1)->find();
  916. $uploadConfig = config('filesystem');
  917. //验证base64格式
  918. preg_match('/^(data:\s*image\/(\w+);base64,)/',$base64, $result);
  919. if(!$result){
  920. return ["code"=>-1,"msg"=>"base64格式格式错误"];
  921. }
  922. //验证图片后缀
  923. if (!in_array($result[2], $uploadConfig['image']['ext'], true)) {
  924. return ["code"=>-1,"msg"=>"不支持的图片格式"];
  925. }
  926. $rootPath = config('filesystem.disks.resource.root');
  927. $hashName = $code.DIRECTORY_SEPARATOR.date('Ymd') . DIRECTORY_SEPARATOR . md5((string) microtime(true)).".".$result[2];
  928. $filePath = $rootPath. DIRECTORY_SEPARATOR .$hashName;
  929. $path = dirname($filePath);
  930. // 检测目录
  931. if (!is_dir($path)) {
  932. if (!mkdir($path, 0777, true)) {
  933. return ["code"=>-1,"msg"=>"生成目录失败"];
  934. }
  935. return ["code"=>-1,"msg"=>"上传目录不存在"];
  936. }
  937. //重名文件验证
  938. if (is_file($filePath)) {
  939. return ["code"=>-1,"msg"=>"文件已存在"];
  940. }
  941. if(!file_put_contents($filePath, base64_decode(str_replace($result[1], '', $base64)))){
  942. return ["code"=>-1,"msg"=>"文件报错失败"];
  943. }
  944. //七牛上传
  945. if($isQiniu==1){
  946. $qiniu = new Qiniu;
  947. $img_url = $qiniu->updateFile('img', $filePath, $filePath);
  948. if (empty($img_url['url'])) {
  949. return ["code"=>-1,"msg"=>"文件报错失败:".$qiniu->getError()];
  950. }
  951. @unlink($filePath);
  952. return ["code"=>1,"url"=>str_replace("\\", "/", $img_url['url'])];
  953. }
  954. $savePath = $sysData['system_url'].config('filesystem.disks.resource.url').DIRECTORY_SEPARATOR.$hashName;
  955. return ["code"=>1,"url"=>str_replace("\\", "/", $savePath)];
  956. }
  957. /**
  958. * 七牛上传图片
  959. * @param Request $request
  960. */
  961. public function qiniuUpload(Request $request)
  962. {
  963. $file = $request->file('file');
  964. if (empty($file)) {
  965. return app('json')->fail("未上传文件");
  966. }
  967. $rootTmp = config('filesystem.disks.local.root') . '/' . \think\facade\Filesystem::putFile('tmp', $file);
  968. $image_size = @getimagesize($rootTmp);
  969. if ($image_size[0] > 1000) {
  970. $imgS = Image::open($rootTmp);
  971. $imgS->thumb(1000, $image_size[1]);
  972. $imgS->save($rootTmp);
  973. } else {
  974. if ($image_size[1] > 1000) {
  975. $imgS = Image::open($rootTmp);
  976. $imgS->thumb($image_size[0], 1000);
  977. $imgS->save($rootTmp);
  978. }
  979. }
  980. $qiniu = new Qiniu;
  981. $img_url = $qiniu->updateFile('img', $rootTmp, $rootTmp);
  982. if (empty($img_url['url'])) {
  983. return app('json')->fail($qiniu->getError());
  984. }
  985. @unlink($rootTmp);
  986. return app('json')->success(['img' => $img_url['url']]);
  987. }
  988. /**
  989. * 七牛上传token
  990. * @param Request $request
  991. */
  992. public function qiniuUploadToken(Request $request){
  993. [$bucket] = UtilService::getMore([
  994. ['bucket', ''],
  995. ], $request,true);
  996. $qiniu = new Qiniu;
  997. $token = $qiniu->createUploadToken($bucket);
  998. return app('json')->success(['token' => $token]);
  999. }
  1000. /**
  1001. * 获取用户模板信息
  1002. * @param int $uid 用户ID
  1003. * @return array
  1004. */
  1005. private function getUserInfo($uid)
  1006. {
  1007. $userInfo = (new UserModel)->where('uid', $uid)->find();
  1008. $auth = (new InfoAudit)->where('uid', $uid)->find();
  1009. $user_work_type_title = (new UserWorkType)->where('id', $auth['user_work_type_id'])->find();
  1010. if ($auth) {
  1011. $auth_info = $auth->toArray();
  1012. } else {
  1013. $auth_info = null;
  1014. }
  1015. return [
  1016. 'is_type_audit' => $auth && $auth['status'] == 1 ? 1 : 0,
  1017. 'ancestral_place' => $auth ? $auth['ancestral_place'] : '',
  1018. 'auth_info' => $auth_info,
  1019. 'user_work_type_id' => $user_work_type_title['title'],
  1020. ];
  1021. }
  1022. }