User.php 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113
  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"] = 0;
  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. return app('json')->success("提交成功,请耐心等待审核");
  422. }
  423. /**
  424. * 平台认证
  425. * @param Request $request
  426. */
  427. public function subTypeAudit(Request $request){
  428. $data = (new TypeAudit)->where("uid",$request->user["uid"])->order("id desc")->find();
  429. if(!empty($data) && $data["status"]==0){
  430. return app('json')->fail("平台审核中,请勿重复提交");
  431. }
  432. $post = UtilService::getMore([
  433. ['service_audit_imgs',[],"empty","请上传服务认证截图"],
  434. ['store_name','','',''],
  435. ],$request);
  436. $save=[];
  437. $save["service_audit_imgs"] = is_array($post["service_audit_imgs"]) ? implode(",", $post["service_audit_imgs"]) : "";
  438. $save["store_name"] = empty($post["store_name"]) ? "" : $post["store_name"];
  439. $save["status"] = 0;
  440. $save["time"] = time();
  441. $save["uid"] = $request->user["uid"];
  442. if(empty($save["service_audit_imgs"])){
  443. return app('json')->fail("请上传服务认证截图");
  444. }
  445. $r = (new TypeAudit)->insertGetId($save);
  446. if(!$r){
  447. return app('json')->fail("系统错误");
  448. }
  449. $no = "CERT-".date("YmdHis")."-".$r;
  450. (new TypeAudit)->where("id",$r)->update(["no"=>$no]);
  451. return app('json')->success("提交成功,请耐心等待审核");
  452. }
  453. /**
  454. * 模板订单提交[第一步]
  455. * @param Request $request
  456. */
  457. public function subShowTemplateOrder(Request $request){
  458. [$id,$pay_type] = UtilService::getMore([
  459. ['id','','empty','参数错误'],
  460. ['pay_type','','empty','请选择支付方式'],
  461. ],$request,true);
  462. if(!in_array($pay_type,["wxpay","balance"])){
  463. return app('json')->fail('不支持该支付方式!');
  464. }
  465. $weixinConfig = (new SysModel)->getWeixinConfig();
  466. // if(empty($weixinConfig)){
  467. // return app('json')->fail('支付配置为空!');
  468. // }
  469. //缓存
  470. $redis = \think\facade\Cache::store('redis');
  471. $key = 'show_template_order_sub_' . $request->user['uid'];
  472. $bool = $redis->handler()->exists($key);
  473. if ($bool) {
  474. return app('json')->fail('请务重复操作,请稍等在重试!');
  475. }
  476. $redis->set($key,1,5);//5秒缓存
  477. $proData = (new ShowTemplate)->where("id",$id)->where("status",1)->find();
  478. if(empty($proData)){
  479. return app('json')->fail("当前模板已下架");
  480. }
  481. $proData = $proData->toArray();
  482. $count = (new UserShowTemplate)->where("uid",$request->user['uid'])->where("show_template_id",$id)->count();
  483. if($count>0){
  484. return app('json')->fail("您已购买过当前模板");
  485. }
  486. //验证
  487. $orderCount = (new ShowTemplateOrder)->where("uid",$request->user['uid'])->where("show_template_id",$id)->where("status",1)->count();
  488. if($orderCount>0){
  489. return app('json')->fail("您已下单该模板,请勿重复下单");
  490. }
  491. $price = floatval($proData["price"]);
  492. // if($price<0.01){
  493. // return app('json')->fail("模板信息错误");
  494. // }
  495. $allMoney = $price;//订单商品费用
  496. $total_money = $allMoney;//订单总费用
  497. $payMoney = $total_money;//订单需支付费用
  498. $payMoney = $payMoney <= 0 ? 0 : $payMoney;
  499. $nowTime = time();
  500. //余额支付验证
  501. if($pay_type=="balance" && $payMoney > $request->user["money"]){
  502. return app('json')->fail("当前余额不足");
  503. }
  504. //主订单数据
  505. $save=[];
  506. $save['uid'] = $request->user['uid'];
  507. $save['order_id'] = makeOrderId($request->user['uid'],"ST");
  508. $save['pay_type'] = $pay_type;//
  509. $save['total_money'] = $total_money;//订单总金额
  510. $save['all_money'] = $allMoney;//商品中金额
  511. $save['pay_money'] = $payMoney;//实际支付金额
  512. $save['balance'] = 0;//余额支付了多少(目前不用)
  513. $save['status'] = $payMoney <= 0 ? 1 : 0;
  514. $save['pay_time'] = $payMoney <= 0 ? time() : 0;
  515. $save['time'] = $nowTime;
  516. $save['show_template_id'] = $proData["id"];
  517. $save['show_template_title'] = $proData["title"];;
  518. $save['show_template_price'] = $proData["price"];
  519. $save['show_template_img'] = empty($proData["imgs"]) ? "" : explode(",", $proData["imgs"])[0];
  520. $save['show_template_code'] = $proData["code"];
  521. //余额实时支付
  522. if($pay_type=="balance"){
  523. $save['status'] = 1;
  524. $save['pay_time'] = time();
  525. }
  526. try{
  527. Db::startTrans();
  528. $o_id = (new ShowTemplateOrder)->insertGetId($save);
  529. if(empty($o_id)){
  530. return app('json')->fail("订单提交失败");
  531. }
  532. //不需要支付
  533. if($payMoney<=0 && $save['status']==1){
  534. //验证并绑定当前模板
  535. (new UserShowTemplate)->userBindTemp($save["show_template_id"],$save['uid']);
  536. Db::commit();
  537. return app("json")->success(["order_id"=>$save['order_id'],"money"=>$payMoney,"status"=>$save['status']]);
  538. }
  539. //余额支付
  540. if($pay_type=="balance"){
  541. //验证并绑定当前模板
  542. (new UserShowTemplate)->userBindTemp($save["show_template_id"],$save['uid']);
  543. //修改用户余额
  544. $res = (new UserDetailModel)->balancePay($request->user["uid"],$payMoney,"show_temp_pay",["to_id"=>$o_id]);
  545. if(!$res){
  546. Db::rollback();
  547. return app('json')->fail("余额支付失败");
  548. }
  549. Db::commit();
  550. return app("json")->success(["order_id"=>$save['order_id'],"money"=>$payMoney,"status"=>$save['status']]);
  551. }
  552. //微信支付
  553. if(empty($request->user['openid'])){
  554. Db::rollback();
  555. return app('json')->fail('用户还未绑定微信!');
  556. }
  557. //清理之前支付凭证 || 防止重复购买
  558. $payTrade = (new PayTradeModel)
  559. ->where("uid",$request->user["uid"])
  560. ->where("o_id",$o_id)
  561. ->where("type","temp")
  562. ->where("status",0)
  563. ->where("time","<",time() - 7*24*60*60)
  564. ->select()
  565. ->toArray();
  566. $wxpay = new wxpayApi();
  567. // $wxpay = new wxpayApi($weixinConfig);
  568. foreach ($payTrade as $v) {
  569. // if($v['pay_type'] == 'wxpay') {
  570. // $result = $wxpay->closeOrder($v['pay_no']);
  571. // }
  572. (new PayTradeModel)->where("id",$v['id'])->where("status",0)->delete();
  573. }
  574. $mtime = microtime(true)*10000;
  575. $payOn = "T".date("Ymd").$mtime .rand(100,999) . $request->user['uid'];
  576. $out_trade_no="";
  577. $payType = $save["pay_type"];
  578. //添加交易记录
  579. $trade = [
  580. 'uid' => $request->user['uid'],
  581. 'o_id' => $o_id,
  582. 'order_id' =>$save["order_id"],
  583. 'pay_no' => $payOn,
  584. 'out_trade_no' => empty($out_trade_no) ? $payOn : $out_trade_no,
  585. 'pay_type' => $payType,
  586. 'money' => $payMoney,
  587. 'type' => 'temp',
  588. 'd_json' => serialize(['orderId'=>$save["order_id"],"give_score"=>0]),
  589. 'time' => time(),
  590. 'status' => 0,
  591. ];
  592. $r=(new PayTradeModel)->insert($trade);
  593. if(!$r){
  594. Db::rollback();
  595. return app('json')->fail('支付信息获取失败!');
  596. }
  597. $clictip = get_client_ip();
  598. if(empty($clictip)){
  599. $clictip = $request->ip();
  600. }
  601. $payData = $wxpay->wxmpPay([
  602. 'body' => "微信小程序购买模板",
  603. 'out_trade_no' => $payOn,
  604. 'total' => $payMoney,
  605. 'openid' => $request->user['openid'],
  606. 'payer_client_ip' => $clictip,
  607. ]);
  608. if(empty($payData)){
  609. Db::rollback();
  610. return app('json')->fail($wxpay->errorMsg);
  611. }
  612. Db::commit();
  613. $redis->delete($key);
  614. return app('json')->success([
  615. 'jsApiParameters'=> $payData,
  616. 'pay_no' => $payOn,
  617. 'order_id' => $save["order_id"],
  618. "status" => $save['status'],
  619. "money" => $payMoney,
  620. ]);
  621. } catch (DbException $db){
  622. Db::rollback();
  623. return app('json')->fail("订单生成失败");
  624. }
  625. }
  626. /**
  627. * 获取模板购买订单详情
  628. * @param Request $request
  629. */
  630. public function payShowTemplateOrderInfo(Request $request){
  631. [$order_id] = UtilService::getMore([
  632. ['order_id','','empty','参数错误'],
  633. ],$request,true);
  634. $data = (new ShowTemplateOrder)
  635. ->field("order_id,total_money,all_money,pay_money,status,time")
  636. ->where("order_id",$order_id)
  637. ->where("uid",$request->user["uid"])
  638. ->find();
  639. if(empty($data)){
  640. return app('json')->fail('信息不存在!');
  641. }
  642. $data=$data->toArray();
  643. if($data["status"]==0 && $data["time"]<time() - 30*60){
  644. (new ShowTemplateOrder)->where("id",$data["id"])->where("uid",$request->user["uid"])->update(["status"=>-1]);
  645. $data["status"]==-1;
  646. }
  647. $data["time"] = date("Y-m-d H:i:s",$data["time"]);
  648. return app('json')->success($data);
  649. }
  650. /**
  651. * 用户模板列表
  652. * @param Request $request
  653. */
  654. public function userShowTemplateList(Request $request){
  655. $post = UtilService::getMore([
  656. ['page', 1],
  657. ['pageSize', 50],
  658. ], $request);
  659. $post["pageSize"] = $post["pageSize"]>50 ? 50 : (int)$post["pageSize"];
  660. $post["page"] = $post["page"]<=0 ? 1 : (int)$post["page"];
  661. $where=[];
  662. $where[]=["ut.uid","=",$request->user["uid"]];
  663. $totalCount = (new UserShowTemplate)->alias("ut")->where($where)->count();
  664. $data=null;
  665. if($totalCount>0){
  666. $data = (new UserShowTemplate)
  667. ->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")
  668. ->alias("ut")
  669. ->join("show_template t", "t.id = ut.show_template_id","left")
  670. ->where($where)
  671. ->order("ut.is_default", "desc")
  672. ->order("ut.id", "desc")
  673. ->page($post["page"], $post["pageSize"])
  674. ->select();
  675. foreach($data as $k=>$v){
  676. $data[$k]["is_use"] = 1;//是否已经购买或者可以使用
  677. $data[$k]["imgs"] = getImageAr($v["imgs"]);
  678. $data[$k]["img"] = empty($data[$k]["imgs"]) ? "" : $data[$k]["imgs"][0];
  679. $data[$k]["sales_count"] = $data[$k]["real_sales"] + $data[$k]["unreal_sales"];
  680. unset($data[$k]["real_sales"]);
  681. unset($data[$k]["unreal_sales"]);
  682. }
  683. }
  684. $data = empty($data)?[]:$data;
  685. return app('json')->success(["list" => $data, "pageSize" => $post["pageSize"],"page"=>$post["page"],"totalCount"=>$totalCount]);
  686. }
  687. /**
  688. * 设置默认模板
  689. * @param Request $request
  690. */
  691. public function setShowTemplate(Request $request) {
  692. [$show_template_id] = UtilService::getMore([
  693. ['show_template_id', '', 'empty', '参数错误'],
  694. ], $request, true);
  695. (new UserShowTemplate)->where("uid", $request->user["uid"])->where("is_default", 1)->update(["is_default" => 0]);
  696. (new UserShowTemplate)->where("uid", $request->user["uid"])->where("show_template_id", $show_template_id)->update(["is_default" => 1]);
  697. return app('json')->success("设置成功");
  698. }
  699. /**
  700. * 获取邀请海报小程序码
  701. * @param Request $request
  702. */
  703. public function getWxmpInviteQrcode(Request $request){
  704. $inviteData = (new SysModel)->getDataInfo("invite");
  705. $bgimg = $inviteData["img"];
  706. if(!empty($request->user["invite_img"])){
  707. return app('json')->success(["qrcode"=>$request->user["invite_img"],"bgimg"=>$bgimg]);
  708. }
  709. $weixinA = new weixina();
  710. // $data = $weixinA->getUnlimitedQRCode("pages/index/index","scene=".$request->user["uid"]);
  711. $data = $weixinA->getUnlimitedQRCode("pages/index/index",$request->user["uid"]);
  712. // var_dump($data);
  713. if(empty($data)){
  714. return app('json')->fail("小程序码获取失败".$weixinA->error);
  715. }
  716. $base64 = 'data:'.$data['contentType'].';base64,'.base64_encode($data['buffer']);
  717. $res = $this->uploadImageBase64("wximg",$base64,1);
  718. if($res["code"]!=1){
  719. return app('json')->fail($res["msg"]);
  720. }
  721. (new UserModel)->where("uid",$request->user["uid"])->update(["invite_img"=>$res["url"]]);
  722. return app('json')->success(["qrcode"=>$res["url"],"bgimg"=>$bgimg]);
  723. }
  724. // public function getWxmpInviteQrcode2(Request $request){
  725. //
  726. // //获取小程序码
  727. // $weixinA = new weixina();
  728. // $data = $weixinA->getUnlimitedQRCode("pages/index/index","scene=".$request->user["uid"]);
  729. // if(empty($data)){
  730. // return app('json')->fail("小程序码获取失败".$weixinA->error);
  731. // }
  732. // $base64 = 'data:'.$data['contentType'].';base64,'.base64_encode($data['buffer']);
  733. // $code = "temp";
  734. // $sysData = (new SysModel())->where("id",1)->find();
  735. // $uploadConfig = config('filesystem');
  736. // //验证base64格式
  737. // preg_match('/^(data:\s*image\/(\w+);base64,)/',$base64, $result);
  738. // if(!$result){
  739. // return ["code"=>-1,"msg"=>"base64格式格式错误"];
  740. // }
  741. // //验证图片后缀
  742. // if (!in_array($result[2], $uploadConfig['image']['ext'], true)) {
  743. // return ["code"=>-1,"msg"=>"不支持的图片格式"];
  744. // }
  745. // $rootPath = config('filesystem.disks.resource.root');
  746. // $hashName = $code.DIRECTORY_SEPARATOR.date('Ymd') . DIRECTORY_SEPARATOR . md5((string) microtime(true)).".".$result[2];
  747. // $filePath = $rootPath. DIRECTORY_SEPARATOR .$hashName;
  748. // $path = dirname($filePath);
  749. // // 检测目录
  750. // if (!is_dir($path)) {
  751. // if (!mkdir($path, 0777, true)) {
  752. // return ["code"=>-1,"msg"=>"生成目录失败"];
  753. // }
  754. // return ["code"=>-1,"msg"=>"上传目录不存在"];
  755. // }
  756. // //重名文件验证
  757. // if (is_file($filePath)) {
  758. // return ["code"=>-1,"msg"=>"文件已存在"];
  759. // }
  760. // if(!file_put_contents($filePath, base64_decode(str_replace($result[1], '', $base64)))){
  761. // return ["code"=>-1,"msg"=>"文件报错失败"];
  762. // }
  763. //
  764. // //获取海报背景
  765. // $inviteData = (new SysModel)->getDataInfo("invite");
  766. // if(empty($inviteData["img"])){
  767. // return ["code"=>-1,"msg"=>"海报背景不存在"];
  768. // }
  769. // $bgimg =explode("resource", $inviteData["img"])[1];
  770. // if(empty($bgimg)){
  771. // return ["code"=>-1,"msg"=>"海报背景不存在"];
  772. // }
  773. //
  774. // $savePath = $rootPath. DIRECTORY_SEPARATOR .$code.DIRECTORY_SEPARATOR.date('Ymd') . DIRECTORY_SEPARATOR . md5((string) microtime(true))."b".".jpg";
  775. //
  776. //
  777. //
  778. //
  779. // $bg = $rootPath.$bgimg;
  780. // $bgSize = getimagesize($bg);
  781. // $qrcodeSize = getimagesize($filePath);
  782. // $handle = Image::open($bg);
  783. // $handle->water($filePath,[($bgSize[0]-$qrcodeSize[0])/2,($bgSize[1]-$qrcodeSize[1])/2]);
  784. // $handle->save($savePath,"jpg",80);
  785. // $qiniu = new Qiniu;
  786. // $img_url = $qiniu->updateFile('img', $savePath, $savePath);
  787. // if (empty($img_url['url'])) {
  788. // return ["code"=>-1,"msg"=>"文件报错失败:".$qiniu->getError()];
  789. // }
  790. // @unlink($filePath);
  791. // @unlink($savePath);
  792. // return ["code"=>1,"url"=>str_replace("\\", "/", $img_url['url'])];
  793. // }
  794. //
  795. // public function checkImgPath(){
  796. //
  797. // }
  798. /**
  799. * 图片合成
  800. * @param type $bg
  801. * @param type $qrcode
  802. * @param type $savePath
  803. */
  804. public function createPosterImg($bg,$qrcode,$savePath){
  805. }
  806. /**
  807. * 获取小程序码
  808. * @param Request $request
  809. */
  810. public function getWxmpQrcode(Request $request){
  811. $weixinA = new weixina();
  812. $data = $weixinA->getUnlimitedQRCode("pages/index/index","a=1");
  813. if(empty($data)){
  814. return app('json')->fail("小程序码获取失败".$weixinA->error);
  815. }
  816. $base64 = 'data:'.$data['contentType'].';base64,'.base64_encode($data['buffer']);
  817. $res = $this->uploadImageBase64("wximg",$base64);
  818. if($res["code"]!=1){
  819. return app('json')->fail($res["msg"]);
  820. }
  821. return app('json')->success(["img"=>$res["data"]]);
  822. }
  823. /**
  824. *
  825. * @param Request $request
  826. */
  827. public function uploadBase64(Request $request){
  828. [$img,$code] = UtilService::getMore([
  829. ['img', '','empty',"请上传图片"],
  830. ['code', 'image'],
  831. ], $request,true);
  832. // $imgAr = explode("base64,",$img);
  833. // if(empty($imgAr)){
  834. // return app("json")->fail("请上传base64图片");
  835. // }
  836. // $imgBase64 = count($imgAr)==1?$imgAr[0]:$imgAr[1];
  837. // //判断字符串是否经过编码方法
  838. // if($imgBase64!=base64_encode(base64_decode($imgBase64))){
  839. // return app("json")->fail("请上传base64图片");
  840. // }
  841. // $base64 = "data:application/octet-stream;base64,".$imgBase64;//七牛
  842. $res = $this->uploadImageBase64($code,$img);
  843. if($res["code"]!=1){
  844. return app('json')->fail($res["msg"]);
  845. }
  846. return app('json')->success(["img"=>$res["data"]]);
  847. }
  848. /**
  849. * 图片上传
  850. * @param Request $request
  851. * @return type
  852. */
  853. public function upload(Request $request){
  854. $uploadConfig = config('filesystem');
  855. $sysData = (new SysModel())->where("id",1)->find();
  856. $file = $request->file('file');
  857. $code = $request->post("code","image");
  858. if(empty($file)) {
  859. return app('json')->fail("未上传文件");
  860. }
  861. $size = $file->getSize();
  862. if(!empty($size) && $size>$uploadConfig["image"]["size"]*1024*1024){
  863. return app('json')->fail("图片不能超过{$uploadConfig["image"]["size"]}M");
  864. }
  865. if(!in_array($code, $uploadConfig['image']['path'])){
  866. return app('json')->fail("上传路径错误");
  867. }
  868. $ext = $file->extension();
  869. if(!in_array($ext, $uploadConfig['image']['ext'])){
  870. return app('json')->fail("图片类型错误");
  871. }
  872. $upPath = \think\facade\Filesystem::disk('resource')->putFile( $code, $file);
  873. if(!$upPath){
  874. return app('json')->fail("上传失败01");
  875. }
  876. $savePath = $sysData['system_url'].'/resource/' . $upPath;
  877. $imgUrl = str_replace("\\", "/", $savePath);
  878. return app('json')->success(['img'=>$imgUrl,'size'=>$size]);
  879. }
  880. /**
  881. * 视频上传
  882. * @param Request $request
  883. * @return type
  884. */
  885. public function uploadVideo(Request $request){
  886. $uploadConfig = config('filesystem');
  887. $sysData = (new SysModel())->where("id",1)->find();
  888. $file = $request->file('file');
  889. $code = $request->post("code","video");
  890. if(empty($file)) {
  891. return app('json')->fail("未上传文件");
  892. }
  893. if(!in_array($code, $uploadConfig['video']['path'])){
  894. return app('json')->fail("上传路径错误");
  895. }
  896. $ext = $file->extension();
  897. if(!in_array($ext, $uploadConfig['video']['ext'])){
  898. return app('json')->fail("视频类型错误");
  899. }
  900. $upPath = \think\facade\Filesystem::disk('resource')->putFile( $code, $file);
  901. if(!$upPath){
  902. return app('json')->fail("上传失败01");
  903. }
  904. $savePath = $sysData['system_url'].'/resource/' . $upPath;
  905. $imgUrl = str_replace("\\", "/", $savePath);
  906. return app('json')->success(['video'=>$imgUrl]);
  907. }
  908. /**
  909. * base64文件上传
  910. * @param type $code
  911. * @param type $base64
  912. */
  913. public function uploadImageBase64($code,$base64,$isQiniu=0){
  914. $sysData = (new SysModel())->where("id",1)->find();
  915. $uploadConfig = config('filesystem');
  916. //验证base64格式
  917. preg_match('/^(data:\s*image\/(\w+);base64,)/',$base64, $result);
  918. if(!$result){
  919. return ["code"=>-1,"msg"=>"base64格式格式错误"];
  920. }
  921. //验证图片后缀
  922. if (!in_array($result[2], $uploadConfig['image']['ext'], true)) {
  923. return ["code"=>-1,"msg"=>"不支持的图片格式"];
  924. }
  925. $rootPath = config('filesystem.disks.resource.root');
  926. $hashName = $code.DIRECTORY_SEPARATOR.date('Ymd') . DIRECTORY_SEPARATOR . md5((string) microtime(true)).".".$result[2];
  927. $filePath = $rootPath. DIRECTORY_SEPARATOR .$hashName;
  928. $path = dirname($filePath);
  929. // 检测目录
  930. if (!is_dir($path)) {
  931. if (!mkdir($path, 0777, true)) {
  932. return ["code"=>-1,"msg"=>"生成目录失败"];
  933. }
  934. return ["code"=>-1,"msg"=>"上传目录不存在"];
  935. }
  936. //重名文件验证
  937. if (is_file($filePath)) {
  938. return ["code"=>-1,"msg"=>"文件已存在"];
  939. }
  940. if(!file_put_contents($filePath, base64_decode(str_replace($result[1], '', $base64)))){
  941. return ["code"=>-1,"msg"=>"文件报错失败"];
  942. }
  943. //七牛上传
  944. if($isQiniu==1){
  945. $qiniu = new Qiniu;
  946. $img_url = $qiniu->updateFile('img', $filePath, $filePath);
  947. if (empty($img_url['url'])) {
  948. return ["code"=>-1,"msg"=>"文件报错失败:".$qiniu->getError()];
  949. }
  950. @unlink($filePath);
  951. return ["code"=>1,"url"=>str_replace("\\", "/", $img_url['url'])];
  952. }
  953. $savePath = $sysData['system_url'].config('filesystem.disks.resource.url').DIRECTORY_SEPARATOR.$hashName;
  954. return ["code"=>1,"url"=>str_replace("\\", "/", $savePath)];
  955. }
  956. /**
  957. * 七牛上传图片
  958. * @param Request $request
  959. */
  960. public function qiniuUpload(Request $request)
  961. {
  962. $file = $request->file('file');
  963. if (empty($file)) {
  964. return app('json')->fail("未上传文件");
  965. }
  966. $rootTmp = config('filesystem.disks.local.root') . '/' . \think\facade\Filesystem::putFile('tmp', $file);
  967. $image_size = @getimagesize($rootTmp);
  968. if ($image_size[0] > 1000) {
  969. $imgS = Image::open($rootTmp);
  970. $imgS->thumb(1000, $image_size[1]);
  971. $imgS->save($rootTmp);
  972. } else {
  973. if ($image_size[1] > 1000) {
  974. $imgS = Image::open($rootTmp);
  975. $imgS->thumb($image_size[0], 1000);
  976. $imgS->save($rootTmp);
  977. }
  978. }
  979. $qiniu = new Qiniu;
  980. $img_url = $qiniu->updateFile('img', $rootTmp, $rootTmp);
  981. if (empty($img_url['url'])) {
  982. return app('json')->fail($qiniu->getError());
  983. }
  984. @unlink($rootTmp);
  985. return app('json')->success(['img' => $img_url['url']]);
  986. }
  987. /**
  988. * 七牛上传token
  989. * @param Request $request
  990. */
  991. public function qiniuUploadToken(Request $request){
  992. [$bucket] = UtilService::getMore([
  993. ['bucket', ''],
  994. ], $request,true);
  995. $qiniu = new Qiniu;
  996. $token = $qiniu->createUploadToken($bucket);
  997. return app('json')->success(['token' => $token]);
  998. }
  999. /**
  1000. * 获取用户模板信息
  1001. * @param int $uid 用户ID
  1002. * @return array
  1003. */
  1004. private function getUserInfo($uid)
  1005. {
  1006. $userInfo = (new UserModel)->where('uid', $uid)->find();
  1007. $auth = (new InfoAudit)->where('uid', $uid)->find();
  1008. $user_work_type_title = (new UserWorkType)->where('id', $auth['user_work_type_id'])->find();
  1009. if ($auth) {
  1010. $auth_info = $auth->toArray();
  1011. } else {
  1012. $auth_info = null;
  1013. }
  1014. return [
  1015. 'is_type_audit' => $auth && $auth['status'] == 1 ? 1 : 0,
  1016. 'ancestral_place' => $auth ? $auth['ancestral_place'] : '',
  1017. 'auth_info' => $auth_info,
  1018. 'user_work_type_id' => $user_work_type_title['title'],
  1019. ];
  1020. }
  1021. }